nos_
ENRU
Вся документация

Как это устроено

Гипервизор

docs/hypervisor.mdОткрыть на GitHub

Эта страница пока есть только на английском: документация собирается прямо из каталога docs/ репозитория и поэтому всегда совпадает с кодом. На русском у нас есть руководства.

A type-1 hypervisor for nos, written as Rust crates and loaded into a running kernel as a module:

$ insmod /hv.ko
module: hv loaded at 0xFFFF800031000000
$ hv info
hv: AMD-V (SVM) -- ready
  cpu                  AuthenticAMD, itself under a hypervisor
  revision             1, 16 ASIDs
  nested paging        yes  -- guest physical addresses translated by the CPU
  next-RIP save        no   -- where an intercepted instruction ends
  decode assists       no
  flush by ASID        no
  VMCB clean bits      no
  virtual VMSAVE       no
  virtual GIF          yes
  AVIC                 no
  pause filter         no
  SVM lock             no
  x2APIC               yes  -- the host's; a guest's is MSR exits either way
  2 MiB nested pages   yes  -- a guest's memory from the huge pool a block an entry
  1 GiB pages          yes  -- guest memory in one nested entry a gigabyte
  huge pool            none -- hugepages= not given: a guest's memory is 4 KiB frames
hv: AMD-V (SVM) on for cpu none of 0-3
$ hv on
hv: turned on for cpu 0-3
hv: AMD-V (SVM) on for cpu 0-3 of 0-3
$ hv run hypercall 2
hv: guest hypercall -- memory above 4 GiB through its own page table, then every register across a hypercall
  ran on     cpu 2, 634 us
  said       "nos: long mode"
  exits      0 port in, 14 port out, 0 cpuid, 1 hypercall, 0 host interrupt
  stopped    hlt at 0x812b
  checked    guest physical 4 GiB holds what it wrote; 15 registers went out at the hypercall and 15 answers came back
hv: guest hypercall ok
$ rmmod hv
module: hv unloaded

This is stage 3 of the roadmap, and all four of its steps are here: the machine's virtualization extension, found, reported, and turned on and off for the CPUs that will run guests; a VM -- guest memory behind a nested page table, one CPU under AMD-V, its exits decoded -- that runs guests of a few bytes in long mode and checks that each did what it was told; and, over an emulated 8250, PIT, RTC and 8259 PIC, a real Linux bzImage booted to an interactive BusyBox shell (hv boot, and A Linux guest below).

Why a module

Nothing about a hypervisor has to be in the kernel image, and three things argue for keeping it out.

A machine that runs no guests should carry none of it. Not the code, and above all not the CPU state: EFER.SVME and MSR_VM_HSAVE_PA on AMD, CR4.VMXE and VMX root operation on Intel are the CPU's, not a task's, and a kernel that never runs a guest has no business touching them. Loaded, the module turns them on; unloaded, it turns them off, and the machine is in the state it booted in.

It is the subsystem least pleasant to debug by rebooting. insmod, try it, rmmod, change one field, insmod again is a loop of seconds; VMCB and VMCS setup is where most of the time in this stage goes (plans/03-hypervisor.md says so), and a rebuild-and-boot loop would spend that time twice over.

Unloading is a gate of its own. A hypervisor that can be taken out has to prove, every time, that it turned the extension off before its code was freed -- and the check for that is the same check live update (stage 5) will need, years earlier than it would otherwise be written. tests/hv-test.py loads, turns it on for every CPU, unloads without turning it off, and loads again to ask every CPU what it has. If the first unload left anything on, the second load says so.

What it costs is stated in Loadable modules: a module cannot register a block device or a NIC, because those register with their layer as Rust trait objects from inside the image and there is no C name for a module to bind. That is a limit on how a guest's virtual devices will be served, not on the hypervisor: a guest's disks and NICs are emulated by this module over the kernel's own (kcore::block::Disk, kcore::net::Nic), which is what a hypervisor wants anyway.

The crates

hvarch/              the CPU's extension: the instructions, the control MSRs,
                     the structures the hardware reads -- the VMCB, laid out
                     in x86/svm/vmcb.rs -- and entering a guest. All the
                     unsafe.
hv/                  everything else: the machine (machine.rs), guest memory
                     and its nested page table (memory.rs, npt.rs), the
                     VMCB as this hypervisor fills it in and the exits it
                     comes back with (svm.rs), the VM (vm.rs), and the
                     built-in guests (guests.rs).
modules/hypervisor/hv/          the module: the shell command, the task a guest's CPU
                     runs on, and the lifetime of it all.

hv and hvarch are workspace members but not default members: a plain cargo build, and so the kernel's own build, does not compile them. They exist only inside hv.ko. A kernel built without the module has no hypervisor in it at all -- not a symbol.

The split is the point, and it is measurable:

$ scripts/unsafe-count.py hv hvarch
hv        26087 lines     4 blocks    0 unsafe fn    0 unsafe impl  = 4
hvarch     8362 lines   197 blocks   46 unsafe fn    1 unsafe impl  = 244

The long-term goal of this kernel is other people's Linux guests on this machine, and the bug class that goal cannot survive is a guest reaching host memory. So the line is drawn once, in the crate graph, where a script can count it rather than a reviewer having to remember it. The four sites in hv are the two calls into hvarch from the IPI handlers that turn the extension on and off (machine.rs), and the call that enters a guest, one per backend (svm.rs, vmx.rs), whose two preconditions are invariants of types in hv rather than promises at the call: guest memory owns every page its nested table maps, and the machine never names a host save area that has been freed. Guest memory, the nested page tables, the policy, the decoders, the emulated devices and the run loop -- the rest of its twenty-six thousand lines -- have none.

AMD-V first, Intel VT-x second

The order is decided by where the code is iterated on, not by the hardware.

QEMU's TCG emulates SVM, nested paging included, and emulates no VMX at all. On the development machine -- a Mac, where the x86 kernel runs under TCG -- AMD-V is the only extension under which a guest can be brought up at all. It is also the simpler of the two: the VMCB is a plain structure in memory, where VMX needs vmread/vmwrite for every field, and a VM-entry failure there reports itself through one error number that means a dozen things.

What QEMU gives, and what it does not, is worth knowing before debugging against it:

$ qemu-system-x86_64 -cpu max ...
svm yes   npt yes   vgif yes   x2apic yes (10.2; 8.2 has none)
nrip-save no   decodeassists no   flushbyasid no   v-vmsave-vmload no   vmx no

Before QEMU 9.2, TCG does not put a guest with paging off through the nested page table. get_physical_address (target/i386/tcg/.../excp_helper.c) translates through stage 2 only from inside a guest page-table walk; with CR0.PG clear it takes the guest physical address for a host physical one, and the guest runs out of the host's memory. 9.2 fixed it (env->cr[0] & CR0_PG_MASK || use_stage2). It was found here: the first real-mode guests all stopped at the same #UD with the same registers whatever their code was, and the fault guest's write past its memory did not fault. Real hardware has no such hole, but the development host's QEMU is 8.2 and the build container's 6.2, so every built-in guest starts in long mode with paging on -- which is how a 64-bit Linux kernel is started anyway.

Two of those absences matter. Without nrip-save the hypervisor has to work out for itself where an intercepted instruction ended -- which is a short table of lengths (cpuid is 2 bytes, vmmcall 3, rdmsr/wrmsr 2), not an instruction decoder, because every instruction that is intercepted on purpose is one whose length is known; and an IOIO intercept hands over the next instruction's address in the VMCB regardless. Without decodeassists the same holds for the rest. Both are present on real AMD parts.

Use -cpu max. The default qemu64 model reports SVM without nested paging, and a hypervisor that will not walk the guest's page tables itself -- this one, deliberately -- has no use for that.

Intel VT-x is written for the hardware this kernel actually runs on: the Hetzner EX44 and the Dell laptop are both Intel, where it is native and fast. It is the whole of a backend now -- the VMCS, EPT, the launch stub and the exit decoder -- and every built-in guest runs under it, brought up and debugged under nested KVM on the Intel dev box (below). TCG has no VMX at all, so the gate uses KVM there; on an AMD host -cpu host gives AMD-V, and under TCG anywhere -cpu max gives AMD-V, so the two backends are covered between the three.

One bit stands between this kernel and vmxon on those machines, and it is not in the hypervisor. VMX operation requires CR0.NE (bit 5; it is in IA32_VMX_CR0_FIXED0 on every Intel part), and nos never sets it. The APs come out of INIT with CR0 = 0x60000010, NE clear, and the boot path adds PE and PG (boot64.asm) and WP (enable_wx_support) and nothing else; the BSP has whatever GRUB and the firmware left, which Multiboot2 calls undefined. vmxon does not fail on that -- it faults, and this kernel panics on a #GP -- so vmx::enable checks the fixed bits on each CPU before it, the error is HostState, hv on names the CPU that refused, and hv info names the bit:

  host CR0/CR4         no   -- on this CPU vmxon would fault: CR0 needs NE

The check is per CPU and not part of the machine-wide verdict, because the registers are per CPU: a verdict that changed with the CPU insmod happened to run on would be no verdict. The fix is one bit on every CPU, beside where enable_wx_support sets WP -- what every other x86-64 kernel does. NE chooses native #MF over the PC's FERR#/IRQ 13 for x87 errors, and this kernel has no x87 code to raise one: the C++ is built with -mno-80387, so there is no x87 instruction in the image and none can appear, and the Rust targets are soft-float. It is still a change to how every x86 machine boots, the two whose only console is the network among them, so it came with the VMX backend, where a guest shows it working -- boot64.asm's enable_paging sets NE beside where it clears CD/NW after INIT, on the BSP and every AP, and hv info reads host CR0/CR4 yes on each.

The VMX backend, and where it differs from AMD-V

The two backends are one shape above hvarch: hv::vm::Backend is Svm or Vmx, and the run loop and the built-in guests call it without an svm or a vmx in them. The guest state both keep is the AMD save-area layout (vmcb::Save plus the general registers) -- for VMX a shadow, since the real state lives in the VMCS and is reached only through vmread/vmwrite. Guest::run in hvarch::x86::vmx syncs the shadow into the VMCS before an entry and reads it back after, so the policy above -- CPUID, MSRs, the loader -- is written once.

That sync is lazy, and has to be: a VMCS holds sixty-odd fields, and eight segments of four fields each are most of them, so a full round-trip every exit is sixty vmread/vmwrite -- and under a nested hypervisor, where each one traps to the L0 kernel, that is most of the cost of running the guest. But the guest owns nearly all of it: CR0/3/4, the segments, GDTR/IDTR, RSP, RFLAGS it changes in the VMCS itself, with no exit (no CR or segment interception), so the shadow need not carry them at all. The first entry writes the whole state; after that only what the policy changes between entries goes in -- RIP past an instruction, the system MSRs, the injected event -- and only what it reads comes back: where the guest stopped, its flags, and FS/GS base, which it does change through an intercepted wrmsr (the per-CPU base, as this kernel keeps its own) as well as un-intercepted. The control registers and segments are read only when a guest is being stopped and dumped. A full sync every exit was ten times the work, and turned a real distribution's boot from seconds into minutes. An EPT violation, which is mostly an MMIO access performed for the guest (MMIO), reads what performing it takes and no more: CR0, CR3 and CR4 for the walk to its instruction, CS's rights for the mode (and CS's base outside 64-bit code), RSP, the CPL. One that ends the guest after all has the rest read for its report while the VMCS is still current on that CPU (Guest::read_whole_state), and a report that could not read it says so, rather than show the shadow's older values as the guest's.

And within the light set it is dirty-tracked: Guest keeps what the VMCS last had of each field it may write between entries (Synced) and writes only what the policy changed -- RIP after a skip, the interruptibility a skip clears, a system MSR after a wrmsr, the interrupt-window control when it toggles, the injected event when there is one (the CPU clears the field's valid bit as it takes the event, so with none there is nothing to write). That is exact for every field the guest cannot change without an exit. The FS and GS bases it can -- wrfsbase, swapgs -- so a copy older than the last exit must never be written back (Alpine wedged on exactly that once): they are read on the exits where the policy may touch them, rdmsr and wrmsr, and what it leaves is compared with that read alone. On the way out the exit reason is read first and the rest by reason: the host's interrupt needs nothing more, an instruction its length, port I/O its qualification too, and only an exit that may have happened during an event's delivery -- an exception, an EPT violation -- or one nobody foresaw reads the interruption and vectoring words and the guest-physical address. Twelve vmwrites and fourteen vmreads an exit became one or two and four.

The differences that are not hidden by the shadow at all:

  • The VMCS is opaque, and per CPU. It is made as plain memory (a privileged instruction at construction would fault, since a VM is made where VMX may be off and on a CPU that will not run the guest); the first entry vmclears it once, where VMX is known on, into the clear launch state vmlaunch needs. From there the VMCS is left current after an exit, not vmcleared, and the next entry on the same CPU is a vmresume, which does not reload it -- 8.6% fewer nanoseconds an exit under nested KVM (18.6 -> 17.0 µs, hv bench exits=50000 on the Intel dev box), where a vmclear flushes the whole shadow VMCS, and proportionally more on real silicon, where it is a memory flush the earlier per-exit vmclear paid every time. The one invariant a resume needs is that a VMCS is never current on two CPUs at once, kept two ways: before a guest's task runs on another CPU its VMCS is vmcleared off the old one, and when a guest is dropped its VMCS is vmcleared off its CPU before the page is freed -- each a vmclear run on that CPU by an IPI sent from task context, never with interrupts off, that waits for the CPU to answer. Without the drop one a freed VMCS page would take a vmptrld's write of cached state on that CPU's next entry; the migration one is a safety net, since a guest's task is pinned to one CPU and does not in fact move. Nested KVM will vmlaunch an uncleared VMCS, so the first-entry vmclear and this whole ordering are for the hardware, not the gate. (The AMD VMCB is plain memory and had none of this to arrange.)
  • Host state is the hypervisor's to save. AMD-V's vmsave/vmload move the host's segments and MSRs around vmrun; VMX restores the host from the VMCS host area, which HostRegs::capture fills on the CPU the entry runs on -- its CR3, its GS base (where its per-CPU data is), its TR, its GDTR and IDTR, and the host's five syscall MSRs into the exit MSR-load list (five rdmsrs, and under nested KVM four exits to it, that were paid on every entry before). Rewritten when the guest's task has moved CPU, not every entry -- and only then is the VMCS vmptrlded: each CPU remembers which VMCS is current on it (CURRENT_VMCS, kept exact by the VMPTRLD, VMCLEAR and VMXOFF that are the only things to change it), and an entry whose VMCS is current already skips the instruction. The CR4 the exit loads back from the host area has to be the one an entry runs under, with OSFXSR and OSXSAVE: captured without OSFXSR -- as it once was, the bit set around each entry and captured before -- the FXSAVE after the exit could leave the XMM registers out and the XSETBV after it was an undefined opcode. Now both bits are the CPU's for as long as VMX is on for it (below), and the capture is right by construction.
  • The host's NMI is delivered by hand. Under AMD-V an intercepted NMI stays pending until stgi and the host takes it then; under VT-x the exit is its delivery -- the NMI is consumed, and NMIs stay blocked until an IRET. So an NMI exit ends with int 2 into the host's own handler, whose IRET unblocks the next, the way #MC is raised with int 0x12 on both sides and the way KVM does it. What would otherwise be lost is the panic path collecting this CPU's stack from another (Cpu N did not answer the NMI, exactly when the backtrace was wanted) and the profiler's counter overflow, after which its LVT stays masked and the profiler is dead on that CPU.
  • CR2 is nobody's on Intel. vmrun keeps a guest CR2 in the VMCB; VMX keeps none, so run saves the host's and restores the guest's around the world switch by hand. The switch of the x87, SSE and AVX registers and XCR0 is the same as AMD-V's -- neither extension switches them -- but that the CPU stops an XSETBV above CPL 0 or without CR4.OSXSAVE itself, before its exit, which the run loop checks again anyway.
  • CR8 is the host's on Intel. In 64-bit mode CR8 is the local APIC's task priority register, and under VT-x a guest's mov cr8 reaches the real one unless told not to: 15 there keeps every interrupt but an NMI off the host's CPU -- the tick, the kick, the IPI a TLB shootdown waits for, which would panic the machine ten seconds later -- for as long as the guest likes, and after it has gone, since the exit restores no TPR. AMD-V gives the guest V_TPR under V_INTR_MASKING and never exits. So the VMX controls stop the guest at every CR8 access (Exit::Cr8), and the policy answers from a shadow TPR of the guest's own, a #GP for a value CR8 cannot hold. The tpr built-in guest checks both backends.
  • CR0's PE and PG are the host's to watch. Every entry checks that the "IA-32e mode guest" control agrees with EFER.LMA and that CR0 is one VMX allows, so a guest that turned paging off or on behind the host's back would fail its next entry. So PE and PG are in CR0's guest/host mask, with NE and the bits VMX fixes: a mov to CR0 or an lmsw that would change one of them exits (Exit::Cr0Write), and the policy does what the CPU would -- a #GP where the architecture has one, EFER.LMA set or cleared as paging goes on or off with LME set, the entry control made to follow at the next entry, and the translations cached under the guest's VPID dropped. Every CPU a start-up IPI starts climbs from real mode this way, which also takes unrestricted guest: a CPU without it runs guests of one CPU only (More than one CPU).
  • An NMI waits for the guest's IRET. One of a guest's CPUs can send another an NMI, and a second must wait until the handler of the first has returned. Under VT-x that is the "virtual NMIs" pin control: the guest's NMI blocking is its own, set as one is injected and ended by its IRET, and the NMI-window exit comes the moment a held one can go in. AMD-V has no such control; it intercepts the IRET instead, whose exit comes before the IRET has run, so the blocking ends once the guest's RIP has moved past it -- what KVM does.
  • The syscall MSRs are switched through load lists. STAR, LSTAR, CSTAR, FMASK and KERNEL_GS_BASE are not VMCS fields, and a guest run with the host's would be catastrophic -- a userspace SYSCALL jumps to the host's LSTAR, and it was exactly this that a real Linux oopsed on at RIP: 0x0 the moment it ran /init, the kernel itself having booted whole in ring 0 without them. AMD-V moves these with vmsave/vmload; VMX has no such instruction, so Guest keeps a VM-entry MSR-load list (the guest's values, from the shadow) and a VM-exit MSR-load list (the host's, off the CPU), and the CPU loads each in turn. KERNEL_GS_BASE needs one more list: swapgs changes it without a wrmsr the host hears, so a VM-exit MSR-store list saves the guest's live value -- otherwise the guest's swapgs-established kernel GS base is lost each round, and the next swapgs returns junk. That was a real distribution kernel double-faulting on a garbage RSP the moment an interrupt returned to user mode; a purpose-built guest that never took one from user mode did not show it. The store list's one entry is the entry-load list's own KERNEL_GS_BASE entry, so what an exit stores is what the next entry loads, whichever path makes it. It was a slot of its own once, copied into the load list by the run loop alone: an exit the world switch answered itself (hvarch::x86::fast: a write of the TSC deadline or of the ICR, a HLT) re-entered with the value of the last full exit, and a guest's swapgs since was undone -- its user GS base came back as its kernel's per-CPU address, which a 64-bit Linux with 64-bit programs never looks at and a 32-bit program's TLS does. With all three lists, an unmodified Linux -- a tinyconfig to a BusyBox shell, and a full Alpine 3.24 to a root login with its clock, apk, disk and network -- runs under VT-x.
  • Controls, and one bitmap. Every port exits by the processor-based controls (unconditional I/O exiting), not by the 12 KiB iopm a VMCB points at; every MSR exits by a 4 KiB bitmap with every bit set but three -- the FS, GS and KERNEL_GS bases, the guest's own and nobody else's, which VT-x saves and loads itself (two VMCS fields, and the exit MSR-store and entry MSR-load lists) and which a Linux guest writes at every context switch: two exits a switch, the most frequent a busy guest made, gone -- on both sides, since the AMD msrpm lets the same three through, the stub's vmsave and vmload carrying them (hvarch::x86::PASSTHROUGH_MSRS is the one list). The rest of AMD-V's intercept set is controls too, since VT-x stops a guest at none of them unasked: CR8 (above), MONITOR, MWAIT and RDPMC, which CPUID says the guest has not got and which run on the host's CPU otherwise; WBINVD, which otherwise writes back and drops the package's whole shared cache -- every core stalled for milliseconds -- as often as the guest cares to; and PAUSE, so that a guest spinning comes out to be handed what is due to it (Time); CPUID, INVD, VMCALL, XSETBV and a triple fault exit unconditionally, and XSAVES is #UD in the guest because the secondary control that would enable it is off. RDTSCP and RDPID, and INVPCID, run in the guest where its CPUID offers them -- enable RDTSCP and enable INVPCID on, where the CPU has them (hvarch::x86::offers) -- and are #UD there otherwise, as on a CPU without them; none of them exits. Each control field is written through adjust, which forces on the bits IA32_VMX_*_CTLS says must be 1 and off the ones it forbids -- a value that ignored them fails entry with nothing named. Guest CR4.VMXE is forced set (the fixed MSRs demand it) and masked to read 0, since the guest is told it has no VMX.
  • A refused entry is the CPU's VMEXIT_INVALID, not a software check. AMD-V's VMCB is checked in software first (Vcpu::check) so a bad one is named before the CPU sees it; VMX has no such check -- a bad guest state is the CPU's to refuse, at vmlaunch, reported as an entry failure and shown as Exit::Invalid with the instruction error. Both an outright VMfail and a VM-entry failure exit keep the VMCS's entry/exit/pin/processor controls, their invalid bits against the CPU's capability MSRs, the MSR-load fields, VTPR/TPR threshold and the entry MSRs in the stopped vCPU's dump. The snapshot is taken before VMCLEAR, so it survives the failed VMCS becoming non-current; the refused guest checks that the dump contains it. An event an exit interrupted the delivery of is given back rebuilt from its vector, type and error code, not copied: bit 12 of what the exit wrote is undefined, and the entry field wants bits 30:12 clear.
  • VPIDs, and INVEPT and INVVPID once per CPU a guest runs on. A VPID is VT-x's ASID: the tag the TLB keeps a guest's linear and combined mappings under, so that a VM entry or exit need drop neither the guest's nor the host's, which are tagged 0. Without one -- as the backend first ran -- every transition dropped both, the host's included: every exit cost the host its translations, as every AMD-V entry did before ASIDs (-22% to -34% of an exit on the AX41). Here a VPID is the guest's for its life, the lowest free one from a lock-free bitmap of 65535 (vpid_take), given back when the guest is dropped; AMD's ASIDs are per CPU and per generation, and the third VM of the asid built-in guest, under VT-x, is checked to have been given a VPID one of the first two had. What must then never happen is a number's translations from an earlier holder served to the next: a guest's first entry on each CPU runs a single-context INVVPID for its number, and enable an all-context one after vmxon, for what an earlier load's guests left. EPT has the same hazard one level down: guest-physical mappings, the EPT's own translations, which the CPU tags with the EPT's address and keeps across transitions and across VMXOFF and VMXON. A guest destroyed frees its EPT; the next guest's EPT is likely made in the same page (the allocator hands back what it was last given), so its tag is the old one's, and the CPU would serve the old guest's translations -- to pages that are the host's again -- for the new guest's addresses, which are the same low addresses every kernel touches first. Nested KVM keeps its own shadow EPT and shows none of this. So enable follows vmxon with an all-context INVEPT, dropping what an earlier load's guests left, and a guest's first entry on each CPU (the moment its host state is captured there) is preceded by a single-context INVEPT for its EPT -- once per CPU per guest, which costs nothing, and after which the only translations under that tag are this guest's, an EPT that only grows never making a stale one. usable requires the instruction. This is the counterpart of the AMD side's ASID generations, which begin run out at every load for the same reason.

The hypercall built-in guest is the one whose machine code is a vendor's: vmmcall (0F 01 D9) is AMD's and an invalid opcode on Intel, so the loader patches it to vmcall (0F 01 C1) where the guest runs under VT-x. The refused and asid guests test AMD-only mechanisms, and each has a VMX form that tests the Intel equivalent -- the CPU refusing a non-canonical guest RIP, and three VMs isolated by their EPTs; tpr runs unchanged, and is stopped twice under VT-x and not at all under AMD-V.

What AMD-V's entry keeps whatever the VMCB says, hvarch::x86::vmx::Guest keeps whatever the policy asked -- its own way, since VT-x's controls are not AMD-V's intercepts:

  • CR4.MCE is the host's. The CR4 guest/host mask holds MCE and VMXE whatever hv asks, and every bit hv does not let the guest own (Guest::new's cr4_own: VME, PVI, TSD, DE, PSE, PAE, PGE, PCE, OSFXSR and OSXMMEXCPT, where its CPUID offers them): the VMCS's CR4 keeps MCE set and the guest reads the read shadow's. A mov to CR4 that changes a bit of the mask exits, naming its register and length, and crate::cr performs it from there -- a bit its CPUID does not offer the #GP a CPU without the feature gives, so PKE stays the guest's to have only where PKU is offered, its PKRU switched with it -- and writes the register and the shadow at the next entry. A read never exits, the shadow answering it, and a write of the guest's own bits never does either: Linux's global TLB flush turns PGE over twice, with no exit, where AMD-V stops every mov of CR4. PAE cleared in long mode is then the CPU's own #GP.
  • The debug registers are the guest's. Every mov of one exits ("MOV-DR exiting"), named by the exit -- register, direction, general-purpose register -- and crate::dr answers it: DR0-3 from four of the guest's own, made the CPU's before each entry through the same per-CPU record AMD-V uses (svm::LoadedDebugAddrs); DR6 from the guest's own, which is no VMCS field and is never put in the register -- every read of it exits -- and DR7 the VMCS's, which "load debug controls" puts in the register at the entry and the exit takes back out, leaving the host's with all four off. DR4 and DR5 are DR6 and DR7 again, or a #UD under CR4.DE; a mov above CPL 0 the #GP, under general detect the #DB, and a DR6 or DR7 written with a bit above 31 the #GP, which the exit comes before the CPU's check of.
  • A #DB of the guest's own goes back to it. VT-x writes no DR6 at a #DB that exits -- the exit qualification has what it would have written -- so the exit puts it into the guest's DR6 as the CPU would have (B0-B3 cleared first, RTM's bit the other way up; KVM's kvm_deliver_exception_payload), and the run loop gives the #DB back with GD cleared from DR7, as a CPU entering the handler clears it; a single step taken out of a STI or MOV SS shadow with TF set is marked pending, which the CPU does at every exit but this one and the entry checks. ICEBP's #DB exits at the instruction, as a privileged software exception: stepped past, and its #DB given as the trap it is, as AMD-V's intercept of it is.
  • The controls the host needs are required. adjust drops a control the CPU -- or a hypervisor under this one -- does not allow; one the host cannot do without dropped refuses the guest, naming the field and the bits (Refusal::Controls): the exits for its interrupts and NMIs, its ports, CR8, MONITOR, MWAIT, RDPMC, every mov of a debug register and WBINVD, nested paging, the 64-bit host, the switch of EFER, the PAT and DR7 -- and what the guest was promised, unrestricted guest and its VPID. A guest run without one of them would be the host's to lose.
  • The world switch keeps a guest's speculation off the host (hvarch::x86::spec), what CPUID and IA32_ARCH_CAPABILITIES say decided for each CPU as the extension is turned on there, with KVM's as the reference: after every exit the guest's values cleared out of every register the stub returns with and the return stack refilled before its first ret, as AMD-V's stub does; an IBPB between two guest CPUs on a CPU; IBRS in IA32_SPEC_CTRL while the extension is on -- enhanced, set once, on the EX44, and legacy, a barrier only when written, written again after every exit on a CPU without it (Skylake) -- with BHI_DIS_S beside it where the CPU has the control; VERW, the CPU's buffers cleared, the last thing before every entry where MDS, TAA or RFDS apply (the EX44's E-cores have RFDS); and the L1 data cache flushed before every entry where L1TF lets a guest read it (Skylake). A guest's own SPEC_CTRL goes over the host's for its run, and the host's alone is written back after the exit -- by the stub, for legacy IBRS. hv says which of them the CPU it runs on has, and reads every CPU's IA32_SPEC_CTRL back, warning where it is not what the host runs with there. What each costs an exit on the EX44 is in What an exit costs.

What the VMX backend does not do yet, and says so rather than pretends:

  • Branch history cleared by hand. A CPU with enhanced IBRS that is open to branch history injection and has no BHI_DIS_S -- Ice Lake, Tiger Lake, or an Alder Lake and later under a hypervisor that does not pass the control through, as QEMU 8.2's -cpu host does not -- wants the software sequence that clears the history at every exit; hv names such a CPU instead. None of the three machines here is one.

What it does today

hv                          what the machine has, and which CPUs it is on for
hv info                     the whole of what the CPU said, a line a feature
hv on [cpu|all]             turn the extension on
hv off [cpu|all]            turn it off
hv run <guest|all> [cpu]    run a built-in guest, or all of them, on a
                            task of its own -- bound to cpu, or to one
hv boot <kernel> [firmware] [mem=MiB] [cpus=N] [secs=N] [cpu=N] [xapic] [ioapic] [apicv|noapicv] [rxmod=US] [nooffload] [initrd=path] [disk=path[:ro]]... [input=...] [cmdline=...]
                            load a Linux bzImage -- or a PVH ELF, such as
                            hvboot, which boots the guest's own kernel
                            -- and run it on a vCPU -- on cpus of them,
                            each on a host CPU of its own -- for secs,
                            then print its console and how it ended
hv start <kernel> [firmware] [mem=MiB] [cpus=N] [cpu=N] [node=N] [xapic] [ioapic] [apicv|noapicv] [rxmod=US] [nooffload] [initrd=path] [disk=path[:ro]]... [input=...] [log] [restart] [net] [cmdline=...]
                            the same, left running until it is stopped;
                            restart boots it again when it resets itself
hv list                     the started guests: running or how they ended,
                            their CPU, uptime, restarts and exits
hv console <id> [bytes=N]   the end of one's console
hv attach <id>              its console, live and typed at, over ssh -t;
                            ^] detaches
hv send <id> <text>         type at it, \n or \r for Enter
hv exec <id> [secs=N] <line>
                            type a line, print what comes back up to the
                            prompt after it
hv wait <id> [secs=N] [boot=N] <text>
                            until this boot's console shows text -- with
                            boot=N, once it has restarted N times -- or it
                            stops
hv restart <id>             boot it again from its files, running or stopped
hv stop <id|all> [secs=N]   press its power button and give it secs (30)
                            to turn itself off, pressed again every 15 s
                            while it runs, then stop it; say how it
                            ended, take it off the list -- as rmmod and
                            nos's poweroff and reboot stop all of them,
                            given insmod's stop_secs= (120)
hv forward [add <port> <vm> <guest-port> | del <port>]
                            a port of nos's relayed to a guest's
hv help                     all of these, a line each

CloudHv firmware guests are selected by firmware on hv boot, hv start or hv create, or by firmware = true in vm.toml. With no kernel path this selects /lib/CLOUDHV.fd; an explicit PVH ELF path after the same flag is useful for the DEBUG build. The firmware is entered by the existing PVH loader, but its machine has CloudHv's 8086:0D57 host bridge, CF8/CFC without ECAM, and xAPIC plus an IO-APIC even for one vCPU. Ordinary Linux guests remain Q35. Host-function pci= is not available on this machine. Save, restore and migration carry its host bridge and, where selected, Hyper-V's shared and per-vCPU state in version 5 of the VM state, so it cannot come back as Q35; versions 1 through 4 remain readable.

hyperv on the same commands, or hyperv = true in vm.toml, selects Microsoft's Hv#1 interface for a firmware guest. It is refused for an ordinary Q35 guest, whose KVM interface is unchanged. The implementation provides the Microsoft CPUID range through 0x40000005, GUEST_OS_ID, HYPERCALL and per-vCPU VP_INDEX, a read-only hypercall page with the vendor's opcode, reference time, SynIC and synthetic timers, virtual APIC MSRs and VP-assist EOI, and TLB-flush and synthetic-IPI hypercalls. An unknown hypercall gets HV_STATUS_INVALID_HYPERCALL_CODE.

hv boot firmware mem=64
hv create shell firmware
hv start shell

With a bootable EFI System partition on its virtio disk, the firmware runs its \EFI\BOOT\BOOTX64.EFI rather than extracting a kernel on the host. On the EX44's VT-x this reaches the UEFI Shell and automatically boots Ubuntu 24.04.5 through its own shim and GRUB to a login with EFI runtime services; virtio-blk's large-request path below is what EDK2's disk driver uses. hv exec recognizes the Shell> prompt as well as Linux's # and $ ; end a UEFI command with \r, as in hv exec shell echo hello\r, since the Shell echoes LF but executes on CR. hv-test.py drives this path through Boot Manager on every x86-64 run.

Turning it on allocates one page per CPU -- AMD's host state save area, Intel's VMXON region -- and then sends that CPU an IPI that does nothing but write MSRs. The page is allocated before the IPI and never inside it: a page allocation shoots down every other CPU's TLB and waits for every CPU to answer, and a CPU inside an interrupt handler has interrupts off and cannot (the spinlock rule in CLAUDE.md).

The status line asks the CPUs, not the module. hv sends each CPU an IPI that reads EFER or CR4 and reports what came back, and says so loudly if that disagrees with what the module thinks it turned on. Nothing else in this kernel touches those bits, so a disagreement can only be a bug here -- and it is exactly the kind that is invisible to code that reads only its own bookkeeping.

Turning it off checks first, on the CPU itself. vmxoff on a CPU that is not in root operation is an undefined-opcode fault, and this kernel's handler panics; so the IPI handler reads the register and acts on what it finds. That also makes hv off the way back from a CPU some earlier load left the extension on for -- the page it was using is gone, but turning it off needs no page. And on Intel it checks one thing more: that no guest's VMCS is current on the CPU. A VMCS is left current after an exit (the next entry resumes it), and VMXOFF under one leaves the CPU's cached copy of it nowhere good -- the manual wants every active VMCS vmcleared first -- so hvarch counts the VMCSs current on each CPU, up where one is made current and down where it is cleared off, and vmxoff is refused while the count is not zero: the CPU stays on, keeps its page, and hv off names it (a guest's VMCS is still current on cpu 3 -- left on; stop the guest first). The CPU clears its own slot in the host-area table as it goes off, in the same IPI, so there is no moment at which an entry is turned away from a CPU that then stays on. rmmod never meets this: it drops every guest before it turns anything off, and a dropped guest's VMCS is current nowhere.

A guest

A VM is guest memory behind a nested page table, the permission maps it runs under, and one CPU (hv::vm::Vm) -- or, for a Linux guest, as many as it is given (More than one CPU). A guest's CPU is a task: hv run spawns one, bound to the CPU asked for -- or, asked for none, to the one it runs on, so that what a check reads of the host after a run is the CPU's the guest ran on -- and waits for it, and the task enters the guest over and over from task context, handling each exit between entries.

Its memory

hv::GuestMemory is regions of guest physical addresses, each backed by host pages that are mapped nowhere (kcore::frame::Frame): pages of RAM the kernel hands out by their address and puts in no table of its own, so that a guest of any size costs pages and no kernel address space, and the guest's nested table is the only mapping they have. They are zeroed before the guest can see them, so that what a guest finds in its memory is what it was given and never what the host left there -- or another guest: a guest's memory, once it is gone, goes back as its pages were, and is zeroed before anything is handed it again. Free pages are zeroed ahead, too, while CPUs are idle (Paging, zerofree=): so that what the last guest left is gone from RAM within seconds of its end rather than whenever the page is next handed out, and a guest's frames and huge blocks, taken from those known zero first (alloc_page_keeping, alloc_huge_frame), are not zeroed as it starts.

Two rules make it the one place that decides what a guest can reach:

  • Nothing hands out a reference into it. The guest writes its memory whenever it runs, on whatever CPU, and a Rust reference to memory that changes under the compiler is undefined behaviour however it is used (plans/01-rust-strategy.md calls this the most important decision of the hypervisor). Every access is a copy -- read, write, read_obj::<T: Pod>, write_obj -- bounds-checked against the region it falls in, and made by the kernel through its temporary window onto each page it touches -- the CPU's own slot of it, mapped for that page's part of the copy and nowhere after -- a page's part one call of the architecture's memcpy, which the compiler sees nothing of; an address a guest gave, whatever it is, is at worst Unmapped. A queue's rings are the one exception to the window, and not to the rule: a device reads and writes them at every request, and a copy maps and unmaps a page -- a TLB flush -- at every access, a dozen a frame. So they are mapped while the queue is up (GuestMemory::map, three pages a queue, through mm::map_pages) and still reached a value at a time -- one volatile load or store at a checked, aligned offset, an index with acquire or release (kcore::frame::Mapped). The mapping holds a share of its region's frames (kcore::frame::Run), so none is freed while it is mapped, whichever of the guest and its devices goes last. Undoing one shoots its address down on every host CPU, so a device makes eight and then one a second (virtio::Maps): a guest that set its queues up over and over would otherwise have every CPU of the host interrupted at will, and past the budget its rings are copied, as before, and the report says so. On the EX44, between two guests of two CPUs: dd | nc 2.72 s where it took 4.15, and 2.83 where it took 4.45 with the offloads, five runs of each; BusyBox's httpd serving 100 MB five times over 0.29 s where it took 0.47 -- 1.8 GB/s -- and 0.62 where it took 1.63-1.68 without the offloads. A dozen pages mapped and flushed a frame had been most of what the host spent on one.
  • The nested page table is inside it. A guest reaches exactly what its nested table maps, and this table maps nothing but pages the same value owns: every page is owned before it is mapped, and freed only with the table. "The guest can reach host memory it was not given" is then not a mistake a caller can make, and the one unsafe call that enters a guest has that as a type's invariant rather than a comment's promise.

How much of it, and where

On a machine of several NUMA nodes, every frame and every block of the huge pool is taken from the node of the guest's first vCPU first, the nearest node's when it has none (NUMA): its placement sets the node (Spec::placed), and LinuxGuest::new_on hands it to the guest's memory (GuestMemory::place_on). hv start says the node, and how much of the memory the allocator found there (its memory node 1's (100%)).

A Linux guest has from 64 MiB to 512 GiB (mem=, in MiB; memory = in a vm.toml), laid out as Q35's firmware lays out a machine (linux::Ram): RAM from 0 up to 0xC0000000 (linux::HOLE_RAM_END), where the PCI hole starts, and the rest of it from 4 GiB. Q35's ECAM is at 0xE0000000, and the MSI-X tables', the IO-APIC's and the local APIC's pages follow at 0xFE000000, which RAM must not cover. Its memory map says so, an entry for each, the hole at 640 KiB as before (linux::e820_entries, for a bzImage's zero page and a PVH start info alike); everything the loader writes -- the kernel, the initrd, a PVH image's segments -- is put below the devices' pages, where the identity map and the boot protocol's 32-bit fields reach, and the kernel finds the rest in the map. Its RAM must also end below what it is told a physical address is (CPUID 0x80000008, the host's -- policy::phys_bits), or it could not reach it: a guest that would not fit there is refused rather than given RAM it cannot use. 512 GiB is the most RAM this kernel can take of a machine, so no guest is bigger than its host could be; what is refused below that is the host's memory, the kernel's reserve kept (a sixteenth of RAM, no less than 64 MiB).

Where its pages come from is the boot's to say. With no hugepages=, a guest's memory is frames taken a page at a time, as it always was, each a 4 KiB entry of the nested table. With one, the kernel reserves the huge pool at boot -- 2 MiB blocks, physically contiguous and aligned, taken off the free list right after it is built, before anything has fragmented it, the highest first, and never so many that less than twice the kernel's reserve is left (PageTable::reserve_huge_pool, Kernel parameters) -- and every guest's memory is the pool's: a block every 2 MiB (kcore::frame::HugeFrame, a Run of them), zeroed ahead or when it is handed out, and mapped with one entry of the level above the last -- PS in AMD's nested table, bit 7 in Intel's EPT, where the CPU says its walk takes them (IA32_VMX_EPT_VPID_CAP bit 16; Caps::nested_2m, which hv info reports) and 512 entries where it does not. The guest pages its own memory as it likes, 4 KiB pages and all; what changes is the host's half of every walk, a level shorter, and what the TLB keeps of a translation, 2 MiB where the guest's own page is that large -- Linux's map of all of its memory, for one. A guest the pool has not room for does not start, and says so: mem= a multiple of 2 MiB, and the blocks it wants free (hv start checks before it takes any, and LinuxGuest::new refuses with NoHugePages if another guest took them in between). There is no falling back to frames: with a pool, a guest's memory is the pool's, so that what a guest is given does not change with what ran before it. The pool is the pool for as long as the machine is up, guest or no guest, which is the price: what it holds is no use to the kernel.

The kernel's half (mm/page_table.cpp): two bitmaps, a bit a 2 MiB block of the most RAM the bootstrap map can reach, one saying what is in the pool -- written once, at boot, before there is another CPU -- and one what of it is free, under the page allocator's lock. A block of the pool is on no free list and in no count of free pages, its pages' descriptors as a page handed out has them, so nothing else can take a page of it; free_frame of a page inside one and free_huge_frame of anything that is no block handed out are panics. cpp-fuzz.py's pagetable target reserves pools on machines of more than 4 MiB, hands their blocks out and back, and holds every step to a model; every arm64 smoke boot reserves one (hugepages=64M) and has the frames' selftest hand a block out, write it through its pages and give it back.

The nested page table

AMD's nested table has the host's own long-mode format, four levels of 512 entries (hypervisor/hv/src/npt.rs), with one difference that bites: a nested walk is a user-mode access at every level, so every entry has U/S set or the guest faults on memory it was given. It is built from the host's side only and walked by software only through its own indices -- an arena of tables, each knowing the index of the table under each entry -- so an entry the CPU reads is written here and never read back to find the next level. Accessed and dirty are set from the start, so the CPU has nothing to write into it. The tables a region needs are all made before any of its pages is mapped, so mapping cannot fail halfway for want of memory, and a page already mapped is refused rather than moved.

What entering a guest cannot be told to do

The VMCB is laid out in hypervisor/hvarch/src/x86/svm/vmcb.rs field by field from appendix B of the AMD manual, and every field anything touches has its offset checked against the manual at compile time.

What goes in it is policy, and lives in hv::svm: which instructions stop the guest, what state it starts in. None of that can hand the guest the host, because hvarch::x86::svm::Guest::run sets the part the host depends on on every entry, whatever the VMCB says:

  • intercepts of INTR, NMI, SMI and INIT (the host's interrupts end the guest's turn and are taken by the host), SHUTDOWN (a guest's triple fault would otherwise shut the CPU down), IOIO and MSR (without them every port and MSR is the guest's, whatever the maps say), INVD (discards the host's dirty cache lines), INVLPGA, VMRUN, VMLOAD and VMSAVE (which take host physical addresses), STGI and CLGI (the physical GIF), SKINIT, XSETBV (XCR0 is the CPU's and vmrun does not switch it);
  • intercepts of #DB and #AC, because a guest can make delivering either raise it again -- a data breakpoint on the stack its own #DB frame goes to -- and the CPU then loops inside the delivery, where no instruction ever ends and no interrupt, NMI included, is ever taken: the host has lost the CPU (CVE-2015-8104 and CVE-2015-5307, which KVM closes the same way). Giving them back to a guest that expects them is the policy's to do -- but for an #AC under VT-x on a host that detects split locks, which is not the guest's own alignment check (CR0.AM and RFLAGS.AC in ring 3) but the host's detection of a split lock: that one is said in /logs/hv.log, once every five seconds a VM at most, and the guest stepped past it with the detection off for that instruction alone, by the monitor trap flag (Guest::read_split_lock, step_split_lock; Boot). The splitlock built-in guest is the check;
  • the intercept of #MC -- and since an intercepted machine check is not delivered to the host by the CPU, run raises vector 18 itself before interrupts come back on, into the kernel's own handler, which panics;
  • CR4.MCE set in the CR4 the guest runs with, and the intercept of every write of CR4, so that the guest cannot clear it in the register either: with MCE clear a machine check is no exception but a shutdown -- the guest's triple fault, as the exit has it -- and the host never hears of it. What the guest believes CR4 holds is the policy's to keep: hv intercepts its reads of CR4 as well, and answers them, and performs its writes, from the CR4 the guest wrote (hypervisor/hv/src/cr.rs, crate::cr) -- the instruction fetched by the guest's paging and decoded, as an MMIO access's is, since a CPU without decode assists (QEMU's, a nested hypervisor's) does not name the register. A write of a bit the guest's CPUID does not offer is the #GP a CPU without the feature gives, so LA57 and CET stay off, PKE where its PKRU is not switched, and OSXSAVE on a CPU without XSAVE; one a CPU would not take where the guest is -- PAE cleared in long mode, PCIDE with a PCID in CR3 -- is a #GP too; and a write that changes a bit a CPU translates by flushes the guest's TLB, as the CPU would. QEMU's TCG never stops a guest at a read of CR4, whatever the VMCB asks: its decoder checks a read of any control register against CR0's read intercept, adding the register's number to the exit code only when the code is not 0 -- and CR0's read is (decode_op, target/i386/tcg/decode-new.c.inc, QEMU 10.2). There the guest reads the register, MCE in it, and its writes are the host's all the same. Intercepting CR0's reads too would catch them there, and on a real CPU catch SMSW, which a guest's user process may run;
  • what of the guest's speculation the world switch can keep from the host and from the next guest (hvarch::x86::spec): after the exit, the guest's values cleared out of every register the run stub returns with, and the return stack refilled before the host's first ret -- a guest's return addresses left there would have the host's returns predicted to them; before the entry, an IBPB where the guest CPU is another than the last on the CPU -- two CPUs of one guest included -- or this one after an IBPB it asked for itself, where the CPU has IBPB; and automatic IBRS turned on with the extension, where the CPU has it;
  • the intercept of every read and write of DR0-DR3, and the CPU's four made the guest's own before each entry. The breakpoint addresses are the CPU's, not the VMCB's -- vmrun switches DR6 and DR7, not them -- so without both a guest would read whatever the last guest on its CPU left there, and a breakpoint it set would be moved by the next guest's write, or left behind when its vCPU moved to another CPU. Each Guest keeps its own four, from which the policy answers the guest's movs and into which it performs them (hypervisor/hv/src/dr.rs, crate::dr, the instruction decoded as CR4's is); its own DR7, which vmrun loads, arms them. A record per CPU of what its four hold (LoadedDebugAddrs) has an entry write only the ones that differ -- nothing else in the kernel writes them, the guest cannot, and neither vmrun nor #vmexit does -- so a guest that never sets a breakpoint costs no write at all, where four writes of a debug register, each serializing, would cost every entry. A mov above CPL 0 is the #GP a CPU gives, and one under DR7's general detect the #DB -- DR6.BD set, GD cleared, the move not made -- where a CPU checks either after the intercept rather than before. QEMU's TCG, whose slip with CR0's read code is above, adds the register's number to a debug register's code, which is never 0: there the intercepts are each register's own;
  • physical interrupts masked by the host's flag, not the guest's (V_INTR_MASKING), so a guest sitting with interrupts off cannot keep the host's out;
  • nested paging on, over the table the caller's memory owns; SEV, AVIC and virtual VMSAVE off, since each has the CPU work at physical addresses the VMCB gives it;
  • I/O and MSR permission maps with every bit set but the three of the guest's own base MSRs (hvarch::x86::PASSTHROUGH_MSRS, which the stub's vmsave/vmload carry), and no way to clear another: a port the guest reaches directly is one of the host's devices;
  • nothing assumed clean;
  • the ASID, and what the TLB is told on the way in, given by the CPU the entry is on (Address space identifiers): a translation left over from another guest -- or from a guest that has gone, to a page since handed back to the host -- would be the host's memory in a guest's hands, so which ASID a guest runs under is not the policy's to say.

Entering and leaving

Guest::run turns interrupts off, checks on the CPU it is on that SVM is on and that VM_HSAVE_PA is the page this hypervisor gave that CPU -- not one an earlier load left behind -- and only then enters, so that what was checked is still so: turning the extension off is an IPI, which waits. The machine keeps each CPU's page address in an atomic beside its table for exactly this check, set once the CPU has taken the page and cleared before the CPU is told to let it go -- so before the page is freed, and before the extension is off there.

Address space identifiers

The TLB tags every translation a guest makes with the ASID it ran under and keeps it until something flushes it. Every entry flushed the whole TLB at first, because every guest ran under ASID 1: always right, and every exit cost the guest its translations and the host its own. Now each CPU hands its ASIDs out itself, the way KVM does -- Asids in hypervisor/hvarch/src/x86/svm.rs, the CPU's own, in the one CpuLocal both Guest::runs take once an entry with interrupts off (Entries in hypervisor/hvarch/src/x86.rs, beside the CPU's debug addresses and its speculation state):

  • each ASID is handed out at most once a generation, and a generation ends when they run out -- 32767 on a Zen 2, 15 under TCG -- with a flush of every entry of every ASID at that CPU's next entry into any guest. Until an entry the CPU accepted has made that flush, every entry there asks for it: one the CPU refuses (VMEXIT_INVALID) flushes nothing;
  • a guest keeps its ASID, and its translations with it, only while it keeps entering on the CPU, in the generation and over the nested table it was given it for; anything else -- another CPU, a generation over, another table -- and it is given the next one. So no ASID is live for two guests, or for a guest and one that has gone, without a flush in between;
  • every CPU starts each load of the module run out, so its first entry flushes whatever an earlier load's guests left in its TLB.

What lets a guest keep its translations at all is that its nested table only grows: an entry is written once, where there was none, and stays until the table goes (hypervisor/hv/src/npt.rs), so a translation the TLB still holds is one the table would still make. Every table has an id no other table has, and an entry that took a mapping away or narrowed it would give the table a new one -- moving its guest onto a fresh ASID, clear of the old translation. None does today.

The asid built-in guest is the check: two VMs on one CPU taking turns, an exit each, each reading its own page at the same address, and a third made once they have gone, with the ASIDs a generation limited to two so that it is given one they had, after the flush that ended their generation. A missed flush, or two guests under one ASID, reads another guest's page -- for the third, a page back with the host. Under TCG every entry flushes whatever the VMCB says, so the check can fail only on a CPU that keeps translations.

It also refuses a CPU with CR4.LA57 set. A nested table is walked in the host's own paging mode, and the one here has four levels: walked as five, its top level would be taken for a fifth and the guest's own memory for the last, and the guest would choose its own host physical addresses. Nothing in this kernel turns five-level paging on; the check is where that would be found out, rather than by a guest.

The entry is a naked function, vmrun_stub, and GIF is clear for all of it, so nothing -- no interrupt, no NMI -- runs until the host's state is back whole:

clgi                      nothing gets in from here
vmsave  host page         FS, GS, TR, LDTR, the syscall MSRs: vmrun switches none of them
vmload  guest VMCB
load the guest's registers
sti; vmrun; cli           the host's IF, which vmrun saves, decides that an interrupt exits
store the guest's registers
vmsave  guest VMCB
vmload  host page
stgi                      with IF still clear: the interrupt that ended the turn waits

The vmsave/vmload of the host's state is not optional here: this kernel keeps its per-CPU data at the GS base. Taken out on purpose, the first thing the host does after a guest's exit is a page fault at address 0 in hal::get_current_cpu_hw_id() -- the gate's hv run panics the kernel.

The exits

hv::svm::Vcpu::exit decodes what #vmexit wrote -- port I/O with its size and direction, HLT, CPUID, MSR, VMMCALL, a nested page fault with its address and error code, an exception with its error code, a machine check, a shutdown, and the host's own interrupts, after which the guest goes straight back in. Where an instruction ends comes from the CPU when it saves next RIP; otherwise from the length of the one instruction each intercept is for (HLT 1, CPUID 2, RDMSR/WRMSR 2, VMMCALL 3), and for port I/O from the address every CPU hands over. Stepping past an instruction also steps out of the interrupt shadow it was in.

An exit can cut an event's delivery short -- the host's interrupt arriving while the guest was taking one of its own, a nested fault on its IDT or stack -- and the event is then in exit_int_info, lost unless the next entry injects it. After every exit it is put back into event_inj (the two fields share a format), except a software interrupt or INT3 or INTO, whose instruction the guest's RIP still points at and which running again raises again.

When the CPU says no

A VMCB vmrun refuses comes back as VMEXIT_INVALID and nothing more: no field, no rule. hv::svm::Vcpu::check is the manual's list of consistency checks that a VMCB filled in here could fail -- EFER.SVME, CR0.NW without CD, CR0 above bit 31, CR3 above bit 51, reserved CR4 and EFER bits, DR6 and DR7 above bit 31, long mode without PAE or PE, a 64-bit code segment with D set, G_PAT's memory types, the injected event's type and vector -- and one of this hypervisor's own that the CPU does not make, LMA against LME and PG. Every entry asks it first: a VMCB it finds wrong is never handed to the CPU, and the refusal names the rule. It is the SVM side of the "VM-instruction-error decoder" the plan asks for before it is needed. When vmrun refuses anyway, the report dumps the guest's state.

The built-in guests

Each is a handful of instructions, assembled once -- with NASM, or with clang for mmio and ioapic -- and kept in hypervisor/hv/src/guests.rs as bytes beside the source they came from, run in a VM of its own and checked against what it was told to do. All start in long mode at CPL 0 with paging on, 1 MiB of memory with a GDT, a TSS and a page table in it that maps the first 2 MiB to themselves -- the second of them with no memory behind it -- and 1 GiB to guest physical 4 GiB; all but the second CPU of smp, posted, avx and pkru, which starts where a start-up IPI starts every CPU, in real mode. hv run runs a guest on a task bound to one CPU -- the one named, or the one it runs on -- so that what its check reads of the host after its run is the CPU's it ran on:

Guest Does Shows
exits reads and writes the debug port 0xE9, asks CPUID a leaf only this hypervisor answers, writes what it got to its memory port I/O both ways; CPUID answered by the host; the answers read back out of guest memory
hypercall writes through its own page table to guest physical 4 GiB, puts a value of its own in every register, makes a hypercall, writes every register the host answered to its memory long mode under nested paging, above 4 GiB; the run stub's register save and restore, all 15 registers both ways
uart brings up an 8250 the way a driver does -- divisor behind DLAB, 8N1, FIFO, a scratch-register presence test, what it read back left for the check -- and sends a line polled out of LSR.THRE the emulated serial port, over port I/O alone: the scratch register keeps what was written
fault loads a null DS, then writes to 0x1FF000, which its page table maps and the nested one does not stopped at the nested table, at that address and that instruction: a guest reaches nothing it was not given -- and the state its report shows is the guest's at the fault, the null DS in it, which under VT-x only reading the whole state for the report gives
absent reads AMD's FCH reset-status register at 0xFED803C0 twice, then writes to it a read of a device the platform does not have finds all ones -- what Linux on a Zen CPU reads there -- through one read-only page; the write stops the guest
mmio stores to and loads from 32 bytes of a device's registers in the MMIO window, by every form of mov Linux's accessors are -- an immediate of each size, REX's registers and a high byte, movzx and movsx each access's instruction fetched through the guest's paging, decoded and performed, every value where it belonged (MMIO)
triple int3 with no IDT a triple fault stops the guest, not the CPU
refused starts with CR0.NW set and CD clear a VMCB that breaks a rule is refused before the CPU sees it, the rule named
spin cli; jmp $ the host's interrupts still get through -- about a hundred a second -- and the host stops it when its 300 ms are up
tpr writes 15 to CR8 -- the task priority register, which masks every interrupt priority -- and reads it back the guest gets a shadow TPR of its own (AMD-V's V_TPR; under VT-x the virtual APIC's VTPR, or where the CPU has none, a mov cr8 stops the guest and is answered from a shadow), and the host's CR8, read afterwards on the CPU the guest ran on, is still 0: a guest cannot hold the host's interrupts off its CPU
asid three VMs on one CPU read a page of their own at one address: two taking turns, and a third given an ASID one of them had no guest reads another's page through the TLB, and a reused ASID is reused after a flush (Address space identifiers)
smp two CPUs, on two host CPUs: the first sends the second INIT and a start-up IPI; the second comes up in real mode at the vector's page, climbs through protected mode to long mode, writes down its x2APIC ID and CPUID's, and sends the first an IPI; the first, woken by it, arms its APIC timer for one shot and halts until it fires an application processor started the way Linux starts one, an IPI between two CPUs, and the local APIC timer (More than one CPU)
ioapic on the machine of smp with an IO-APIC, its first CPU alone, in xAPIC mode: reads the IO-APIC's version, then wires the serial port's pin to itself -- as an edge, the THR-empty interrupt enabled and a byte written, then one written while masked; as a level, its handler ending it without reading IIR twice, and the third time reading it edges sent as the line rises and lost while masked; a level sent again at each EOI for as long as its line is up, its remote IRR set until then; every IO-APIC access and every EOI a decoded MMIO access (The IO-APIC)
posted on the machine of smp, asking for its interrupts to be the CPU's: the second CPU, started as smp's is, sends the first a thousand fixed IPIs, one at a time, while the first spins with interrupts on and no HLT, counting them where the CPU has posted interrupts each is posted and notified and taken by the first CPU in its guest, which leaves it a handful of times rather than once an IPI; elsewhere the host hands each over (Interrupts the CPU delivers itself)
apicv on the machine of ioapic, its first CPU's local APIC taken to x2APIC mode by the base MSR: with CR8 at 5 sends itself 0x50 and 0x30 and reads both in IRR; with CR8 at 0 takes 0x50, then 0x30, whose handler sends itself 0x70 and takes it nested, each handler reading ISR; then the serial port's pin through the IO-APIC as a level, three times, each ended by the x2APIC's EOI; and ISR read whole at the end the same to the guest whoever delivers its interrupts: under VT-x with APIC virtualization the CPU delivers all six and takes their EOIs, stopping the guest after the three level-triggered ones for the IO-APIC; elsewhere the host injects them (Interrupts the CPU delivers itself)
pveoi on the machine of apicv, its interrupts the host's to inject on either backend, KVM's PV EOI turned on with its word at 0x7100, each handler ending its interrupt as Linux's does -- the word's bit cleared if set, the EOI register written if not: a self-IPI 0x50 alone; 0x30, whose handler takes 0x70 nested and reads ISR in it; ISR read whole; PV EOI turned off and 0x50 once more 0x50 and 0x70 ended through the word, each EOI the host's at the next exit -- 0x70's at the exit of 0x30's own EOI by the register, done before it -- the word not set while 0x70 waited in IRR nor after PV EOI went off, nothing left in service: two EOIs through the word, two by the register (KVM's paravirtual interface)
kgs on the machine of smp, its first CPU alone running: puts one value in KERNEL_GS_BASE and another in the GS base, stops for a CPUID, runs swapgs, writes 64 times each a fixed IPI to the CPU that never started and its TSC deadline, runs swapgs again and reads both the two bases as its swapgs left them, after writes the world switch answered itself (hvarch::x86::fast) -- under VT-x, whose entries load KERNEL_GS_BASE from a list, an entry past one loaded the value of the last full exit and undid the guest's swapgs; and at least one write answered there, or nothing was looked at
cache on the machine of ioapic, its first CPU alone running: sets CR0.CD and CR0.NW, reads CR0 back and halts with both left set what it wrote read back, and neither bit in any host CPU's own CR0 after it: a VM exit does not put the host's CD and NW back, so under VT-x a guest's write let through left the host's CPU with its caches not filling for good -- the two are in the CR0 guest/host mask now and never in the CR0 a guest runs with (hvarch::x86::vmx::CR0_CACHE_BITS). Under AMD-V the exit puts the host's CR0 back whole, but while the guest runs its CD is the CPU's: a guest can make its own core -- and the sibling thread, its own or its disks' -- slow at will. Not closed yet: it wants CR0's write intercepted and its reads while CD or NW is set, as KVM has it, and QEMU's TCG -- the AMD-V this is tested under -- takes every CR read for a CR0 read
instr one CPU, through the run loop a Linux guest's go through, with #UD and #DB handlers of its own: runs RSM, then INVD, then sets TF and runs a CPUID RSM the #UD a CPU outside SMM gives -- under AMD-V, which stops the guest at it, the host's to give; it was an exit nothing answered, and a user process's rsm stopped its whole VM -- and INVD stepped past under both, the host's dirty lines kept; both named by the backends (hv::exit::Instr), not by one extension's number; and the single step's #DB after the CPUID, DR6.BS set, which the CPU never raises for an instruction that exited and the host now does after every one it steps past -- a debugger's stepi over a CPUID once landed an instruction late
debug one CPU, through the run loop a Linux guest's go through, with an IDT of its own: sets TF with POPFQ and single-steps a NOP, then runs an ICEBP (int1) each a #DB of the guest's own -- intercepted for the delivery loops a guest could make of it -- given back to its handler, the single step's with DR6.BS -- under VT-x, which writes no DR6 at a #DB that exits, the DR6 its exit said, and every mov of DR6 the host's
avx on the machine of smp, both CPUs on the one host CPU the guests run on, taking turns by IPI, and before each of their entries a SIMD section of the host's on that CPU -- ChaCha20-Poly1305 over 1 KiB by the crypto crate, CRYPTOGAMS' AVX2 code where the CPU has it: each turns its local APIC on, runs an XSETBV with CR4.OSXSAVE clear, sets OSFXSR, OSXMMEXCPT and OSXSAVE, runs five XSETBVs a CPU refuses and its own, of the x87, SSE and AVX, reads leaf 1, leaf 0xD's first three subleaves and leaf 7, stores YMM0-15, and loads an x87 control word, an MXCSR and a pattern of its own into YMM0-15; then 64 turns each, a turn its peer's IPI, every one checking all of them against what it left and loading the pattern one more YMM0-15 zero as each CPU starts, though the other's pattern was in the CPU's registers; its YMM registers, MXCSR and control word as it left them at every turn, put back by the host each time the other had had the CPU, or a section had -- 64 times each at least, and the sections run, one a turn at least, with the vector unit lent them; XSAVE and AVX offered, OSXSAVE as CR4 has it, XCR0 1 out of reset and 7 after its own; the XSETBV with OSXSAVE clear a #UD -- the CPU's own under VT-x, the host's under QEMU's TCG, whose intercept comes first -- and the five a #GP each; leaf 0xD's sizes 576 and 832, AVX's component at 576, no XSAVES
pkru on the machine of smp, both CPUs on the one host CPU the guests run on, taking turns by IPI, the second started by avx's code: each turns its local APIC on, runs an RDPKRU with CR4.PKE clear, sets OSFXSR, OSXMMEXCPT and OSXSAVE, and where its CPUID offers PKU sets PKE, makes XCR0 its own -- PKRU in the first's, the x87 alone the second's -- reads leaf 7, leaf 0xD's subleaves 0 and 9 and PKRU, and loads its own into PKRU; then 64 turns each, a turn its peer's IPI, every one checking PKRU against what it left and loading it one key more the RDPKRU a #UD; where PKU is offered -- QEMU's TCG, the EX44, not a Zen 2 -- OSPKE only once its CR4.PKE has it, leaf 0xD's components and sizes for its XCR0, PKRU's subleaf the host's; PKRU 0 as each CPU starts, though the other's was in the CPU's register, and its own at every turn, put back by the host each time the other had had the CPU -- 64 times each at least, whatever its XCR0 says of PKRU
dr two VMs of one CPU each, one after the other on the CPU the guests run on, through the run loop a Linux guest's go through, with an IDT of its own: each reads DR0-DR3, writes a pattern of its own into them through four registers and reads it back through a fifth, then points DR0 at a ret of its own -- each VM's elsewhere -- arms it in DR7 for execution and calls it, its #DB handler turning the breakpoint off every mov of DR0-DR3 the host's: the second VM reads 0 where the first left its own, each reads back its pattern, and each one's breakpoint fires -- DR6.B0, at its ret -- which only its own DR0, made the CPU's before its entry, can do. An execution breakpoint and not a data one: QEMU 10.2's TCG never gets past a store a data breakpoint watches in a nested guest, retrying it for good with no interrupt taken, whoever's DR0-DR3 are the CPU's (What entering a guest cannot be told to do); under VT-x, which stops a guest at every mov of a debug register, the same, its DR6 and DR7 the host's too
tscaux two VMs of one CPU each, one after the other on the CPU the guests run on, through the run loop a Linux guest's go through, with an IDT of its own whose #UD and #GP handlers note the vector -- a #GP's error code with it -- and go on: each reads what its CPUID offers, reads its TSC_AUX by RDTSCP, RDPID and RDMSR, writes a value of its own into it, reads the TSC, RDTSCP and the TSC, reads TSC_AUX by RDPID and RDMSR again, writes it with bit 32 set and reads it once more, and runs INVPCID of types 0 to 4 RDTSCP, RDPID and INVPCID offered exactly where they run in a guest, each run where offered and a #UD where not; TSC_AUX 0 as each VM starts, the second where the first had left its own -- its own put into the CPU before its entries (hvarch::x86::msrs); the value each wrote read back by every way it has, RDTSCP's TSC between the two RDTSCs; bit 32 a #GP, the value kept; RDMSR and WRMSR of it a #GP where neither instruction is offered; INVPCID's four types run and type 4 a #GP; every #GP a #GP(0) -- its IDT ends at gate 13, and an exception past it comes in as a #GP whose error code names its gate; every RDMSR and WRMSR seen by the run loop, and no RDTSCP where it runs
spec two VMs of one CPU each, one after the other on the CPU the guests run on, through the run loop a Linux guest's go through, with an IDT of its own whose #UD and #GP handlers note the vector -- a #GP's error code with it -- and go on: each reads what its CPUID offers of the speculation controls, reads IA32_SPEC_CTRL, writes every control offered into it and reads it back, writes it with bit 62 set and reads it again, asks for three IBPBs by IA32_PRED_CMD, reads PRED_CMD and writes its bit 1 offered exactly the controls the host switches (spec::guest_controls) -- none under QEMU's TCG, every access a #GP; SPEC_CTRL 0 as each VM starts, the second where the first had left its own; the bits it wrote read back, bit 62 a #GP and the value kept; its last entry run under its bits over the host's, and the CPU's the host's alone after; every IBPB it asked for answered by a barrier before its next entry; PRED_CMD's read and bit 1 a #GP; every #GP a #GP(0), as tscaux's; every RDMSR and WRMSR seen by the run loop
cr4 one CPU, through the run loop a Linux guest's go through, with an IDT of its own: reads CR4, writes PAE alone -- MCE cleared -- then PAE and a bit its CPUID does not offer -- PKE, or CET where it is offered PKU -- 0, PAE and PGE through R9 (read back through R13), and bit 32, reading CR4 after each every mov of CR4 performed by the host: the guest reads back what it wrote while the CPU's CR4 keeps MCE, and that bit PAE cleared in long mode and a reserved bit each a #GP(0), CR4 as it was (What entering a guest cannot be told to do) -- the last two, which no CR4 takes in long mode, the CPU's own #GPs before its intercept where it makes them so, as the AX41's Zen 2 does under KVM; on QEMU's TCG, which stops no read of CR4, its reads are the register's, MCE in it, and the writes the host's all the same; under VT-x its reads are the read shadow's, and three of its writes -- those that change a bit the host keeps -- the host's, PAE cleared the CPU's own #GP
msr one CPU, through the run loop a Linux guest's go through, with an IDT of its own whose #GP handler notes what faulted: writes VIRT_SPEC_CTRL and FLUSH_CMD, which its CPUID does not offer, an MSR nobody names (LS_CFG) and a variable MTRR base with a reserved bit; writes and reads back DEF_TYPE, a fixed MTRR and a variable base and mask; reads MCG_CAP, MCG_STATUS and the PAT; asks CPUID for VIRT_SSBD, INVLPGB and the PMU each of the four invalid accesses a #GP(0) its own handler took, nothing written; MTRRcap and the MTRR writes read back; the machine-check registers and the PAT answered; CPUID offering no VIRT_SSBD, no INVLPGB and no PMU, and saying a hypervisor is there (The CPU a guest is shown)
$ hv run all 3
...
hv: guest fault -- a write to memory its page table maps and the nested one does not
  ran on     cpu 3, 51 us
  exits      0 port in, 0 port out, 0 cpuid, 0 hypercall, 0 host interrupt
  stopped    nested page fault at gpa 0x1ff000, error 0x100000006, rip 0x8009
  checked    stopped at the nested table, at the address and the instruction it was told to, its state read whole
hv: guest fault ok
...
hv: guest spin -- cli; jmp $ -- for as long as the host lets it
  ran on     cpu 3, 307051 us
  exits      0 port in, 0 port out, 0 cpuid, 0 hypercall, 31 host interrupt
  stopped    by the host, after 300 ms
  checked    the host's interrupts got through 31 times with the guest's off, and the host stopped it
hv: guest spin ok
hv: guest asid -- three VMs on one CPU, and none reads another's page through the TLB
  ran on     cpu 3, 13708 us
  exits      24 cpuid, 0 host interrupt
  checked    A and B each read their own page taking turns; vm C was given ASID 1, which vm A had, after 2 generation(s) ended, and read its own too
hv: guest asid ok
hv: guest smp -- two CPUs: the first starts the second -- INIT and a start-up IPI, into real mode -- which climbs to long mode and sends it an IPI; then its APIC timer
  ran on     cpu 3 and 0, 18192 us
  exits      cpu 0: 15 (9 wrmsr, 2 hlt, 2 apic irq); cpu 1: 6 (2 wrmsr, 0 hlt)
  stopped    both CPUs halted with interrupts off, the last at 0x80c3
  checked    cpu 1 started by INIT and a start-up IPI, came up in real mode and reached long mode, x2APIC ID 1 and CPUID's the same; its IPI reached cpu 0, whose one-shot APIC timer then ran out and interrupted it
hv: guest smp ok
hv: guest ioapic -- an IO-APIC, through its page: the serial port's pin as an edge, then as a level ended by EOI and sent again while its line stays up
  ran on     cpu 3, 23669 us
  exits      50 (1 port in, 21 port out, 22 MMIO accesses performed, 3 hlt); the IO-APIC sent 5, 3 of them levels, 3 ended by EOI
  stopped    cpu 0 halted with interrupts off at 0x80d4, cpu 1 never started
  checked    version 0x20's 24 pins; two edges taken, none while masked; three levels, each sent again at its EOI while the line stayed up, its remote IRR set in service and clear after
hv: guest ioapic ok
hv: 27 of 27 guests ok

A guest bound to a CPU the extension is not on for is not run, and says which CPU: hv: guest exits not run -- the extension is not on for cpu 2.

What the extension costs while it is on

  • On Intel, a CPU in VMX root operation ignores INIT. It cannot be brought back up through the INIT/SIPI sequence CpuTable::start_all starts APs with until vmxoff. Nothing in nos re-INITs a running CPU today; kexec-style live update (stage 5) will have to.
  • On AMD, EFER.SVME only enables the instructions, and costs nothing else. MSR_VM_HSAVE_PA points at a page that must stay allocated for as long as it does -- which is what CpuPage is, and why the table that owns the pages and the mask of enabled CPUs are set and cleared together under one lock.
  • Either way the page is freed only after the CPU it belonged to has said it is done with it.
  • One Intel write is not given back. If firmware left IA32_FEATURE_CONTROL unlocked, the first hv on locks it with VMXON allowed -- the CPU refuses VMXON otherwise -- and the lock holds until the next reset, whatever rmmod does. It is how every other OS leaves the MSR and how almost every firmware hands it over already, and it is done only after every check that could refuse, so a refusal leaves no trace; but it is the one exception to "unloaded, the machine is as it booted".
  • On AMD, GIF is set before SVM goes off. With the global interrupt flag clear, INIT and NMI stay blocked, and stgi is an undefined opcode once EFER.SVME is clear -- so svm::disable sets it first, as KVM does. The run stub clears GIF only for its own length and sets it before it returns; the off switch is written to be right whatever the stub does.

And while a guest runs:

  • The TLB is flushed only when a CPU's ASIDs run out (Address space identifiers) -- once every 32767 guests, or guests moved between CPUs, on a Zen 2 -- rather than on every entry, the host's entries included, as it was. hv bench ... flush still does that, for what it costs (What an exit costs).

  • The x87, SSE and AVX state is the guest's, and XCR0 with it, switched at the exit and, when it has to be, at the entry. Neither vmrun nor vmlaunch switches them (hvarch::x86::fp). After every exit, an XSAVE of what the guest's XCR0 names into an area each guest owns -- XSAVE's standard format, 832 bytes: the legacy region, the header, and AVX's upper halves of the YMM registers -- or an FXSAVE where its XCR0 is the x87 alone, the SSE registers being the guest's to use whatever XCR0 says. Before an entry, an XRSTOR only when the CPU's registers are not this guest's already -- the kernel keeps, for each CPU, whose load was the last on it (kcore::simd::guest, by a number no two guests ever share), and the host uses the registers nowhere but in a SIMD section (its C++ is built without SSE and x87, its Rust is soft-float; kernel/simd.h), which marks its CPU's nobody's before it uses them -- so between a guest's exit on a CPU and its next entry there they hold what its save saved unless another guest's entry or a section came between, and the entry after a section puts the guest's back. That load is of all the CPU switches, under an XCR0 of all of it, whatever the guest's says: the upper halves of the YMM registers, which a guest whose XCR0 leaves out AVX cannot reach now but can the moment it sets it, are its own or zero, never another guest's. Then XCR0 is made the guest's -- an XSETBV only where it differs, since XSETBV serializes and under a nested hypervisor is an exit to it: a Linux guest runs under the very XCR0 the loads want, and its entries write none.

    The guest's own XSETBV always exits -- AMD-V's intercept, which hvarch sets on every entry; VT-x's, unconditional -- and the run loop performs it as a CPU does (hypervisor/hv/src/cr.rs, xsetbv): a #UD without CR4.OSXSAVE, a #GP above CPL 0, for any register but XCR0, and for a value XCR0 does not take -- the x87 left out, AVX without SSE, anything not offered. GuestFp::set_xcr0 holds a value to the same rules before it is ever loaded, so no XSETBV of the host's can fault on what a guest asked. What is switched, and so all that is offered (fp::offered), is the x87, SSE and AVX as the CPU has them, AVX's component where every CPU with it puts it, at 576 -- the area's bounds -- and PKRU where the CPU has PKU, its 8 bytes past AVX's: AVX-512's, AMX's and CET's state are never in a guest's reach. PKRU is not kept in the area but switched by RDPKRU after every exit and WRPKRU where the CPU held another guest's, beside the XRSTOR: a guest changes it by WRPKRU whatever its XCR0 says, and an XSAVE under an XCR0 without it would leave it out. Both instructions need CR4.PKE, which is set beside OSXSAVE while the extension is on where the CPU has PKU; it changes nothing this kernel does, whose pages are supervisor pages all, to which protection keys do not apply. The guest's own XCR0 may have PKRU or not, leaf 0xD's sizes following it -- its subleaf 9 the host's, the standard area ending past it, the compacted one 8 bytes past AVX's -- and CPUID says OSPKE as the guest's own CR4.PKE has it. The pkru built-in guest is the check: two CPUs taking turns on one host CPU, one with PKRU in its XCR0 and one without, each finding its own at every turn. AMD-V does not stop XSAVES and XRSTORS, which no guest's CPUID offers, and they move the supervisor components IA32_XSS names: it is made 0 while the extension is on, so that they move nothing of the host's (VT-x faults them, its control for them off).

    CR4.OSFXSR, and OSXSAVE where the CPU has AVX, which the loads and saves need, are the kernel's from boot, for its SIMD sections; the extension sets what of them it finds clear when it is turned on for a CPU -- and PKE -- and clears that when it is turned off, not around each entry as OSFXSR once was: that was two serializing writes of CR4 and an XGETBV an exit, and under a nested hypervisor an exit to it for each. That the kernel's code outside a section uses none of these registers is held by its build (scripts/check-simd.py at every link), no fault being left to stop it. Between a guest's exit and the next entry XCR0 is whatever that guest had -- a section that finds it without AVX makes it the kernel's for itself; the extension going off puts back what it found, and IA32_XSS with it. The avx built-in guest is the check: two CPUs taking turns on one host CPU, a section of the host's before each entry, each finding its YMM registers, MXCSR and control word as it left them at every turn.

  • TSC_AUX is the guest's, the value RDTSCP and RDPID read beside the TSC -- the CPU number, as Linux keeps it there -- which neither vmrun nor vmlaunch switches either (hvarch::x86::msrs). Each guest CPU keeps its own, 0 out of reset, written by its WRMSR through the policy, and it is put into the CPU before an entry only where the CPU holds another value: nothing in this kernel reads TSC_AUX or writes it, so between a guest's exit and the next entry it holds what that guest had, and a CPU running one guest makes no write at all. It is loaded on every CPU that has the MSR, whether the guest is offered either instruction or not: AMD-V cannot stop a guest at RDPID, and one running it behind its CPUID's back reads its own 0, not the host's or another guest's. The extension going off puts back what it found. The tscaux built-in guest is the check: two VMs one after the other on one CPU, the second reading 0 where the first left its own.

  • A guest's speculation controls are its own (hvarch::x86::spec, hvarch::x86::msrs): every control of IA32_SPEC_CTRL the CPU has -- IBRS, STIBP, SSBD, and Intel's PSFD, IPRED_DIS, RRSBA_DIS, DDPD_U and BHI_DIS_S, AMD's PSFD -- and IA32_PRED_CMD's IBPB, with AMD's SBPB, which neither extension switches. A guest CPU's SPEC_CTRL is kept beside it, 0 out of reset, written through the policy and held to the bits the CPU takes, and made the CPU's for its run over the host's own: the host's protection -- IBRS and BHI_DIS_S under VT-x, STIBP under AMD-V where a core has two threads -- is never off while a guest runs, and each of these bits only takes from what speculation may do, so a guest's left in the host's until the write after its exit costs speed and nothing else. The MSR is written before an entry and after an exit only where it holds otherwise -- a Linux guest under an enhanced-IBRS host sets the very bits the host has, and costs no write at all -- by the stub's own write after the exit for legacy IBRS, and on an AMD CPU with virtual SPEC_CTRL through the VMCB, which vmrun loads it from whatever the MSR holds: there the guest had run under 0, without the host's STIBP. Its reads and writes always exit. A write of PRED_CMD asks for an IBPB, and each guest CPU counts those it asked for: the IBPB between two guest CPUs on a CPU is keyed by both, so one goes in before its next entry on any CPU it ran on before it asked -- its kernel's barrier between two of its processes, which a CPU it ran the first on and runs the second on later would otherwise not have -- and none goes in twice. That key is the guest CPU now, not the guest: two CPUs of one guest that share a CPU get an IBPB between them, as KVM gives them, since their kernel takes them for CPUs that share no predictors. Where the CPU has an IBPB after every exit already (a Zen 2), that is the one. Not L1D_FLUSH: a guest's flush would have to run on the CPU its data was in, before its task could move. hv counts the IBPBs guests asked for, and reads every CPU's IA32_SPEC_CTRL back, warning where it is not the host's exactly. The spec built-in guest is the check.

  • A halted guest costs its CPU nothing. A HLT with interrupts on is stepped past, as a CPU an interrupt wakes resumes after it, and the vCPU is not entered again until the PIC has an interrupt for it; meanwhile its task sleeps to the timer's next edge, and is woken at it: the host CPU's one-shot timer is armed for the deadline as the task blocks (the local timer, Time). It used to be woken at its CPU's first scheduling point after the edge -- the host tick, at the latest -- so a guest's tick arrived up to 10 ms late. None is lost: every periodic edge that elapsed is owed to the guest and handed over one at a time, each once it has taken the last (Pit::ch0_fire), up to a second's worth. A guest at 250 Hz was given one edge for every two or three periods before, and a guest keeping time in jiffies counted 40% of real time (see On real hardware). Measured on the Linux guest over 120 s of the same boot and a typed id: 5,633,131 exits, 5.56 million of them HLTs, became 76,334 and 11,410; the guest's timer ticks went from 11,973 to 11,943; the vCPU's task slept 89% of the run; and the QEMU process under it went from 106% of a host CPU to 46%.

  • Speculation, AMD-V's half of it (hvarch::x86::spec): after every exit the guest's values are cleared out of the registers the run stub returns with, and the return stack is refilled before the host's first ret -- 32 calls, KVM's fill; automatic IBRS is on while the extension is, where the CPU has that (Zen 4 and later); and what else a CPU needs is decided from its family and CPUID as the extension goes on there, with Linux's list of which family is open to what as the reference. An IBPB right after every exit -- in the stub, as soon as the guest's registers are stored, before the return stack's refill and the host's first ret -- where a guest could otherwise steer the host's branches or returns: BTI on a CPU without automatic IBRS, since this kernel has no retpolines; Retbleed (Zen 1 and 2, and the two families before); and SRSO (Zen 1 to 5) where the IBPB flushes return predictions too, which Zen 1 and 2's does and a later one's where CPUID says IBPB_BRTYPE. That is Linux's retbleed=ibpb and spec_rstack_overflow=ibpb-vmexit for a host whose only way in from a guest is an exit, and it is also the IBPB between two guests on a CPU, which goes in by itself only where there is none after every exit. STIBP in IA32_SPEC_CTRL where a core has two threads: the IBPB clears what a guest trained on this thread, not what one on the sibling goes on training. And HLT and MWAIT always exit (svm::HOST_MISC1): a thread idling switches its core between SMT modes, and on Zen 1 and 2 a ret on the other thread may then be predicted from what the idler left in the return stack (SMT_RSB) -- the host's, refilled, when only the host idles one. hv counts the guests switched on a CPU and the IBPBs issued, says what each one closes, and names what a CPU is open to with nothing to close it: BTI or Retbleed without IBPB, SRSO without IBPB_BRTYPE, two threads without STIBP -- QEMU's TCG, under which hv-test runs where there is no KVM, is the first and the last.

  • Each entry reads EFER and VM_HSAVE_PA on the CPU, and checks the VMCB against the manual's rules, before vmrun.

What an exit costs

hv bench runs a guest that makes nothing but exits -- CPUIDs, each after a read of each of pages pages 4 KiB apart -- on a task bound to one CPU, and times it:

hv bench [cpu=N] [exits=N] [pages=N] [flush] [profile] [mmio]

flush makes every entry flush the whole TLB, as every entry did before ASIDs, so the two can be set side by side on one boot (AMD-V only: under VT-x there is no such entry to ask for); pages is what a flush costs the guest after it -- each read a translation to walk again -- where with none it is what it costs the host. profile times each entry in its parts with the time-stamp counter: the checks and the ASID; the x87/SSE registers put in; vmrun to #vmexit, the stub's VMSAVE and VMLOAD and the guest's few instructions included; the registers taken back out; and the rest, which is the exit handled and the loop round to the next entry. Under VT-x the parts are the checks and VMPTRLD, the shadow written into the VMCS, the registers in, vmresume to the exit, the registers out, and the exit and guest state read out of the VMCS:

$ hv bench exits=20000 profile
hv: 20000 exits on cpu 3, 0 pages read between, ASIDs kept: 342 ms, 17130 ns an exit, 58374 a second (12 host interrupts among them)
hv: an exit, in ns: checks and ASID 127, x87/SSE in 605, vmrun to #vmexit 9012, x87/SSE out 731; the rest -- the exit handled, the loop -- 6655

Those are TCG's numbers, and say nothing about a CPU: TCG flushes its own TLB on every vmrun whatever the VMCB asks, and emulates every instruction of the host's side as well as the guest's. On the AX41 (Zen 2, 2026-09-24, two rounds, the same to a few ns):

Between exits ASIDs kept TLB flushed every entry
nothing 731 ns an exit, 1.37 million a second 940 ns, 1.06 million -22%
a read of 64 pages 873 ns 1321 ns -34%
a read of 240 pages 2180 ns 2448 ns -11%

and the profile of an exit (with its own ~40 ns in it):

ASIDs kept flushed
checks and ASID 90 ns 90 ns
x87/SSE and XCR0 in 119 ns 120 ns
vmrun to #vmexit 314 ns 424 ns
x87/SSE out 102 ns 105 ns
the exit handled, the loop 148 ns 249 ns

The flush cost the world switch 110 ns and the host's side after it 100 ns more, its own translations walked again; with 64 pages the guest's as well. What is left to take is on the host's side of the switch: the x87/SSE state and CR4 around it, 220 ns an exit, and the checks' two RDMSRs.

Those numbers are from before the IBPB after every exit that a Zen 2 now gets (What entering a guest cannot be told to do), and from before what the month since took off an exit. On the silicon -- nos booted on the AX41 beside Ubuntu, 2026-10-23, hv bench cpu=3 exits=200000, three runs and two loads of each module, each the same to a few ns -- that IBPB costs an exit a microsecond, which makes it nearly three times what it was, and STIBP nothing:

An exit, ns on the AX41 a read of 64 pages between
neither (the commit before) 535-537 653-660
STIBP alone 537-540 647-703
the IBPB after every exit, and STIBP 1,543-1,545 1,723-1,763

A third of the microsecond is the barrier itself, in vmrun to #vmexit (330 to 687 ns), where the stub writes PRED_CMD; the other two thirds are the host's code after it running on the predictors it emptied -- the checks (93 to 113 ns), the x87/SSE registers put in (8 to 50) and the exit handled with the loop (117 to 682). Nested under KVM on the same machine (-cpu host with cores of two threads, 2026-10-22) the same change cost 4.7 µs of an exit's 10.2, the barrier and the cold predictors there each inflated by the outer kernel's round trips, and STIBP nothing there either, Linux keeping STIBP on itself. Every built-in guest passes on the silicon with the IBPB on, on the first CPU and the last -- the cr4 guest's two impossible values refused by the CPU itself there as under KVM. The cheaper way to the same end -- the host built with an untrained return thunk and retpolines, so that no IBPB is needed at all -- is left in What a review found, item 1.

Under VT-x the first numbers were nested KVM's on the Intel dev box (-cpu host, hv bench exits=50000), where every unshadowed vmread or vmwrite, every mov cr4, VMPTRLD and intercepted rdmsr is an exit to the outer kernel, and so where the host's side of an exit weighs far more than on the silicon; but the parts they took away are the same parts:

Step, 2026-09-25 ns an exit --
after the review's fixes (CR8, INVEPT, NMI, the intercept set) 17,900
host MSRs cached, VMPTRLD skipped, OSFXSR/XCR0 set once at hv on 12,500 -30%
VPIDs, FXRSTOR only when another guest ran in between 11,700 -7%
the VMCS sync dirty-tracked, the exit read by reason 5,800 -50%

and the profile of the last (hv bench exits=20000 profile): checks and VMPTRLD 13 ns, VMCS written 22, x87/SSE in 38, vmresume to exit 4,610, x87/SSE out 53, VMCS read 51, the exit handled and the loop 1,010. The 4.6 µs in the middle is the outer kernel's round trip for the nested exit, not this code's; of the 12 vmwrites and 14 vmreads an exit, 4,700 and 1,500 ns before the dirty tracking, 73 ns are left. On real Intel silicon the same instructions are tens of cycles each, so the shape of the gain is the same and its size smaller: measured there is what is left to do.

On the silicon -- the EX44's i5-13500, 2026-10-20, nos booted beside Ubuntu from its system image (On real hardware), hv bench exits=200000, each number the same to a few ns over two to six loads of the module -- an exit costs 1.69 µs on a P-core (CPU 0) and 2.07 µs on an E-core (CPU 62) without the speculation mitigations (What a review found, item 1), and 1.82 and 2.49 µs with them. Each one's share, from a module built without it:

An exit, ns P-core E-core
without the mitigations (master's module, f3b0285) 1,690 2,065
with all of them 1,818 2,490
-- the return stack refilled with 2 entries, not 32 -18 -30
-- no BHI_DIS_S -22 -287
-- no VERW -30 -106
-- no IBRS, and so no BHI_DIS_S -50 -303
-- none of the four -97 -431

All of it is 7% of an exit on a P-core and 20% on an E-core, two thirds of that BHI_DIS_S: a cost not of the switch but of every indirect branch the host takes there while the extension is on, which the profile puts in "the rest" (625 ns without the mitigations, 903 with). Linux on the same machine runs its whole kernel under BHI_DIS_S and pays it everywhere. What is left between none of the four and master, 30 ns on the P-core and nothing to measure on the E-core, is the rest of the review's fixes: DR7 switched by the entry and the exit themselves, the registers cleared, the record of the CPU's debug registers. One thing not explained: the first load of the module after a boot runs its E-core exits at 2.2 µs, BHI_DIS_S's share gone, though hv, reading every CPU's IA32_SPEC_CTRL back, finds it set there; every later load is at 2.49.

The P-core's profile, without the mitigations and with them:

without with
checks and VMPTRLD 17 ns 21 ns
VMCS written 20 21
x87/SSE in 63 63
vmresume to exit 950 1,041
x87/SSE out 86 86
VMCS read 20 20
the exit handled, the loop 550-573 605

Those are numbers at the base clock, 2.5 GHz, where firmware left every core and nos kept it until it turned hardware P-states on (Boot, the clock): with the cores up to their turbo an exit costs 1,018 ns on a P-core and 1,512 on an E-core, an MMIO access 2.5 us, and the profile reads checks 12 ns, the VMCS written 12, x87/SSE in 35, vmresume to exit 587, x87/SSE out 49, the VMCS read 11, the rest 339.

The first build with them took three CpuLocals an entry -- the CPU's debug registers, the last guest it entered, its mitigations -- and its checks were 418 ns, each with being calls into the kernel to turn interrupts off and on and to ask which CPU this is. They are one now (Entries in hypervisor/hvarch/src/x86.rs), which the entry takes once as what holds it on its CPU, as AMD-V's did with its ASIDs alone.

mmio has the guest make MMIO loads instead -- mov eax, [rdi] from a device's page in the MMIO window, each a nested fault whose instruction the host walks to, fetches, decodes and performs (MMIO) -- and with profile says what of an exit the access itself took. Under nested KVM, 2026-09-29, 200,000 of each on one CPU (the access's share from a run of 20,000 under profile):

a CPUID exit an MMIO load the access itself
AX41 (Zen 2, AMD-V) 10.3 µs 11.7 µs 1.1 µs
rserver (i5-13500, VT-x) 5.8 µs 8.7 µs 2.4 µs
rserver, the whole guest state read at every EPT violation 5.8 µs 30.8 µs

The last line is the first measurement, and why an EPT violation now reads only what performing an access takes (The VMX backend): of the forty-odd fields a report wants, most are ones a nested KVM keeps out of the shadow VMCS it gives L1, each an exit to it, and 25 µs of every access went there. What is left above a CPUID exit is L0's longer way through a nested fault (0.3 µs under VT-x, none to measure under AMD-V) and the access itself -- three reads of the guest's page tables (the bench's code is on a 2 MiB page; four for a 4 KiB one) and one of its instruction, each a copy through the frame window with a mapping of its own made and dropped, and the decoding, which is a few dozen branches. The copies are where to look if an MMIO-heavy guest makes it matter: on the EX44's silicon (2026-10-20, a P-core) a CPUID exit is 1.8 µs, an MMIO load 4.5, and the access 2.5 of that -- no less than under nested KVM, being the host's own work, and so there most of what an MMIO access costs.

arm64

On Arm a hypervisor is not an extension a kernel turns on -- it is an exception level a kernel runs at. nos is handed the machine at EL2 when firmware boots it there and drops straight to EL1 in its first hundred instructions (arch/arm64/boot.S), and a module cannot climb back: EL2 is entered by taking an exception to it, and a kernel already at EL1 has no way to ask.

So the arm64 backend reports and does not run:

$ hv info
hv: Arm virtualization (EL2) -- not implemented on this architecture
  running at           EL1
                       -- boot.S drops EL2 to EL1; a module cannot climb back
  VMIDs                8 bits
  VHE                  no
  stage-2 output       40 bits

The EL2 hypervisor is a change to the boot path -- stay at EL2, run the kernel there with the virtualization host extensions, install stage-2 translation -- and that is where it will be written. Everything above hvarch is unchanged by it, which is the leverage the roadmap's reordering bought by doing the HAL and arm64 before the hypervisor rather than after.

Running it

The module is built with the kernel (make modules, or any make), and goes on a root filesystem the way any module does:

make nocheck                                 # out/x86_64/modules/hv.ko
scripts/mkrootfs.sh root.img 64 <dir> 1024   # with hv.ko in <dir>
qemu-system-x86_64 -cpu max -smp 4 -m 1G -cdrom nos.iso \
    -drive file=root.img,format=raw,id=d0,if=none \
    -device virtio-blk-pci,drive=d0,disable-legacy=on,disable-modern=off

Under KVM on a Linux host, -enable-kvm -cpu host gives the guest the host's own extension (nested virtualization: kvm_intel nested=1 or kvm_amd nested=1), which is far faster than TCG and is how the VMX path is exercised before it reaches real hardware. tests/hv-test.py uses it on both: AMD-V on an AMD host, Intel VT-x (nested) on an Intel one, and AMD-V under TCG's -cpu max where there is no KVM -- TCG has no VMX, so the Intel backend is reached only through KVM. The two guests whose verdict differs by vendor (refused, asid) have their expected output chosen from hv info.

The gate is tests/hv-test.py (Tests and gates):

tests/hv-test.py                  # x86-64: the extension on and off and off again, and every guest
tests/hv-test.py --arch aarch64   # arm64: that it reports and refuses

A Linux guest

hv boot loads an unmodified 64-bit Linux bzImage by the boot protocol and runs it on a vCPU. The kernel and the initrd are streamed from a file straight into guest memory a chunk at a time, so neither has to fit in one allocation; then hv::linux lays the guest out -- the zero page from the setup header, the command line, an e820 map, identity page tables and a GDT, all written through GuestMemory's copying accessors -- and puts the vCPU at the kernel's 64-bit entry with RSI at the zero page. It holds no reference into guest memory: everything it writes the guest could have written itself.

Three things stand between that entry and a running kernel, and all three are here:

  • A CPU cut down to what is emulated (hv::policy), and named whole. CPUID is an allow-list: a leaf the policy does not name is all zeros, as is every leaf past the tops it reports -- 0x16 and 0x8000_0021, or the host's if lower -- and of the leaves it names a guest is told the host's bits it lets through: XSAVE's state as far as the switch around vmrun and vmlaunch moves it, the x87, SSE and AVX -- XSAVE, OSXSAVE as the guest's own CR4 has it, AVX, FMA, F16C, AVX2, VAES and VPCLMULQDQ, and of leaf 7's subleaf 1 the VEX-coded AVX-VNNI, AVX-IFMA, AVX-VNNI-INT8 and -INT16, AVX-NE-CONVERT, SHA512, SM3 and SM4; leaf 0xD made up for those three components, its sizes for the guest's own XCR0; XSAVEOPT, XSAVEC and XGETBV's ECX 1 as the host has them, never XSAVES -- and no AVX-512, AMX, whose state nothing switches; PKU where the CPU has it, the guest's PKRU switched with it, and OSPKE as its CR4.PKE has it; of paravirtualisation KVM's signature, NOP_IO_DELAY and PV EOI alone (KVM's paravirtual interface); the speculation controls the host has -- IBRS and IBPB, STIBP, SSBD, and Intel's PSFD, IPRED_DIS, RRSBA_DIS, DDPD_U and BHI_DIS_S, AMD's PSFD and SBPB -- with IA32_SPEC_CTRL and IA32_PRED_CMD the guest's own (What the extension costs), but not L1D_FLUSH, whose flush would have to run on the CPU the guest's data was in before its task could move; of the structured leaf, 7, what runs as it is and owns no state of the host's -- SMEP, SMAP and UMIP for the guest's kernel, FSGSBASE over bases the VMCS and the VMCB keep, BMI, ADX, ERMS and FSRM (and of subleaf 1 the fast zero-length and short string facts, FZRM, FSRS and FSRC), RDSEED, SHA, GFNI, CLFLUSHOPT and CLWB, SERIALIZE -- with MD_CLEAR, VERW clearing the CPU's buffers in a guest as anywhere, and ARCH_CAPABILITIES, whose MSR reads as the host's but for the bits that are not facts of the CPU (those naming an MSR nothing answers) -- IBRS_ALL among the facts, the guest's SPEC_CTRL its own; PCID, and INVPCID -- a global flush without two writes of CR4 -- RDTSCP and RDPID where they run in a guest: always under AMD-V, where the CPU has them, and under VT-x where it has the controls that turn them on, the last two reading the guest's own TSC_AUX (What the extension costs); of the power leaf ARAT alone, and for a guest of one CPU no local APIC and no x2APIC (one of more has an emulated x2APIC: More than one CPU); and the hypervisor bit, since there is one, which has Linux leave the microcode loader and the bare-metal chicken bits alone. Its CPUs are one package, whichever host CPUs their vCPUs run on, each CPU's APIC ID its number -- 0 for a guest of one -- of cores of one thread, or of two where its CPUs are one host core's two threads (Where its CPUs sit): leaf 1, the sharing counts of leaf 4 and AMD's 0x8000001D, the x2APIC topology leaf (0xB), and AMD's 0x80000008 and 0x8000001E say so, none of them the host's; 0x1F, past the top, the SVM leaf and the memory-encryption leaf are blank. Every MSR is intercepted but the three segment bases, and every one is an allow-list's too: the system MSRs (EFER, the PAT, the segment bases, the SYSCALL and SYSENTER registers) are the guest's own state and are served from the VMCB save area -- a PAT entry that is no memory type, an address that is not canonical, an EFER bit its CPUID does not offer each a #GP, as the CPU gives -- the x2APIC's by the local APIC of a guest that has one, the TSC as the host's. The MTRRs are each vCPU's own: MTRRcap advertises fixed ranges, WC and eight variable pairs; DEF_TYPE, the eleven fixed registers and eight base/mask pairs read back as written. All start at zero; a memory type or reserved bit the CPU refuses is a #GP. They never change the nested table's memory types. A few more answer as a CPU with nothing behind them would, each taking a write that leaves it as it is and no other: the machine-check registers (no banks, nothing to report), which leaf 1 offers and Linux reads with no fallback for a fault -- a fault on a machine-check register is a panic to it -- the microcode revision, the host's on Intel (by which Linux keeps PCID on a Raptor Lake whose microcode has the fix) and none elsewhere, and of each vendor what Linux reads of every such CPU without asking: Intel's platform ID and MISC_ENABLE, its fast strings as the host has them; ARCH_CAPABILITIES where leaf 7 offers it, read-only; AMD's HWCR, DE_CFG and NB_CFG, with the bits a Linux on AMD checks set as the hardware has them. Every other MSR is a #GP, read or written -- what a guest's rdmsr_safe probes are ready for, and a line in the VM's report. One a guest's user can reach is refused on purpose: DEBUGCTL, whose BTF ptrace's block-step sets -- Linux says so once ("unchecked MSR access error") and steps by instruction instead, where a write kept nowhere would have it believe it steps by branch. LBR virtualization in the VMCB would let BTF work.
  • The devices a guest cannot boot without (hv::devices): the 8250 serial port the console writes to (which raises IRQ4 for the transmitter, so the driver sends past its first byte); an 8254 PIT whose counter counts down at 1.193182 MHz off the host clock, whose channel-2 output goes high at its terminal count (what pit_calibrate_tsc waits on), and whose channel 0 raises IRQ0 -- the system tick a guest cannot schedule without: an edge a period in the periodic modes 2 and 3, and one when a loaded count runs out in the one-shot modes 0 and 4, which a kernel's high-resolution timers drive a count at a time; an MC146818 RTC that answers the host's wall clock, with UIP set for the 2 ms before each second turns over; and a pair of 8259 PICs the guest takes its interrupts from -- every one of them, for a guest of one CPU, which runs with no local APIC.
  • The exit loop (hv::run) that answers all of the above, injects the highest-priority interrupt the PIC has when the guest can take one (and asks the CPU, through SVM's virtual-interrupt window, to exit the moment it can when it cannot), and halts the vCPU when the guest does: an idle HLT is stepped past -- a CPU an interrupt wakes resumes after it, so Linux's sti; hlt; cli returns to its idle loop, and out of the STI's interrupt shadow -- and the vCPU is not entered again until an interrupt is pending for it, its task asleep until the timer's next edge. It streams the guest's console to the kernel log a line at a time -- a boot's worth, a thousand lines, and then at most fifty a second, what it leaves out said once a second at most (... N lines not logged), so that a guest printing as fast as it can does not have the host's log, serial line and netconsole for its own; the console itself, which the report and hv console show, keeps every byte -- and stops with a reason and a register dump.

And what a PC's firmware leaves a kernel, which it reads instead of asking a BIOS: the e820 map, an MP table for a guest of more than one CPU (More than one CPU), and the ACPI tables, with the fixed hardware they describe (ACPI).

What this reaches today, on a tinyconfig Linux 6.18 under AMD-V (QEMU's TCG, where the guest is twice emulated and slow), is a full boot to an interactive shell:

$ hv on
$ hv boot /bzImage initrd=/initrd cmdline=console=ttyS0 nolapic rdinit=/init
  --- ttyS0 ---
[    0.000000] Linux version 6.18.53 ...
[    0.000000] NX (Execute Disable) protection: active
...
[    0.540000] Run /init as init process
nos-guest: init is up, / on ramfs, busybox v1.36.1
Linux (none) 6.18.53 #1 x86_64 GNU/Linux

BusyBox v1.36.1 built-in shell (ash)
~ # id
uid=0 gid=0
~ #
  --- end ttyS0 ---

The shell reads what is typed at it: hv boot ... input='id\n' hands the guest a line once it is at a prompt, and the 8250's receive path -- with the answer to the cursor-position query (ESC[6n) a line editor sends first -- carries it. The gate is tests/hv-linux-test.py, a manual one (a bzImage is megabytes and CI cannot build one in its time), pointed at a kernel by hand; with --initrd it checks the guest reaches its init and a shell, and --input 'id\n' --expect uid=0 checks it runs the command.

A disk

disk=<path>, on hv boot or hv start and as many times as there are disks, gives the guest a virtio block device over a file of nos's: vda, vdb, ... in that order, each the size of its file -- past 4 GiB too, as big as nos's ext2 lets a file be (Filesystems: almost 2 TiB of 4 KiB blocks), and blank from truncate /vm/disk.img 20G if it is to be made on nos. The guest mounts it, ext4 and all, as it would a disk of QEMU's:

$ hv start /bzImage initrd=/initrd disk=/disk.img cmdline=console=ttyS0 nolapic
$ hv exec 0 mount -t devtmpfs devtmpfs /dev
$ hv exec 0 mount /dev/vda /mnt
$ hv exec 0 cat /mnt/hello.txt

An image is one writer's, or any number of readers'. A guest's disk claims its image as it opens it, by the file rather than the path -- its mount and inode, so two names of one image are one: a disk that writes it has it alone, and disks that only read it (:ro) share it. Two guests' filesystems on one set of blocks would each wreck the other's with nothing to say so; a start or a boot that cannot have its claim is refused, saying whose the image is --

$ hv start /bzImage initrd=/initrd disk=/disk.img:ro cmdline=console=ttyS0 nolapic
hv: vm 1 not started -- /disk.img: vm 0's disk writes it

-- and the claim goes with the disk, when its VM stops. It holds among the VMs only: nos's own shell is not held to it (modules/hypervisor/hv/src/disk.rs).

Legacy virtio over PCI, reached by port I/O -- so still no instruction decoded anywhere. PCI's configuration space is the PC's mechanism #1, an address written to 0xCF8 and the data at 0xCFC, for bus 0: a host bridge at 00:00.0, which is what Linux's sanity check of the mechanism looks for, then a function for each disk (hv::devices::pci). Only a dword access at 0xCF8 reaches the address -- a byte at 0xCF9 is the chipset's reset control, which the run loop sees first. Each disk's registers are in an I/O BAR, placed as a BIOS would place it and movable as a BAR is; its interrupt is INTA, on IRQ 11 of the emulated slave PIC, raised as an edge when the device's interrupt status goes from clear to set -- the PIC here is edge-triggered, and a line re-raised while the driver has yet to look would be interrupts it finds nothing for, which Linux ends up disabling a line over. (That exposed a slip in the PIC: acknowledging a slave interrupt dropped the cascade line even with another slave request waiting.)

Virtio's MSI-X memory BAR is movable too. Its table and pending bits share one RAM-backed page. The region that owns that page keeps its initial address, which the host uses to read entries, write pending bits and migrate its bytes; the guest's BAR and its NPT/EPT mapping move together through move_msix. A destination over RAM, another mapping, an absent page or the xAPIC page is left unmapped, and a later BAR write can move it again. During live migration the dirty log translates that stable backing address to the current mapping: a move makes the new page read-only while the log is active, and its first write faults and marks the backing page. A saved BAR restores its mapping. A capture while a BAR shows its temporary sizing mask is refused, since the mask alone cannot carry both that state and the address to restore.

The rings are the guest's; the host trusts none of them (hv::devices:: virtio). A queue's descriptors, its available ring and its used ring sit in guest memory, where the guest may write any of them at any moment. Every index, address and length read from them is checked before it is used: a descriptor past the queue, a chain longer than the queue -- a loop --, more chains than the queue holds, an indirect descriptor where none was taken, a table the device will not follow, or a ring or a table outside guest memory stop the device, which takes nothing more until the driver resets it; a request's own buffer outside it is that request's error -- a disk's S_IOERR, a frame dropped -- and the device goes on. A queue the driver has not set up, or took down (a page frame number of 0), is none to work on at all: its rings would be at page 0, where a pass once asked for its kicks and gave back what it served, and, with EVENT_IDX, found more to do at every look -- the first CPU's round due again at once, for good. Taken down or set up anew, a disk's chains still with its backend are the old rings', given back to nobody, as a reset's are. A disk's request is one entry of its ring (VIRTIO_RING_F_INDIRECT_DESC, which the disks offer and the NICs do not): its buffers in a table of descriptors in guest memory that the chain's last descriptor names -- read 16 at a time, one copy through the kernel's window each, and checked as the ring is: whole descriptors, followed by their next inside the table, none of them a table again, the chain no longer than the queue. Without it a request took a descriptor of the ring a segment plus two, a 256 KiB one 66 of 256, and Linux, which takes descriptors from the ring until there are none, had three of them -- 768 KiB -- with its disk at once, whatever its queue's depth: a 1 MiB write at a depth of 8 that has 8 MiB out under KVM. A request's header, data and status are taken as streams across its readable and writable buffers, whatever the layout; its sector range is checked against the disk's size. A request larger than a backend buffer is served in parts, including one in a single descriptor from EDK2's VirtioBlkDxe, which does not negotiate size_max or seg_max.

Each side asks for the other's notifications only when it wants them (EVENT_IDX, virtio::F_EVENT_IDX, which the disks and the NICs offer). Without it every chain the driver makes available is a notify -- an exit -- and every chain given back an interrupt, unless the driver's one flag says it wants none at all. With it each side says, in a word past its own ring, at which entry it wants to hear of the other's work: the driver at which used entry it wants an interrupt (used_event), the device at which available entry it wants a notify (avail_event). The device asks only when it stops for want of chains: a disk once it has taken every request there was -- with every one of its buffers out it asks for none, a request coming back has it look -- a NIC's transmit queue once it has sent every frame, its receive queue only when a frame waits for buffers, so the guest's refills of its receive ring cost no exit at all, the next frame taking what they posted. An ask is the index the device has seen, written; a full fence; and the index read again (Queue::ask_kick): a chain made available between the device's last look and its ask, by a driver on another CPU that saw no ask yet, has no notify coming for it and is taken then. A pass that ends at its bound (more) is the first CPU's round to go on with at once -- that CPU rung, if the pass ran on another's -- since a driver that notifies only when asked gives the device no other reason to come back. A disk's pass is bound by the data it moves as well: 512 KiB of writes taken out of the guest's memory and reads given back into it, two backend buffers' worth (blk::PASS_BYTES). It runs under the platform's lock, which every other CPU's port and MMIO access waits for, and a guest writing a megabyte at a time eight deep once had 8 MiB copied under one: Linux's clocksource watchdog on another of its CPUs found a read of the PM timer taking 800 us. hv-fuzz holds every call into the disk to what one pass may move, and the report says how many passes were cut short. The interrupt is the driver's to place: the device raises one when the used index has passed the driver's word since it last decided (wants_interrupt), and Linux puts its word three quarters of the way through what it has out for its transmit queue, and leaves it behind while NAPI polls. Each device's notifies and interrupts are in the report (hv stop). Under TCG, Linux 6.18 through hv-linux-test.py --net -- the same build with EVENT_IDX not offered as the control -- refilled its receive ring with 1 notify where it had 35, and took 128 receive interrupts where it had 216 (107 where 161, with two CPUs); its sends were a notify a frame either way, each finding the ring drained. Its disk (--disk) made 373 notifies where 398, and 367 where 408 -- that workload seldom has more than eight requests out, which is where the disk's are spared. The hv fuzzer's virtq target holds both sides to a Linux driver's every request served (Testing).

The disk works beside the guest. A request used to be served before the notify that made it available returned, the vCPU waiting for its disk -- and on the AX41 a guest writing back what apt-get update had fetched stalled for seconds at a time (On real hardware). Now the notify only takes the requests off the ring -- a write's data copied out of guest memory into the request's buffer -- and hands them to the backend, which serves them on a task of its own, on a CPU other than the vCPU's: each request started the moment the task finds it, a read or a write of blocks its image has with the device asynchronously and a flush, a discard or a write of zeros served then and there, once the image's I/O in flight is done (modules/hypervisor/hv/src/disk.rs; the image's queue, A disk's image). So the disk has every request the guest has out, as under KVM, and each comes back when it is done rather than with the slowest of a lot -- where the lot was the guest's unit, it saw its disk at a depth of what the last lot left out. Each time round the run loop what it has served is given back: a read's data copied into the guest, the status written, the chain on the used ring, an interrupt; and as it finishes each lot the task wakes a halted vCPU or kicks a running one out of its guest, the NICs' way (A network). Guest memory is touched under the platform's lock, on whichever task holds it: a vCPU's, or the disk's own as it gives back what it served (LinuxGuest::serve_disk) -- the lock, not the task, is what orders that against a reset and every other CPU's access. A reset, or the queue set up anew, forgets the chains still with the backend, and the new driver's requests start only once those are back: side by side, a crash kernel's journal write and its dead kernel's last write to the same blocks, over a backend that stalled, could land in either order (QEMU drains its backend at a reset for this). A driver that takes no FLUSH may take its disk to be write-through (virtio 1.x, 5.2.5.2): each of its writes is flushed before it is answered, as QEMU makes its backend write-through for one, and a flush it sends anyway is served, not refused. At most 64 requests are out at once (blk::IN_FLIGHT), each in a 256 KiB buffer of the backend's taken when the disk is made (Backend::with_buffer) -- a driver that negotiates them is told a request carries at most 64 segments of a page (seg_max, size_max). EDK2's VirtioBlkDxe does not negotiate either and may put an 896 KiB read in one descriptor, so a larger guest request is served a buffer at a time through the same slot: a read's part is copied to its own offset before the buffer is reused, a write's next part is copied out then, and only the last part writes the status and returns the chain. A failure ends the whole request, and a write that needs a final flush gets one, not one a part. Nothing is allocated on the way, and a guest that keeps its ring full waits for its disk rather than growing anything of nos's -- the disk's task has its lists of them from the disk's opening too, so that a disk that could not have them refuses its VM's start rather than starting a guest whose disk never answers. The buffers are the image's (kcore::fs::ImageQueue): its disk reads and writes them as they are, so a request's bytes are copied once, between the guest's memory and the buffer. A volume of NBS's has buffers of its own, a slot each, which go with a request to its session and come back with the answer; the session makes a message of each request from the heap, which is the one thing on a volume's way that allocates.

The disk's bytes are a trait's (hv::disk::Backend, which is handed a request and gives it back served): the module's QueuedDisk holds the image (kcore::fs::Image, whose word the kernel looks up on every call; nothing else may write the file, cut it, grow it, rename it or remove it while the disk has it, nor its filesystem be unmounted -- A disk's image), reads and writes it where the guest asks -- within the file's size, never growing it -- with no lock of the VFS's taken, through the file's map the image holds, a write into a hole first growing the file by the 16 MiB chunk around it, and for a guest's flush, offered and taken by ext4, flushes the device: the filesystem's sync only after a write the filesystem had to take itself. Which file it is comes first, so that a second guest's disk on it is refused saying whose it is (Claims), and only then is it held. The report counts each disk's reads, writes, flushes and errors, and the image says as it is let go of how many of its batches went off the lock and how many through it, and how many requests its queue served with the device asynchronously and how many by the batch.

What a guest no longer needs it gives back -- a chunk at a time. The disk offers discard and a write of zeros (VIRTIO_BLK_F_DISCARD, F_WRITE_ZEROES; a disk the guest may only read offers neither): a guest's fstrim, ext4 mounted with discard, blkdiscard, mkfs of its own disk -- ranges of sectors, up to eight a request and 64 MiB a range, aligned best to what the image gives back whole -- its chunk (Backend::discard_sectors, Image::discard_unit), 4 KiB where it gives back nothing -- so that the guest splits its discards on a chunk's edge and sends none shorter. The device copies the ranges out of the guest's memory once, checks them in its own copy -- whole sectors inside the disk, no flag but a write of zeros' unmap -- and hands the backend that copy (Request::ranges): a guest that changes them after the check changes nothing it was checked on. The image gives the whole chunks of a discard back to nos's root (Image::discard, Vfs::punch, ext4's and ext2's punch): holes in its file from then on, reading as zeros, its size as it was -- so an image no longer only grows; what a discard covers of a chunk only in part is left the guest's. A write of zeros with unmap gives back the chunks it covers whole and writes zeros over the rest; without, it writes zeros, its blocks kept. ext2 gives the blocks back in batches in truncate's order -- each batch's pointers cleared and on the disk, the inode committed, and only then the blocks freed in the bitmap -- so a crash leaks at most a batch to e2fsck and never leaves a block both in use and free; the indirect blocks stay, whatever is left in them, since they map what is past the range too. That the next file may have a block the moment the punch is done is safe because an image's calls come one at a time: no read of its own is under way off the VFS's lock on a block it mapped before. The report counts the discards and writes of zeros, and the image says how many blocks it gave back.

What a guest's write costs nos's ext2 (Filesystems): one into a hole of the image flushes nos's disk once and writes the pointers to what it filled after that, where it used to cost a flush and four FUA writes, and every block it took a write of its indirect block besides; one over blocks the image has flushes nothing, and writes its inode only when the second of its mtime changed. The image is also no longer looked up by its path for every 64 KiB. The same 48 MiB dd if=/dev/zero ... conv=fsync in the guest under TCG, as the guest timed it, and what nos asked of its own disk over the whole run, its boot's hundred-odd flushes included (QEMU's info blockstats):

the image on nos's root before after
with holes: the guest's writes allocate 11.3 s; 32,640 writes, 134 MB, 4,716 flushes 2.2 s; 13,530 writes, 55 MB, 317 flushes
whole: the guest's writes overwrite 3.4 s; 15,534 writes, 64 MB, 1,978 flushes 0.83 s; 14,559 writes, 60 MB, 112 flushes

On the AX41 a Debian guest writes at 1.2 GB/s and reads at 1.6 GB/s, and what apt-get update leaves dirty goes down in a few hundredths of a second where it took half a minute (On real hardware).

tests/hv-linux-test.py --disk is its gate: an ext4 image with a file in it on nos's root, the guest mounting it, reading the file, writing 4 MiB and a file of its own, syncing and reading back after a remount -- and then nos's root judged by e2fsck, and the image, taken back out of it, judged too and holding what the guest wrote. It needs a guest kernel with PCI, legacy virtio-pci, virtio-blk and ext4.

A disk from a cloud's image

A cloud image comes as QEMU's qcow2 -- Ubuntu's ubuntu-24.04-server-cloudimg-amd64.img, Debian's genericcloud, Fedora's -- and a guest's disk here is a raw file. hv convert <image> <disk> makes the one the other (modules/hypervisor/hv/src/image.rs, over the diskimage crate, which has no kernel in it):

$ hv convert /img.qcow2 /img.raw
hv: /img.qcow2: qcow2 version 3, a disk of 7 MiB in clusters of 64 KiB -- into /img.raw
hv: /img.raw: 2 MiB written of 7 MiB, the rest holes -- 34 clusters inflated, 8 copied, 0 zeros, 55 not there -- in 0.0 s

-- a progress line every few seconds on a big one, as wget's. Ubuntu 24.04's image (serial 20261017, its SHA-256 the one SHA256SUMS gives) converts, by the same code on the host, to a disk qemu-img compare calls identical.

The holes are kept. The disk is a new file, grown to the image's size with a hole (File::set_len), and only its blocks that are not all zeros are written: Ubuntu's 3.5 GiB disk costs the 1.7 GiB it holds, and grows as its guest writes. truncate it bigger, for a guest to grow its root into (cloud-init's growpart does): hvboot reads the image's GPT from its primary header, wherever the disk ends.

What it reads: versions 2 and 3; clusters of 512 bytes to 2 MiB; clusters stored whole, compressed by zlib -- 27,971 of the 28,663 that Ubuntu's image has data in -- all zeros, or not there; and extended L2 entries, their subclusters each of those. A compressed cluster is inflated by a DEFLATE decoder of the crate's own (common/storage/diskimage/src/inflate.rs) whose every rule is zlib's, checked in zlib's order -- what it needs of a stream's bits before it calls a code bad included: QEMU reads those clusters through zlib, so a cluster QEMU reads must give its bytes here and one QEMU refuses must be refused. Internal snapshots are left out: the disk is the image as it is now.

What it refuses, saying why: an overlay on a backing file, which it does not contain; encryption, AES or LUKS; an external data file; zstd compression; an image QEMU marked corrupt; features it does not know; a disk that is there already, which is not written over; and a file that is no qcow2 -- by what it is: a raw disk is given to a guest as it is, an ISO read-only, a gzip or xz stream is unpacked first, a VMDK, VHD, VHDX or VDI is converted elsewhere. A conversion that fails leaves no disk behind.

The image is a download, and untrusted. Its every offset is held to the format's alignment and to the file, every table to the bounds QEMU puts on it, and nothing it says makes the converter read, write or hold more than 64 KiB at once, whatever its cluster size -- a 2 MiB cluster is never one allocation. QEMU reads past a file's end as zeros; here a table or a cluster that starts past it, and a compressed one that runs past its last sector and does not decode, are refused, asking "is the image whole?": what has them is a download cut short, and a disk of zeros where its data should be is a failure nobody would hear of. Its gate is tests/diskimage-test.py (host, in CI): images qemu-img and qemu-io write, of every version, cluster size and kind, converted and held byte for byte to what qemu-img reads; the refusals; the decoder against zlib over streams made and broken at random; and the images' metadata fuzzed. hv-test.py converts in nos, on both architectures, and holds the disk to its SHA-256 (Testing).

A device as a guest's disk

disk= takes a partition or a whole disk of nos's as well as a file. The guest's virtio disk is then the device itself: its requests go to the block layer's queue for that device (kcore::block::DiskQueue, over layers/block/src/devq.rs) and nothing else -- no file and no filesystem on the way, so no extent map looked up, no chunk grown ahead of a write, no ext4 commit, no lock of the VFS's (modules/hypervisor/hv/src/devices.rs, disk.rs).

A device is named by what finds it again at the next boot. Linux and nos alike number the EX44's two NVMe drives differently from one boot to the next, and a vm.toml that said nvme1 would one day be given the other drive. So disks gives each device an id, and a vm.toml keeps that:

> disks
vda     131072 sectors (64 MB)  512 bytes/sector
nvme0   131072 sectors (64 MB)  512 bytes/sector  disk:nvme-QEMU_NVMe_Ctrl_nosdevtesta
nvme1   131072 sectors (64 MB)  512 bytes/sector  disk:nvme-QEMU_NVMe_Ctrl_nosdevtestb
nvme01   16384 sectors (8 MB)   512 bytes/sector  part:6e6f7364-6576-0000-0000-000000000001
nvme02   32768 sectors (16 MB)  512 bytes/sector  part:6e6f7364-6576-0000-0000-000000000002

A partition is part: and its GPT unique GUID, as Linux's PARTUUID writes it, or its MBR's disk signature and number (part:4e6f7331-01); a whole NVMe disk is disk:nvme- with the model and serial number its controller gives. A device with neither -- the virtio disk above -- has no id, and is given only by its name, dev:vda, to what is given once: hv boot, hv start with a kernel. Its name is never written into a vm.toml. A vm.toml's id is looked up at every start, under whatever name the device has that boot, and two devices with one id -- a disk copied whole, partition table and all -- are refused rather than one taken.

hv devices is what could be given, and what is in the way of each:

> hv devices
vda         64 MiB  (no id)  whole disk  -- held by a mounted filesystem
nvme0       64 MiB  disk:nvme-QEMU_NVMe_Ctrl_nosdevtesta  whole disk  -- holds nvme03, an EFI System partition: never given  -- holds a GPT partition table
nvme1       64 MiB  disk:nvme-QEMU_NVMe_Ctrl_nosdevtestb  whole disk  -- empty
nvme01       8 MiB  part:6e6f7364-...-000000000001  GPT type 0fc63daf-...  -- holds an ext4 filesystem labelled "devtest"
nvme02      16 MiB  part:6e6f7364-...-000000000002  GPT type 0fc63daf-...  -- empty
nvme03       4 MiB  part:6e6f7364-...-000000000003  an EFI System partition  -- empty
nvme04      16 MiB  part:6e6f7364-...-000000000004  GPT type 0fc63daf-...  -- holds data nos does not recognize

A device is "held by" what claimed it, and "in use by" what claimed something it overlaps -- a partition of it, the disk it is a partition of -- which is as much in the way of giving it; the VMs whose vm.tomls name it, and those being made that are being given it, are said, and a vm.toml that cannot be read is said after the list, the devices it names not known. All the vm.tomls are read once for the whole list. What is on a device nothing is in the way of is read off its first 72 KiB and its last 128 KiB, where each kind keeps its mark (diskimage::contents): ext2, ext3 and ext4 told apart by their features, XFS, btrfs, F2FS, swap, an LVM physical volume, an md RAID member of any superblock version, LUKS, ISO 9660, NTFS, exFAT, FAT, squashfs, nanofs, nos's disk log, a GPT or an MBR -- with its label where the kind has one -- and bytes that are none of those as "data nos does not recognize". Only a start of zeros is "empty".

A device is given where it may be, and the rest is refused saying why:

> hv create e1 /hvboot mem=64 disk=dev:nvme03
hv: nvme03 (part:...-000000000003) is an EFI System partition: the machine boots from it, and no vm is given it
> hv create e2 /hvboot mem=64 disk=dev:nvme01
hv: nvme01 (part:...-000000000001) holds an ext4 filesystem labelled "devtest" -- the vm would have its data over it; give it anyway with force
> hv create d1 /spin.elf mem=64 disk=dev:nvme02
hv: /vms/d1/vm.toml written -- hv start d1 boots it
> hv create d2 /hvboot mem=64 disk=dev:nvme0
hv: nvme0 (disk:nvme-QEMU_NVMe_Ctrl_nosdevtesta) holds nvme03, an EFI System partition: the machine boots from it, and no vm is given it
> hv create d5 /hvboot mem=64 disk=dev:nvme02
hv: nvme02 (part:...-000000000002) is vm d1's disk already (its vm.toml names part:...-000000000002) -- two vms on one device wreck each other's data; give it anyway with force
  • never an EFI System partition or a BIOS boot partition, by their GPT types or the MBR's 0xEF -- not even with force -- nor a device that holds one or overlaps one: the whole disk the firmware boots from, which was once given and poured over where nos's root was on the other drive and nothing held the ESP's;
  • never a device something holds -- a mounted filesystem, the disk log, a guest running on it, netblk serving it for writing -- nor one overlapping something held: the disk under nos's root, a partition of a disk a guest has whole;
  • with force only, a device another VM's vm.toml names, or one overlapping it -- the whole of a disk one of whose partitions is d1's above -- one a VM being made or cloned is being given, a device while some VM's vm.toml cannot be read, which may name it, and a device with anything on it.

The look and the write of the vm.toml that names a device are one step: hv create and hv disk attach make both under the lock every change of a vm.toml takes, and a VM being made keeps the devices it was given with its name's hold until its vm.toml says so -- two VMs given one device at once were each told no other VM named it, and both wrote it.

hv create <name> ... disk=<device> and hv disk attach <vm> <device>[:ro] [force] give a device; hv disk detach <vm> <device> takes it off the vm.toml and leaves the device as it is -- both to a VM that is stopped, whose next start has them. Each writes the id, not the name it was given by (disks = ["part:6e6f7364-...-000000000002"]). The checks are made where a device is given and not at every start: once given, what is on it is the guest's, the filesystem it makes included. A vm.toml written by hand, or by the config_set call, is taken as it says -- the EFI System partition and the claims are still refused when it starts, and so is a device named by this boot's name (dev:nvme1), which the next boot may give another drive: the start says the id to write instead. The rest is the writer's to have checked.

While its VM runs, a device is its VM's alone. A start claims each of its devices for vm <name>'s disk in the block table, whose claims compare stretches of one physical disk: no mount, no disk log, no write of the shell's, no other guest can have that device or anything that overlaps it until the VM stops --

> diskwrite nvme02 0 55
disk 'nvme02' is in use by vm d1's disk

-- and a start that cannot have its claim is refused, saying whose the device is. A claim is one holder's, so :ro makes a device read-only to its guest but does not let a second VM read it: a device is one VM's at a time.

The queue. DiskQueue has the calls fs::image's queue has -- buffers lent between requests, a request started on one, reaped, waited for -- so a device disk and a file disk share the disk task's loop (modules/hypervisor/hv/src/disk.rs, its Media trait), and the module has no unsafe of its own for either. A request longer than the device takes at once is split into the commands it can take and given back when the last is done; a device busy with nos's own I/O is waited for as an image waits for it; and a device without the asynchronous path -- virtio-scsi in nos, and virtio-blk polled before its interrupt is in place -- is served a page at a time on the spot. What the guest's device offers follows the backend: discard where the device can give blocks back -- an NVMe whose controller has Dataset Management (ONCS bit 2), which nos now sends -- and not on a read-only disk; no write of zeros, which a guest then writes itself; and a device of 4 KiB sectors is shown in 512-byte sectors still, as every disk hv gives a guest:

A disk's sectors are 512 bytes, whatever its backend's block. A device of 4 KiB sectors and a volume of NBS's (4 KiB blocks) are shown to the guest with 512-byte sectors -- its logical block -- and the backend's block as the physical one (VIRTIO_BLK_F_TOPOLOGY, its least I/O a block): a partition table and filesystems laid out in sectors, as every distribution's image is, are read as they were written. Shown its blocks as its sectors (VIRTIO_BLK_F_BLK_SIZE), as it once was, Ubuntu's kernel looked for the GPT of its own image a block in, found no partition and stopped in its initramfs, its root's label nowhere. The device serves a read of part of a block from the blocks around it; a write of part of one reads them, merges the guest's sectors in and writes them whole -- alone: it waits for every write out to come back, and no write is handed over while it is out, or two of them in one block, or a whole one beside it, would write back each other's sectors as they were (blk::Pad; hv-fuzz's blk target holds a sector one write alone wrote to what it wrote, the backend serving in any order). A guest of 4 KiB-aligned I/O -- Linux, told the physical block -- seldom sends one: the partition tables' reads, a superblock's kilobyte, a FAT's sectors. A write of zeros is not offered on such a disk, and a discard gives back the whole blocks it covers.

A device poured from a cloud's image. hv convert <image> <device> [force] writes an image's disk onto a device -- qcow2 converted as it goes, a raw image copied -- and hv create <name> <url> onto=<device> [force] makes a VM of a download that way, its seed and vm.toml in its folder and its first disk the device:

> hv convert /pour.qcow2 dev:nvme04 force
hv: /pour.qcow2: qcow2, a disk of 6 MiB -- onto nvme04, 16 MiB
hv: nvme04: 6 MiB written in 0.0 s, the rest of the device given back to it

A device does not read as zeros where nothing was written, as a file's hole does, so the pour writes zeros wherever the image has none -- in order, through the same queue -- and gives back the rest of the device past the image's disk where the device takes a discard; an image bigger than the device is refused before anything is written, and size= is refused with onto=, the device being the size it is. What is poured is a qcow2 image or a raw disk: one with a partition table, or with what diskimage::contents knows a disk holds -- a filesystem, a RAID member -- or a start of zeros. An empty file, and one of bytes no disk holds -- a page of HTML -- are refused, where they were once poured, the empty one giving the whole device back to it. The checks are a given device's: force over what is on it, and never one in use. A pour cannot take back what it wrote: one that fails, or is stopped, says the device -- or the volume -- holds part of the image now, and a device that gives back none of its writes for two minutes is given up, said so, rather than waited for by hv convert, and the unload or the poweroff behind it, for good.

What the folder's commands do with a device. hv clone refuses a VM with one: the clone would share it, and two machines on one disk wreck it. hv delete takes away the folder and leaves the device as it is, saying so (hv: part:...-000000000002 left as it is -- a device of nos's, which a delete never touches; a volume of NBS's likewise). The vm provider's devices, disk_attach and disk_detach, and create's onto and force, are the same functions (On the management bus), and the panel's "Create" offers the devices that may be given, saying why a refused one was.

On the EX44 (5 November; bench/vm/results/comparison-device.md, one run each): the bench's Ubuntu guest on a 15 GiB partition of its own, under KVM as a raw disk and under nos given by its id, on the same CPUs. Against KVM on that partition nos's first write of a new file ran at 97% -- on a file of nos's root it ran at 78-80% of KVM -- its 4k reads at QD1 at 101% and at QD32 at 147%, its 1 MiB reads and writes at 100% and 95%, the kernel build at 99%, pgbench's read-write at 111-161%; its 4k writes at QD1 at 90% and at QD32 at 71% (169k IOPS against 238k), the one row where KVM gained more from the partition than nos did.

Its gate is tests/hv-device-test.py (x86-64): two boots over one root with two NVMe drives beside it, one partitioned by the test and one blank. The first boot gives each its id and has hv devices say what is on it, refuses the EFI System partition outright and an ext4 without force, gives a partition and a whole disk by their ids, refuses the disk under the given partition, pours a qcow2 image onto a partition of 0xFF bytes -- the host holding it to the image byte for byte after, its holes zeros -- boots hvboot on a partition by name, holds a running VM's device against the shell's write, and refuses a clone. The second boot swaps the drives: every id is found under the other name, the VM starts on its partition by its id, and a delete leaves the device alone.

A host's PCI device

A whole PCI function of the host's -- a GPU first -- given to one guest, which drives it with its own driver: what Linux's VFIO does for QEMU, with no user space between (plans/gpu-passthrough.md has the design, its stages, and the test machine). x86-64 with Intel VT-d, booted iommu=on:

> hv start gpu /vmlinuz initrd=/initrd.img mem=8192 cpus=4 pci=01:00.0 net

or in a vm.toml, pci = ["01:00.0"]. At most four functions a guest, named bus:device.function in hex as pci and iommu print them. A function one of the host's drivers has taken is not given -- a disk's, a NIC's: guestpci=01:00.0 at boot keeps every driver of the host's off it (docs/kernel-parameters.md), and it is the guests' to have from then on.

Its interrupts are remapped (arch/x86_64/vtd.cpp, VT-d's interrupt remapping, on with iommu=on wherever every unit taken over has it): every interrupt of the host's -- each MSI and MSI-X vector, each IO-APIC pin -- is an entry of its unit's table, verified to come from its own requester, and a compatibility-format interrupt is blocked. So a DMA write of the device's to 0xFEExxxxx, which is how a device interrupts, raises the device's own vector and no other: blocked, and said, whatever else it names. Where interrupts are not remapped -- a unit without IR, an IO-APIC no unit's scope names -- that write is an interrupt of the host's, of any vector, on any CPU, the TLB shootdown's, the scheduler's: pci= is refused there unless the guest is said to be trusted with that, unsafe_interrupts (unsafe_interrupts = true), as VFIO refuses a platform without remapping unless told allow_unsafe_interrupts. Every function given says which in the log.

What the module does with it (modules/hypervisor/hv/src/passthrough.rs), before any of the guest's memory is taken: a function a driver of the host's has taken is refused (PciDevice::driven: one that turned bus mastering on through kcore::pci, or said it was its own, take -- xHCI's and ATA's, which turn on none); a function the firmware reserved memory for -- a DMAR RMRR names it or a bridge above it (kcore::iommu::reserved, Vtd::reserved_for): a USB controller's legacy keyboard, an integrated GPU's stolen memory -- is refused, as VFIO refuses one: its DMA has to keep reaching the host's memory; the function is claimed -- one guest a function -- and the other functions of its IOMMU group are blocked, each in a domain of nothing, unless the guest holds them too; a group one of whose other functions is mastering -- the host's, or a driver's -- another guest's, or one the firmware reserved memory for is refused, said with the function and why they are one group.

IOMMU groups (modules/hypervisor/hv/src/groups.rs): the functions an IOMMU cannot keep apart, because what one sends may reach another peer to peer without passing it. ACS is turned on first wherever the host's functions have it -- Source Validation, P2P Request and Completion Redirect, Upstream Forwarding, as Linux turns it on where it has an IOMMU -- so that a port sends what comes up from below on up, where the IOMMU sees it. Then a function reaches everything below the bridge above any port on its way up that does not isolate (a switch's downstream port without ACS joins the switch's whole subtree, where Linux keeps each port's apart), what is below every function of a root port's device where one of its functions does not (a device of several root ports routes between them inside), and every function of its own device where it has no ACS of its own (a GPU and its audio function: one group); every pair so joined, and the closure, is a group. A function below a conventional bridge, or a PCIe-to-PCI one, is refused: its requests reach the IOMMU by the bridge's id. A bus two bridges claim is grouped not at all, and its functions refused. Every function given says its group where it has company (hv: 01:00.0: IOMMU group with 01:00.1 -- its device's functions, with no ACS); a group's bridges are left be -- they forward, and master nothing of their own. Its BARs are read with its decoding off, the screen held meanwhile: on a machine whose boot GPU is the one given -- Hertz's A2000 -- the kernel's console is that GPU's memory, the firmware's framebuffer in one of its BARs or, where GRUB hands nos none (Hertz), the EGA text buffer at 0xB8000 in the legacy window the firmware routes to the boot VGA, and a write to memory that is not decoded is an Unsupported Request. Where the console is the function's -- a BAR of its, or the legacy window of a VGA controller -- the screen lets go of it for good (FbTerm::release_within, VgaTerm::release_within, as Linux's vfio-pci takes efifb off its aperture): the reset ends that picture anyway, and the memory is the guest's. Then it is reset (ResetPlan): by its FLR where every function of the device the guest holds has one (as Linux makes one: its transactions given a second, the device asked until it answers); else the whole device by the secondary bus reset of the bridge above it, made once, by the first of its functions the guest names, before any of them is set up -- where the bus is the device's alone, as it is below a PCIe port; else it is given as it is, said. Either way its state is saved before and written back after, as Linux's pci_save_state keeps it: the header, the PCIe controls, each Resizable BAR's size -- a BAR a reset resized under its register would be mapped as one size and decode another -- and ACS's controls, the last two in the extended configuration space (x86-64: the MCFG's ECAM, a bus at a time, held to the port CAM's reading as it is opened at the scan; till then and where there is none, an access past 256 bytes reads all ones -- it used to read the header's again). And its interrupts taken by the host: its MSI-X where it has it, with its table and PBA in BARs given -- the real table the host's to program (kcore::msix::MsixTable, reached through a mapping of its BAR from its start, so that the kernel does not size the BAR again while it decodes), a vector of the host's for each entry the guest is given, MAX_VECTORS (16) at most, each a slot of the kernel's 64 (RUST_MSIX_SLOT_COUNT, their entry points generated in asm.asm) and an entry of its unit's interrupt table -- else its MSI (kcore::msix::MsixTable::new_msi). Once the guest's RAM is there, the function is moved to an IOMMU domain of it (kcore::iommu::Domain), every region at its guest address -- 2 MiB leaves where the RAM is the huge pool's -- so that its DMA reaches the guest's memory and nothing else. As the guest goes, in this order: the route of its interrupts to the guest, the interrupts and the host's table, bus mastering, an FLR, the domain -- the device left blocked, never passed through again while it may remember a guest -- and the claims.

What the guest sees is hypervisor/hv/src/devices/host.rs: the real configuration space, read through, with what has to stay the host's laid over it --

  • the BARs are the guest's: what it writes is where they are in its space, and sizing reads back the real size; the real registers are never written;
  • the command register's bus mastering goes to the device; its memory and I/O decoding are the guest's alone, the device decoding its memory for as long as the guest holds it, so that no access of the guest's finds it deaf -- an Unsupported Request, which a server may escalate to a machine check (CVE-2020-12888); INTx stays off;
  • its interrupts are emulated (host::Messages), MSI-X's where the function has MSI-X with its table and PBA in BARs given, else MSI's: what the guest writes -- MSI's capability, or MSI-X's control word and table -- is what the host's handler of the real vector sends it (LinuxGuest::deliver_msi), held pending while it is off or masked, MSI-X's PBA saying so, and sent once unmasked. MSI-X's table is as long as the guest is told: the device's, MAX_VECTORS at most -- a driver takes as many vectors as the table says there are -- and MSI-X's enable and function mask are the guest's alone, the real ones the host's. The one of MSI and MSI-X not given is not in the capability list the guest walks (the pointer that names it names the one after it), and none of its bytes is the guest's: a guest that turned MSI on where the host takes MSI-X would wait for an interrupt that never comes;
  • a capability's id and next pointer are read-only, whatever the device's are: a device that took a write there would have the guest change the list the host walked;
  • the expansion ROM a copy the host read of the device's, once, as it gave it (an image of 0x55AA, 2 MiB at most): the guest's ROM BAR its own to size, place and turn on, and where it is on, the copy mapped read-only -- read as memory, rep movs among it, a write nothing; the real ROM BAR, which on many devices shares a decoder with another BAR, never the guest's;
  • the INTx pin the device's, wired to a line nothing raises (run::HOST_IRQ): the device's INTx stays off and its interrupt is its MSI, but a driver that wants a legacy IRQ to exist finds one -- NVIDIA's refuses a function with neither that nor MSI-X; power management never out of D0; the PCIe device control's FLR, payload sizes and error reporting the host's, its phantom functions -- whose requests would carry another function's id, and so another IOMMU context -- and no snoop kept off; the link control the host's; the Advanced Features capability's FLR not reachable;
  • the header type's multi-function bit the guest's: set where its device has more than one function behind its port, whatever the device's says of functions the guest may not have;
  • every other register is the device's, written through, as QEMU's VFIO does.

Each device is behind a root port of the guest's (devices/port.rs), as on the machine: a PCIe endpoint's functions given one after another -- the module sorts them by their addresses on the host -- are one device's, behind one port on the next slot of bus 0, as functions 0 up of the bus below it, numbered after the ports before it (LinuxGuest::add_host_function): their numbers on the host less the first's, so a GPU's audio function is at 00.1 beside it, where Linux's hda_intel looks for its GPU, and a NIC's ports are one slot's, as its driver's link aggregation wants them; function 0's header type says the device has others. The port is Red Hat's (QEMU's, 1b36:000c, which Linux knows as a generic root port and has no quirk of): a type 1 header and a PCIe capability of a root port of no slot, and nothing else -- no interrupt of its own, no PME, no extended capability -- so that Linux's port driver binds and finds no service to start. Nothing of it reaches the device: its bus numbers are the guest's to renumber, and the run loop routes configuration accesses by them (Platform::host_config); its command register, windows and bridge control are the guest's to write and change nothing -- the device's BARs are mapped where its own registers put them, and a secondary bus reset resets nothing, as an FLR the guest asks for does not: a reset is the host's. Its link is the device's as it is at each read (port::Link: the device's own link capabilities and status, its speeds, its payload size), with no ASPM, no bandwidth notification and no slot: the guest's PCIe code has no link of its own to manage, and the device's link control is the host's. A function that is no endpoint -- an integrated one, a PCI device -- is alone on a slot of bus 0, as before. The BARs are placed as firmware places them behind a bridge: a 64-bit prefetchable one above the guest's RAM, any other below 4 GiB, where a port's memory window is, and each device's from a fresh MiB of each window, so that its port's windows -- whole MiBs, set where its BARs are -- hold its BARs and nobody else's, and the guest's Linux claims every BAR where it is.

A bridge, a function with neither MSI-X whose table and PBA are in BARs given nor MSI, and one whose capability list loops, runs on, or has a second capability of a kind the host keeps registers of, are not given: a guest writes at any offset it likes, and every register the host keeps has to be in a capability it found.

Some pages of its BARs are left out of the mapping, and every access of them traps and is answered on the view above (host_mmio, HostFunction::trapped; an access not aligned to its size a byte at a time, eight bytes of the table or the mirror as two dwords):

  • MSI-X's table and PBA, every page they have a byte in: the guest's table and its pending bits, emulated -- mapped, the guest would program the real entries and, where interrupts are not remapped, send any vector of the host's. A page they share with registers of the device's own has those passed through to the real page an access at a time, as VFIO does: QEMU's NVMe has its table right after its doorbells, in their page;
  • NVIDIA's mirror of the configuration space in BAR0 at 0x88000: each access of it is one of the view above. A write within the MSI capability's id and next pointer is also passed to the real mirror -- the driver acknowledges its MSI so, and without it the GPU sends one interrupt and no more (QEMU's vfio_nvidia_quirk_mirror_write) -- and only within them: a write that reached the control word past them would be the guest's to the host's own MSI. Since Pascal the re-arm is a dword at 0x704 of the mirror instead (nouveau's gp100_pci_msi_rearm), past the first 256 bytes: that dword alone is written through to the real mirror, as VFIO lets a write there reach the device; the rest of the mirror's extended space is the guest's view of it below, read-only.

PCI Express's configuration space (ECAM): bus 0 presents Q35's root complex (8086:29C0), with CF8/CFC kept beside it. Every Q35 guest has its extended space, 4 KiB a function, at linux::ECAM_BASE (0xE0000000, buses 0-255, a MiB each), a window every access of which traps (GuestMemory::trap_range) and is answered as one through the ports is (ecam: pci::ecam_target names the function and the register; bus 0's emulated functions by the bus, PciBus::function_read, a host's slot or a bus below a port by Platform::host_config). The MCFG names it, a motherboard resource in the DSDT (PNP0C02) reserves it and so does the memory map -- Linux takes ECAM only where it is reserved -- and the host bridge's _CRS gives buses 0-255, which ECAM has to cover. A host's function's extended space is the device's, read-only, with the capability list the guest walks cut to those there to read (host.rs's EXT_SHOWN): AER's error status, the virtual channels, the serial number, a vendor's (VSEC, DVSEC), LTR, the link's; none it would have to write to use, since a write reaches nothing -- SR-IOV, ARI, ATS, PRI and PASID, which are the IOMMU's, the Resizable BAR (its BARs are the size the host gives), ACS, DPC, PTM, TPH, DOE and the power budget's are not in the list. Each one shown names the next one shown; the first dword, where the device's first is not shown, is a header of none naming the first that is; a list that loops shows none. An emulated function's and a port's extended space is empty: zeroes.

Every Q35 guest's memory has a hole for the BARs (LinuxGuest::new_holed): its RAM below 4 GiB ends at 3 GiB (linux::HOLE_RAM_END), its BARs that are not 64-bit and prefetchable go from there up to ECAM and the MSI-X pages, the rest from the first GiB past its RAM -- both windows in the DSDT's _CRS, so that Linux keeps each BAR where it was put. The 64-bit window there reaches only as far as the BARs placed in it, in Cloud Hypervisor's 8 MiB units: the rest of the guest's addresses are its OS's own, and Linux's HMM takes a GPU's VRAM's worth of them for the device memory NVIDIA's UVM registers the GPU with -- with the window up to the top of them none was left, and CUDA was refused ("initialization error"). The memory map -- which reserves ECAM, at the top of the hole -- and the kernel's and initrd's places are planned for the same layout (linux::plan_below, pvh::plan_below), and a layout planned for the other kind of guest is refused by load: its map would hand the kernel the hole as RAM. A BAR is mapped straight into the nested table, uncacheable (the guest's PAT makes it write-combining where its driver asks), 2 MiB at a time where aligned; one the guest moves is mapped anew, and one it moves over RAM, another BAR or the platform's pages is left unmapped -- an access of it stops the guest. A VM holding a host's function is not saved and not moved: its device's DMA reaches no dirty log, and its state is the device's.

hv pci says each function the host has as this module would give it, read and nothing changed (passthrough::survey, hostpci.rs): its ids and class, a driver's or kept for guests, its reset, its interrupts, its IOMMU group as it will be with ACS on, the VMs whose vm.toml names it, a guest holding it, and why not where it cannot be given -- as QEMU's topology of the passthrough gate has it:

> hv pci
00:04.0 1b36:000c 06.04  free  reset none  MSI-X 1  -- not given: a bridge
01:00.0 1b36:0010 01.08  kept for guests  reset FLR  MSI-X 65  group 01:00.1
01:00.1 1af4:1042 01.00  kept for guests  reset FLR  MSI-X 3  group 01:00.0
02:00.0 1af4:1042 01.00  kept for guests  reset bus reset  MSI-X 3
03:00.0 1af4:1044 00.ff  kept for guests  reset FLR  MSI-X 2  group 03:00.1  -- not given: its IOMMU group holds 03:00.1, the host's

hv pci attach <vm> <bus:dev.fn> puts a function on a stopped VM's vm.toml -- refused where the survey says it cannot be given -- and detach takes it off; the vm provider's pci, pci_attach and pci_detach are the same through the API, and the panel lists them with the VMs.

Not done yet: AMD-Vi. VT-d's posted interrupts -- the device's message straight into the vCPU, no host interrupt -- wait for a machine whose unit has them (CAP.PI): Hertz's two have not (CAP 0xd2008c40660462 and 0x1c0000c40660462, bit 59 clear), nor has QEMU's.

Gates: hv-fuzz.py's hostfn target (the view above against a model of the real function: whatever the guest does, what reaches it holds to the host's rules -- MSI-X's real table and PBA never reached, a page reached only where it traps -- and what the guest sees to the PCI spec's -- a BAR decoded from its registers, MSI-X's table, PBA and capability list among it; each rule of host.rs a mutant it catches, tests/fuzz/hv/mutants.py), the platform target's guest holding a GPU (the run loop's bus, mirror, BAR moves and MSIs), and the linux and pvh targets' holed layouts, the pci target's ports (only the configuration data's are a host function's, whatever the address latched names: a disk's notify once went to the GPU's space instead, and the guest's disk stopped as NVIDIA's driver probed); iommu-test.py for the domains; hv-passthrough-test.py, QEMU's NVMe behind its VT-d given to a Linux guest of nos's under TCG -- its driver reading, writing and taking its MSI-X, more than one vector of it, and then, the driver let go of, the controller driven by hand to write where the guest has no RAM (blocked, said with its requester) and at the interrupt range (refused by nos's table, said); and on a machine with a GPU, by hand, gpu-passthrough-test.py: on Hertz an RTX A2000 in nos's guest -- with NVIDIA's own driver (580, the open modules), nvidia-smi naming the GPU and CUDA's deviceQuery, vectorAdd and matrixMul passing; or with nouveau, its GSP booted by DMA through the domain and a thousand fences each waited for on the GPU's MSI, sent on by hv (docs/testing.md).

A network

net, on hv start, gives the guest a NIC on the guests' switch, and with it an address: 10.0.100.2 for the first port, .3 for the next, handed to its kernel on the command line (ip=). nos is 10.0.100.1 on the same subnet, so the guests reach it, and it reaches them -- ping 10.0.100.2 from nos's shell goes out of the device whose subnet the address is on -- and guests on one network (network=) reach each other once their firewall lets their network in (The firewall):

$ hv fw create lab
$ hv fw lab add allow in from net       # the network's guests reach each other
$ hv fw lab add allow in tcp 80         # and anyone its port 80
$ hv start /bzImage initrd=/initrd net network=lab firewall=lab cmdline=console=ttyS0 nolapic
$ hv start /bzImage initrd=/initrd net network=lab firewall=lab cmdline=console=ttyS0 nolapic
$ hv exec 0 ping -c 3 10.0.100.1        # nos
$ hv exec 0 ping -c 3 10.0.100.3        # the other guest, on lab too
$ ping 10.0.100.2                       # from nos
$ hv forward add 8080 1 80              # nos's 8080, to guest 1's 80

A guest is alone on the switch unless its network says otherwise. A port is on a network -- network=<name> on hv start, network = "..." in a VM's vm.toml -- or alone, and a guest reaches the other guests of its network as on one LAN and no other guest at all: one alone, as every VM is that names no network, reaches nos and, through NAT, the world, and that is all. A frame for another network's guest goes nowhere, counted against the guest that sent it in hv list (N frames for another network's guests, dropped); one for every port goes to its own network's and hv0; and IPv6's first-come bindings are each network's own. Nothing goes from one guest to another through nos either: NAT takes nothing for the guests' own subnet, and the stack forwards nothing. hv list says each port's network or alone, and so does hv vms of a folder's. A guest on a cloud's machines is in the same place -- its tenant's network, and nobody else's.

The gate is tests/hv-linux-test.py --net, whose two guests are on one network and ping each other, and whose VM from a folder, alone, pings nos and gets nothing from the other network's guest -- not by ARP, whose question that guest never hears, and not by a frame sent to its MAC, which the switch drops and counts. The hv fuzzer's switch target puts the ports on two networks and alone, and holds every delivery and every count to its model; eight mutants -- a frame to another network's guest let through, a broadcast to every port, a send whole or a checksum left to finish taken to another network, IPv6's bindings one table for all, every port alone, a port's network kept past its release, nothing counted -- each fail it.

A port changes hands with frames for it on their way -- one VM gone, another taking its port -- and so what the switch looks at without a lock it asks again under the port's inbox lock, where the owner, its network and what its NIC takes change together: a frame meant for the VM going reaches the VM coming only if that one is of the sender's network, and a send whole or a checksum left to finish reaches only a NIC that says, by then, it takes it so. The switch target makes that moment: a hook in its spin locks hands a port over just before one of the locks a send takes, and every guest is held to what some order of the hand-over, the new NIC's word and the send gives -- the frame lost, at most, to the VM going or coming. Seven mutants of the checks under the lock each fail it; four of them nothing but that moment shows.

The guest's NIC is virtio-net, legacy, on the same transport as its disks (hv::devices::net): two queues, a MAC and a link status offered, and offloads both ways (below), legacy's header in front of every frame either way -- ten bytes, twelve once the driver takes mergeable buffers. A send is cut, or handed on whole, before the notify returns; what waits for the guest is put into the buffers it has posted each time round the run loop, one frame held by the device while it has posted too few.

A queue pair for each of the guest's CPUs (VIRTIO_NET_F_MQ, with its control queue, F_CTRL_VQ): a guest of more than one CPU -- which has MSI-X -- is offered as many pairs as it has CPUs, up to eight, and a control queue after them, through which its driver says how many it uses; the device uses the first alone until it does, and refuses a count past those offered. Each queue has its vector, which Linux gives each CPU its own of: what a CPU sends it is told of on that CPU, and what comes for it is taken there, its NAPI poll on that CPU's softirq, where one ring and one interrupt had every CPU's traffic go through one. A frame for the guest goes to the pair the guest last sent its flow from -- virtio's automatic receive steering, a table of 256 slots by a hash of the flow's two ends, learned as it sends -- and a flow it has not sent to the pair its hash picks. The one frame the device holds for want of buffers is the device's and not a pair's: held for a ring that is empty, it holds up the frames behind it for the others until that ring's refill, which the device asked a notify for; and when the driver changes how many pairs it uses, the device delivers at once, steered anew -- a frame held for a pair the driver had just stopped using waited on a notify that would never come, and every frame behind it with it, which the hv fuzzer's virtq target found at its 1,825th input. The report says how many pairs the driver uses (hv stop). Under TCG, Linux 6.18 on two CPUs through hv-linux-test.py --net --cpus 2 took both pairs, and its receive interrupts each on its own CPU: 41 of the first pair's on its first CPU, 72 of the second's on its second.

Offloads, both ways. The device completes a checksum the driver leaves to it (VIRTIO_NET_F_CSUM) -- a UDP datagram's that comes to 0 as all ones, over IPv4 or over IPv6 past its extension headers, since 0 there is no checksum at all and IPv6 refuses it -- and cuts TCP over IPv4 the driver hands it as one send of up to 64 KiB into frames (HOST_TSO4; hv::devices::offload): the headers of the send in front of each, its IP length, ID and checksum, its sequence number and its TCP checksum its own, FIN and PSH the last one's, CWR the first's. What the driver says about either -- where a checksum goes, where the headers end, the segment size -- is checked against the frame before it is used, and a send that does not hold up is dropped, counted. Not offered: ECN on a cut send, IPv6, UDP. A segment of 8 bytes is taken, the least Linux's TCP makes (TCP_MIN_GSO_SIZE): a guest talking to a peer with a small MSS cuts its sends small, and refused under 256 bytes they were dropped whole, the guest never told -- its connection down to the one segment its TCP sends unsegmented after a timeout. What a notify may cost is held by the pass instead: a transmit pass ends at its bound on the frames it made or the bytes it copied out of the guest (1,024 frames, 1 MiB -- a ring of Linux's largest sends is one pass), the next round going on with the rest, where a ring of 64 KiB sends cut at 256 bytes was 65,536 frames and 16 MiB under the platform's lock for one notify.

Between two guests, the switch does neither where it need not. A guest whose driver takes checksums left to finish (GUEST_CSUM) is handed a frame its sender left so as it was sent, the header saying where -- Linux takes it as checked, as it does what comes over its own loopback; one that takes sends whole too (GUEST_TSO4, with mergeable buffers to spread one over, MRG_RXBUF) is handed a send of up to 64 KiB as its sender made it, the header saying the segment size to cut it by should it be forwarded. Everyone else -- nos's stack through hv0, NAT, a guest whose driver takes neither -- is handed whole frames, finished and cut on the way out of the switch, as before. The device tells the switch what its driver takes when it says so; a frame put in before a driver took other features is the device's to finish, and a send its driver no longer takes whole, to drop. A port keeps room for eight sends of 64 KiB beside its frames, taken when it is claimed.

nooffload on hv boot or hv start offers the device without any of them. On the EX44 two guests of two CPUs, one serving a file of 100 MB five times over with BusyBox's httpd -- sendfile, sends of 64 KiB -- and the other fetching it: 0.47 s with them, 1.63-1.68 without, 1.1 GB/s against 320 MB/s -- the fetching guest took 8,500 sends whole where it had taken 362,000 frames. With the sending side's alone, the sends cut in the switch, it was 1.11 s. A sender whose TCP hands the device a segment at a time, dd | nc, is 7% slower with them: 4.45 s against 4.15, five runs each. Offered one at a time, most of that is the sending side's checksum (4.34 s; TSO adds nothing to it, and mergeable buffers alone cost nothing, 4.16), with the exits and the guest's IPIs alike either way: a Linux driver that leaves its checksums to the device gathers each frame from pages too -- scatter-gather comes on with them -- three or four descriptors a frame where it was two, and every descriptor and buffer the device reads is a guest page mapped and unmapped on the host, one access at a time: the likeliest cost, and the rings' pages mapped once took most of it away: 2.83 s against 2.72, the two within their spread (Its memory). A checksum the device finishes it sums eight bytes at a time, since two bytes at a time made that 3-5% slower than the guest's own, taken as it copies. hv-fuzz's offload target holds every send, well made and not, to a model of its own, frame by frame; two mutants -- PSH on every frame, one IP ID for all -- each failed within three inputs. Its netrx target holds what goes into the driver's buffers to another, and switch where each send and frame goes, whole or finished; six mutants -- the buffer count one too many, a partial checksum not finished for a driver that takes none, a send whole to one that takes none, the switch not told what a driver takes, a partial checksum or a whole send handed to every port -- each failed within 17 inputs.

nos's end is a virtual NIC, hv0, in its own stack (layers/net/src/vnic.rs). A module cannot register a NIC -- there is no C name for a driver to be bound by -- so the device is registered from inside the image, the first time a module asks for it by name, and stays; the module trades frames with it through kcore::vnic. What the stack sends out of hv0 goes to the sink the module attached, from the transmit path with interrupts off, and what the module hands in arrives as if received, on the next receive pass. A detach waits out any call of the sink still running, so the module can go after -- the UDP listeners' way.

The switch is the module's (modules/hypervisor/hv/src/net.rs). A guest's NIC is a port, and a port's number is its address and its MAC (02:00:00:00:64:NN), so frames go by their destination MAC with nothing learned: to a port, to hv0, or to everyone for a broadcast or a MAC no port has. A port's inbox holds 256 frames, the guest's receive ring's worth, and is filled from any CPU -- hv0's sink among them, interrupts off -- so it is a spin lock with interrupts off over storage taken when the port is first claimed, and kept for the next VM on it; a full one drops, counted in hv list. A frame put in wakes the guest's vCPU: a halted guest waits on its VM's event, until its timer's next edge or something for it -- a frame, a key typed at hv attach or hv send -- whichever comes first (Event::wait_for, the scheduler).

What the guests share is shared out. hv0's backlog -- the 256 frames handed in and not yet taken by the stack's receive pass (kcore::vnic::BACKLOG), which every guest's traffic to nos and through NAT goes on -- takes from a port, between two of the stack's passes over it, no more than its share: the backlog over the ports a VM has, so a guest alone has all of it and one of several sending as fast as it can leaves the rest theirs. The switch learns of a pass from the count of them the virtual NIC keeps (Vnic::drains) and counts each port's share afresh from it. And what a guest sends to every port -- a broadcast, a multicast, a MAC no port has -- is a copy into every inbox and a wake or a kick of every VM: 64 at once and 256 a second after, a token bucket a port. What either keeps out is dropped and counted against the guest in hv list.

What a guest sends has to be its own. A frame is checked where it comes in at a port (ingress), as a cloud's virtual switch checks it: IPv4, ARP or IPv6 -- nothing the switch cannot check goes through it -- from the port's MAC; an IPv4 packet from the port's address; an ARP message with the port's MAC as its sender's, and the port's address as its sender's or none yet, as a probe has; IPv6 by rules of its own (below). The one IPv4 packet with no address yet is a DHCP client's, which the switch answers itself. The rest is dropped: a frame sent as another guest counted against the guest that sent it in hv list, one of another protocol on hv0's line. Without it a guest could take another's flows through NAT, which answers a flow at the MAC its last packet came from -- one packet with the other's address and the flow's ports was enough -- and tell hv0's ARP table another's address was its own. hv-fuzz's guestnet target found that (testing).

IPv6 goes between the guests, and no further. Nothing of nos's speaks it, so hv0 is handed none -- a guest's IPv6 for nos's MAC is dropped on hv0's line -- and there is no way out: no NAT, no route. Each guest makes its own addresses: its link-local one, and one in the prefix the switch gives it, fd6e:6f73:64::/64 -- unique-local (RFC 4193), its global ID "nos" and 100, the third byte of the guests' IPv4 subnet -- which the switch's router advertisement carries, answering a guest's solicitation: from hv0's MAC and the link-local address it makes, the prefix on the link and to make addresses in, for good, the MTU 1500, and a router lifetime of 0, so no default route and a connect anywhere else refused at once. Since the addresses are the guests' to choose, they are not checked against the port as an IPv4 address is, but bound to the port that first uses one (RFC 6620's first come, first served): as the source of a packet of its, as the target of its neighbour advertisement, or as the address its duplicate detection asks after, if it is nobody's yet. From then on it is that port's alone until its VM goes -- eight a port, a ninth taking the place of its least recently used, so privacy addresses come and go -- and another sending from it, or advertising it, is spoofing, counted against it. A guest's duplicate detection of another's address goes through, for the owner to answer, so a guest asking for a taken address is told so. A guest is no router here and no DHCPv6 server: its router advertisements, redirects and DHCPv6 replies go nowhere (RFC 6105's guard); its neighbour discovery must give its own MAC wherever it gives one, a target that is one address, and come whole, not in fragments (RFC 6980); its source is none only while it finds an address -- a solicitation, a listener's report -- and never a multicast group. A packet whose extension headers hide what it carries -- running past its length, more than eight of them, a first fragment that stops short of the header after them -- goes nowhere, since a router advertisement could be one (RFC 7112); and the packet the switch looks at is the one its receiver takes, to the length its header says, so the two cannot read different messages out of one frame. hv list counts the advertisements and the addresses bound. hv-fuzz's switch target holds the switch to a model of these rules of its own, frame by frame, with neighbour discovery of every kind among its frames, and hv-linux-test.py --net two Linux guests: each makes its address from the advertisement, they ping each other at it and at their link-local ones, one asking for the other's address is told it is taken, and one that takes it anyway gets nothing through to the other.

A guest that is running is kicked out of it. Its turn ends when its CPU takes an interrupt, and the device model hands frames over only between turns, so a frame for a busy guest used to wait for the host's next tick -- ten milliseconds, while at line rate the port's 64-frame inbox fills in under one. On the AX41 a guest that apt-get updated, fetching over several connections while it decompressed, lost some 1,400 frames that way and took 39 s over 28.5 MB. Now the switch kicks the vCPU as KVM does (hvarch::x86::svm::Kick): the vCPU marks itself on its way in before its last look at the inbox, a sender that finds it so marks it exiting and interrupts its CPU (kernel_cpu_kick, straight to the interrupt controller, from any context), and Guest::run looks at the mark once more with interrupts off: a kick from before that point turns the entry back (Exit::Kicked), one after it is an interrupt held pending, which ends the guest's turn as it begins. One interrupt per entry at most, however many frames come; hv list counts them (kicks).

Measured on the AX41 in one boot, the same Debian guest and three builds of the module loaded in turn, a cold apt-get update (28.5 MB) and a gigabyte from Hetzner's speed-test server each:

build apt-get update frames dropped 1 GB
no kick, 64-frame inbox 16 s, 10 s 100, 44 52, 42 MB/s
kick, 64 frames 7 s, 8 s 437, 141 61, 60 MB/s
kick, 256 frames 9 s, 7 s 0, 0 68, 56 MB/s

The kick halves the fetch and lifts the bulk rate by a fifth to two fifths (about 220,000 kicks for the gigabyte, one per three frames). With frames flowing that much faster the 64-frame inbox overflowed more on apt's bursts than it had without the kick, and at 256 -- the guest's own ring -- none was lost. What the gigabyte still loses (500 to 800 frames) is the guest's own ceiling: one vCPU takes each frame through a legacy virtio interrupt and the 8259's, several exits apiece, at 55 to 70 MB/s, and TCP paces to it. That is the next thing to take out: fewer exits per frame, not more room for them.

Receive interrupts, moderated. A guest that takes its frames faster than they come takes an interrupt for every one and acknowledges every one or two: two guests of two CPUs sending TCP to each other through the switch got 1.1 frames an interrupt, and the receiver sent 140,000-180,000 ACKs for 500 MB. So a NIC's receive interrupts are held at least 100 us apart (Net::set_rx_moderation; rxmod=US on hv boot and hv start, 0 for none), as a real NIC's interrupt throttling holds them: what arrives goes into the guest's buffers at once, its interrupt waits until the time since the last is up, and then one takes all that came; a frame after a quiet spell is interrupted for at once. Meanwhile the switch kicks nobody for a frame -- a kick each would hand each over alone -- unless the port's inbox is half full (Backend::quiet_until), and the vCPU that does the devices' work comes back at the end of the window on its own (Net::rx_due): slept to when its guest is halted, and armed on its host CPU's timer before each entry otherwise, one more timer edge (Time). On the EX44, the TCP pair, three runs at each window, taken in turns:

window frames an interrupt receiver's ACKs 500 MB
none 1.12-1.17 137,000-176,000 4.57-5.15 s (4.88)
25 us 2.6-2.8 140,000-168,000 4.47-5.22 s (4.72)
50 us 4.7-5.0 102,000-144,000 4.13-4.80 s (4.57)
100 us 9.7-10.2 63,000-87,000 3.94-4.07 s (4.01)
200 us 20.0-20.5 33,000-47,000 3.70-3.86 s (3.77)

The cost is latency where frames come close together: a hundred small HTTP fetches between the two, each its own connection, took 0.07 s with none, 0.05-0.07 s at 50 and 100 us and 0.08-0.09 s at 200 us; a ping's round trip, 0.24-0.30 ms on average, was the same at every window. Hence 100 us. hv-fuzz holds the NIC to raising what it owes by the time it said it would look again -- which found a queue taken down owing for good, a round the run loop would have made without a pause -- the switch's wakes to a model that knows each port's window, and runs whole machines with it on and off. What it did not see is a window opened behind that vCPU's back: a driver refills its receive ring from the CPU its interrupt is taken on, and that CPU's notify delivers what waited and raises the interrupt itself -- so the first CPU, asleep with the old window's end in mind, slept to its 10 ms cap while the frames that came in the new one woke nobody. Pings between two guests had a 10 ms answer every few hundred; a notify from another CPU that moves the window now rings the first CPU, and 2,400 pings had none, 0.19 ms on average and 0.28 at most.

hv forward is how a guest is reached from outside. The guests have addresses only on their switch; a forward listens on a port of nos's -- on the device the guests go out through by NAT, the default route's, which is the one the world reaches them by (eth0 while NAT is off): on a machine whose uplink was not its first NIC, a forward on eth0 said it was made and was reached by nobody -- and hands each connection to a relay task of its own, which opens one to the guest's port through hv0 (kcore::tcp::TcpStream::connect, new for this) and relays the two. The connect is the relay's: one to a guest that does not answer waits out TCP's five seconds there, where the listener once did, every other client and the forward's own stop waiting behind it. The kernel has 64 TCP connections and a forwarded one takes two, so a forward carries eight at once and refuses the rest. A relay ends when either side's stream ends: there is no half-close, the kernel's TCP having no way for a program to end its sending and go on reading, so a client that shuts its sending side and waits for the answer (nc -N) gets none; and an idle relay looks at each side every few milliseconds, there being no event to wait on for two connections. A relay one side of which takes nothing for a while is given up, counted (given up stalled in hv forward) and said, with the client's address and the guest's, in the network's file log, /logs/net.log (File logs), beside TCP's accept of it. Its listener is a bulk one (TcpListener::bind_bulk): a connection it accepts has buffers of up to 512 KiB each way and scales its window, where a connection's own 8 KiB would hold a client 62 ms away -- the EX44 from a desk in another country -- to 120 KiB/s, whatever the line; and while bytes move, its relay waits a millisecond on the side that has nothing rather than five, which held a download to 4 KiB a round. The other way, the guests reach the world through NAT (next). A client is held to the guest's firewall as its connection is accepted: one its rules do not let in at the guest's port is closed on, counted (denied in hv forward), and hv forward add says so when the firewall lets nobody in there.

The firewall

Every VM's NIC is judged by a firewall, both ways, at its port of the switch (plans/vnet.md, "The firewall"; common/net/firewall, the switch's judged). A firewall is a policy for each direction and up to 64 rules, the first that matches deciding; what no rule matches meets its direction's policy. A VM that names none is judged by default -- what comes in denied, what goes out allowed, no rule -- so a VM is closed until something opens it, its own network's guests included: two VMs of one network reach each other once their firewall says allow in from net.

$ hv fw                                     # the host's firewalls, and the VMs on each
$ hv fw create web                          # in denied, out allowed, no rule
$ hv fw web add allow in tcp 22 from 203.0.113.0/24
$ hv fw web add allow in tcp 80,443         # from anyone
$ hv fw web add deny out tcp 25 at=1        # first: no mail out
$ hv fw web                                 # its rules, each with the flows it judged
$ hv fw set vm1 web                         # vm1's vm.toml says it; a running vm1 judged by it at once
$ hv fw web del 3 | move 2 1 | policy in=deny out=allow
$ hv fw delete web                          # only one no VM names; default never

A rule is allow|deny in|out [tcp|udp|icmp] [ports] [from|to any|net|<a.b.c.d/n,...>] -- ports a list and ranges (22, 80,443, 8000-8100), net the VM's own network on the switch. A firewall is a file, /etc/hv/firewalls/<name>.toml (in, out and rules, as a person writes them), written whole on every change and then put in its place in the switch: every VM on it judged by it from the next frame on, and their open flows judged again -- those it no longer lets through cut, and said. A VM names its firewall in its vm.toml (firewall = "web"), on hv start (firewall=web), on hv create, and in the panel as it is made; one whose firewall's file cannot be read does not start, and says why -- neither open nor stood in for by default.

What is judged, and what is not:

  • Flows, not packets. The first packet of a flow -- TCP's, UDP's, an echo's -- is judged by the rules; a flow they let through is remembered in the port's table, 2048 flows a port, and its packets and its answers go by without the rules after that, and so do ICMP errors about it -- path MTU discovery is nothing without them. Its times and TCP's states are NAT's (netwire::flow), but for a connection answered and not closing, which lives five days. A full table gives up the flow its VM used least lately, never another VM's. A TCP segment of no flow that starts nothing -- of a connection whose flow ran out while it was quiet -- is judged as its connection's first would be, and picked up where it is.
  • The host's own traffic is not judged: what comes from or goes to hv0's address -- DHCP and DNS, the host API a panel's VM reaches, ping from nos's shell. The host is the VM's hypervisor. Nor is ARP, nor IPv6's neighbour discovery.
  • A deny going in is dropped without a word; one going out is answered to the VM -- ICMP communication administratively prohibited, from its gateway, no more often than a rate -- so that its connect fails at once.
  • IPv4 fragments to and from a VM are dropped: they carry no ports. IPv6, which only a network's guests carry between themselves, reaches a VM whose firewall lets its network in, or whose inbound policy allows.
  • A port that changes hands has its table emptied as it is claimed, and a delivery is checked against the owner's claim under the inbox's lock: a VM coming onto a port is never handed what the flows of the one before let in.

What it judged is counted: each rule's flows and each policy's in hv fw <name> (and the fw provider's rules), what each VM was denied each way in hv list, and each packet kept out as a tracepoint of the fw group (fw_deny, docs/tracing.md) -- not a line of the log. A VM made before firewalls is given one at its first start under an hv that has them: default, or -- one with forwards -- a firewall of its own name letting in at each forwarded port, so that what hv forward reached stays reached; hv start says which. api panel create gives the panel's VM its own, panel, letting in at its 443 alone.

A firewall is checked without a guest by a probe (hv probe): a port of the switch with no VM behind it, on a network or alone and judged by a firewall as a VM's NIC is, whose task answers ARP, echo and UDP to port 7, and which pings and sends UDP from the port as a guest's NIC does -- each run answered, refused (communication administratively prohibited) or nothing:

$ hv probe add a network=lab firewall=lab
$ hv probe add b network=lab firewall=lab
$ hv probe ping a 10.0.100.3               # b, from a: 3 echoes sent, 0 answered -- lab lets nothing in
$ hv fw lab add allow in from net
$ hv probe ping a 10.0.100.3               # 3 answered
$ hv probe udp a 10.0.100.3 7 sport=40999  # one flow, run after run
$ hv probe del a

On the management bus the host's firewalls are the fw provider's -- list, rules, get, create, delete, policy, add, remove, move, assign -- a page of the panel's of their own; the vm provider's create takes firewall, which the panel's form offers as a list of them (the descriptor's choices, docs/mgmt.md), and each VM's row says its firewall.

The gates: tests/vnet-test.py boots nos with probes where guests would be -- closed by default, a rule opening it, a deny outwards answered, a change cutting a flow, each denial a fw_deny, rmmod hv with probes up; the hv fuzzer's firewall target holds the crate -- rules, flows, the judge -- to a model of its own that shares nothing with it; fwswitch holds the switch to it, a closed and an open firewall on a network's ports, a port handed over between a judgement and its delivery, whole sends, the host's frames, a forward's clients let in or kept out by the VM's firewall; switch and guestnet run with every port allowed, their models unchanged. tests/fuzz/hv/mutants.py (hv-fuzz.py --mutants) takes out twenty-one of the rules -- the first match, an echo's direction, the stray check, the oldest flow evicted, a change cutting the flows it denies, a delivery held to its claim, the host exempt, a forward's client held to the firewall -- and each must be found.

The way out: NAT, DHCP and DNS

$ hv exec 0 wget -q -O - http://10.0.2.2:8000/    # a server beyond nos
$ hv exec 0 udhcpc -i eth0 -q                     # the switch answers
$ nat
nat: on, hv0 (10.0.100.1) out through eth0 (10.0.2.15); 4 of 4096 mappings, ports 32768-36863
  tcp 10.0.100.2:47410 -> 10.0.2.2:8000 as 32768, 7190 s left
  udp 10.0.100.2:37716 -> 10.0.2.3:53 as 32771, 297 s left
out 53  back 744  mapped 4  taken from the most 0  no room 0  no next hop 0  no frame 0  refused 0  denied 0

NAT is the network layer's (layers/net/src/nat.rs), not the module's: it is forwarding between two of the stack's devices, and it has to look at every packet either of them receives before the protocols do. While the switch exists it holds NAT on (kcore::net::Nat, a guard: dropped with the switch, it turns NAT off) from hv0 out through the device nos's default route is on -- eth0, with the gateway its DHCP lease named. A guest's packet for an address off its subnet, and not one of nos's, arrives on hv0 sent to its gateway, 10.0.100.1; instead of the protocols it goes to NAT, which gives its flow a mapping -- an external port of nos's, 32768 up -- rewrites its source to eth0's address and that port, one hop less to live, and sends it out of eth0 to the next hop. What eth0 receives for a mapped port, from the address and port the flow went to and nothing else, is rewritten back and sent to the guest; so is an ICMP error quoting one of the flow's packets, the packet it quotes made the one the guest sent. Whatever else arrives is the stack's, as before -- a port hv forward listens on is not NAT's unless a guest's flow has it, which it cannot, being below 32768.

What it takes: TCP from a SYN on (a segment of a flow it has no mapping for is dropped, not mapped mid-stream), UDP, ICMP echo; not fragments, not other protocols, and nothing inbound that a guest did not start -- that is hv forward's.

Where a guest may go is the world past nos's edge, not what is behind it. NAT keeps the guests from link-local (169.254/16, where a cloud's metadata server answers at 169.254.169.254, the host VM's credentials behind it), the private networks (10/8, 172.16/12, 192.168/16), carrier-grade NAT's shared space (100.64/10), where some clouds keep theirs, and the uplink's own subnet -- the host's LAN, its neighbours -- whatever that is. A guest's packet for any of them is not mapped: it is counted (denied) and answered with an ICMP destination unreachable, communication administratively prohibited, from 10.0.100.1, quoting it -- so its connect fails at once, "No route to host", rather than waiting out its retries. The DNS server the guests are given is theirs to ask at port 53, wherever it is (10.0.2.3 under QEMU's user network; on a cloud, the metadata server's address). nat allow <net> lets a network through -- the test machine, under QEMU, is on the uplink's subnet at 10.0.2.2 -- and nat deny <net> takes that back; up to 16, kept while NAT goes off and on, as the host's word. nat says what is kept and what is let through. The rule is a pure function (kept) the boot self-test checks; hv-fuzz's nat target holds every packet to a model of its own (nothing to a kept network out, every reject right, the list as nat allow and nat deny left it). A mapping lives while its flow is seen and RFC 5382's and 4787's times after: two hours for a TCP connection that has been answered, four minutes before that and after a FIN, ten seconds after a reset, five minutes for UDP, one for an echo. The checksums are updated for what changed rather than summed again (RFC 1624), so a packet corrupted on the way stays detectably corrupt; an ICMP error, whose whole message changes, is checked before it is rewritten. The boot self-test (rust_net_selftest) checks every rewrite against checksums summed from scratch, and the table's filling, expiry and reuse.

The table is 4096 mappings and a hash of the guests' side of them, taken whole when NAT goes on, so the datapath allocates nothing but the frame a packet goes out in, from the pool. It is under a spin lock held for the lookup only; the frame is built and sent with it down. When all 4096 are live, the next flow takes one: the one used least lately of the guest that holds the most -- its own, when the asker holds as many as any (taken from the most). Each guest's mappings are a list in the order they were last used, in either direction, so the one to give up is found at once; a guest that opens flows as fast as it can takes them from itself, and cannot have every mapping there is, as it could while a full table refused every new flow. The table keeps a share for 64 guests at once, the switch having 16 ports; a packet of a guest past them is refused (no room). It is swept for flows past their time no sooner than the first of them can be -- the soonest of every flow's time, kept as each is made or kept alive, since a UDP flow's five minutes can run out under a TCP flow's two hours. The next hop's address comes from the ARP cache without waiting -- NAT runs on the receive path, which cannot sleep: an entry past its time is still used while it is asked for again, as Linux uses a stale neighbour, and the gateway and an on-link DNS server are asked for when NAT goes on, so a guest's first packet does not find them missing (no next hop counts those that did). A request goes out at most every 100 ms whatever a guest floods.

The switch answers DHCP (modules/hypervisor/hv/src/dhcp.rs). A guest's DHCP message never leaves its port: the switch answers it in place with the port's address -- the same as ip= gives -- a day's lease, the /24 mask, nos as the router, and nos's DNS server. Nothing is remembered, because there is nothing to choose: a request for any other address is refused (NAK) and the client starts again. A guest whose address is set by hand -- its port's -- may ask for the rest with a DHCPINFORM, and is answered with an ACK that has no address and no lease in it (RFC 2131, 3.4). A message the switch takes and does not answer -- a release, a decline, one not well formed -- is counted with the frames it does not carry (frames_foreign), where it once went nowhere, counted nowhere. A distribution that configures its ethernet by DHCP, as most do, needs nothing on its command line; one that takes ip= gets the same address from there.

The DNS server the guests are given is nos's own -- its resolver's, or the one its lease named (kcore::net::dns_server): 10.0.2.3 under QEMU's user network, Hetzner's resolvers on the Hetzner boxes. ip= carries it as dns0, which the kernel shows in /proc/net/pnp and Alpine's initramfs writes to resolv.conf, and DHCP as option 6, which systemd-resolved takes. ip= has the one nos had when the guest started; DHCP asks the kernel as it answers, so a lease renewed after nos's own lease named another resolver has the new one -- it was the one nos had when some guest was last started. The guests ask it through NAT like any other server; nos runs no DNS server of its own.

tests/hv-linux-test.py --net is the network's gate: two guests, their addresses, pings between each guest and nos and between the guests, nos's ping out of hv0, and a page from one guest's httpd fetched from outside the machine through hv forward; then the way out -- dns0 in the guest's /proc/net/pnp, a page and a megabyte (md5 compared) from a web server on the test machine through NAT, a ping there, udhcpc given its port's address, nos as its router and nos's DNS server, and nat and hv list saying so. With --internet, a name looked up through the DNS server it was given.

A public address: one to one

A VM may have an address of the world's of its own -- one rented for it and routed to the machine it runs on -- mapped one to one to its private one (public=; plans/vnet.md, "NAT"). The world reaches the VM at it, and the VM goes out from it: NAT rewrites the destination of what comes for the public address to the VM's own and hands it to the switch, where the VM's firewall judges it -- the source as the world sent it -- and the source of what the VM sends out to the public address; no table of flows, nothing to run out. The guest sees its private address alone. What is not opened by a rule of its firewall stays closed: a public address is an open door only where its firewall says so.

$ hv fw create web
$ hv fw web add allow in tcp 22,80,443
$ hv start web public=203.0.113.9 firewall=web    # or public = "203.0.113.9" in its vm.toml
$ hv list                                          # ... 10.0.100.2 alone, public 203.0.113.9
$ nat                                              # 203.0.113.9 one to one to 10.0.100.2 (...), MTU 1500

How an address reaches the machine: Hetzner's additional address is ordered for the server, with no virtual MAC -- that is for a guest whose own MAC is on the wire, and here none is -- and its router finds it by ARP on the server's link, or routes a subnet to the server's main address; either way it comes to the uplink, which answers ARP for a public address mapped there, as that address, and announces it as it is mapped, so a router that had it elsewhere hears of it at once. Nothing is configured on the uplink itself.

What NAT holds a public address's packets to:

  • What comes in has to come from the world: not an address the deny list has (the private networks, link-local, the shared space -- less what nat allow let through), nor this machine's. Otherwise any neighbour on the link could hand a VM a packet "from" its private neighbour.
  • What goes out is held to the deny list, as the masquerade's is -- but not to the uplink's own subnet: a neighbour there is the world to a public address.
  • ICMP errors are translated both ways, the packet they quote with them -- a router's "time exceeded" about a packet the VM sent comes back quoting it from the VM's own address -- and a packet in past the VM's MTU is answered "fragmentation needed", from the public address, where it may not be cut; NAT cuts nothing. What NAT makes up itself -- that, and the masquerade's rejections -- is held to a rate.
  • One address, one VM, one host: a public address mapped already, or a VM mapped already, is refused; an address of this machine's is never mapped. The mapping goes with the VM's port -- when the VM stops, before the port and its address go to the next VM -- and with NAT. A VM asked for one it cannot have does not start: no way out yet (no lease), the address taken, an address no host may have.

Here a public address is the VM's own host's: one VM on one machine, as public= says. An address that moves with a VM across a cluster's hosts, and one reached on a host its VM is not on, is V4's (plans/vnet.md).

The gates: the hv fuzzer's onetoone target -- addresses mapped and unmapped, refused as the rules say, a network behind hv0 put there and taken away, packets both ways each held byte by byte (the address rewritten, the TTL, the checksums right where they were right), ICMP errors translated with what they quote, "too big", ARP answered for what is mapped alone -- and its nine mutants (hv-fuzz.py --mutants); and tests/vnet-test.py's second phase, one nos on tests/hub.py's LAN with the world past its router: a probe with a public address reached by the world -- a datagram, and an echo once its firewall lets ICMP in -- the world seeing that address and the masquerade's beside it, nothing answering for the address once the probe is gone.

The cluster's networks

A VM may be on a network of the cluster's (plans/vnet.md, V2): one vnet.ko keeps in its state -- a private subnet, its MTU, whether it goes out -- which VMs on every host of the cluster share. network = "vnet:lan" in its vm.toml says so, and nothing else about it: its port, its address and its firewall are vnet's, kept in vnet's state, which vnet ports and vnet port <id> show and vnet port firewall changes.

$ vnet create lan 10.10.0.0/24 mtu=1400
$ hv create web /bzImage net network=vnet:lan address=10.10.0.50 firewall=web
hv: web given port 4 on vnet:lan at 10.10.0.50, judged by its firewall web
$ hv start web
$ hv delete web                             # its port deleted with its folder
  • The port is made at hv create, where a conflict -- an address taken, a firewall there is none of -- shows at once, or at the first start; address= and firewall= are carried out then and kept in vnet's state alone, and port= and public= are the host's networks' words. hv asks vnet through the management bus (hv/src/vnet.rs), as it asks NBS: the vnet provider's attach answers from the state the leader vouches for (raft's ReadIndex, raftmember::read, waiting up to five seconds for a leader); with no leader, a port the host's own state binds here is answered all the same, said unconfirmed in hv list, and asked again until it is confirmed. A VM with no folder is on no such network: its UUID, which its port is vnet's by, is new at each start.
  • Its identity is its port's: the switch's port is claimed as who vnet made it (Switch::claim_vnet) -- its address, its MAC 02:00: and the address's four bytes, its subnet and MTU -- and every delivery is held to that owner and address under the inbox's lock. The guest is told its address and its gateway, the network's first address, on its command line (ip=) and by DHCP, with the MTU (option 26); its NIC says the MTU too (VIRTIO_NET_F_MTU), which a kernel set by ip= has no other way to learn.
  • The switch carries IPv4 and ARP alone there: ARP answered by the switch -- the gateway at hv0's MAC, a port of the network here at its own -- and never carried; the gateway's echo answered from the gateway; nothing broadcast; another network's port, the host's networks, the cluster's other networks through the gateway, and the world from a network that does not go out, all isolated (counted, hv list); a packet past the MTU kept in, and answered "fragmentation needed" from the gateway where it may not be cut, at a rate. The world is NAT's: the network put behind hv0 (Nat::inside) while it has a port here and goes out. hv0's own ARP after a port of one is answered by the switch through a ring a task hands in (hv0's sink may not take the heap).
  • The keeper (vnet::Keeper, task hv/vnet) asks vnet's table every second while a VM here is on such a network, by vnet's instance and its state's revision: the cluster's networks given the switch, the cluster's firewalls its ports are judged by put in their places again as their rules change (vnet:<name> in hv fw's list, which hv fw does not change), and a port vnet moved, deleted or gave another generation shut -- nothing from it or to it, its VM running on, hv list saying why. With vnet gone hv goes on by what it had and says so once.

hv probe add <name> network=vnet:lan [address=...] [firewall=...] makes a probe a port of vnet's under a UUID of its own, deleted with it. The gates: the hv fuzzer's vnetswitch target -- the switch's rules for the cluster's networks held to a model of its own, with twenty-eight mutants among hv-fuzz.py --mutants -- and tests/vnet-test.py --phase v2, one nos with probes on two networks, a VM's port made and deleted with its folder, vnet unloaded under them.

Across hosts: the tunnel

A port of the network on another host is reached through the tunnel (plans/vnet.md, V3; modules/hypervisor/hv/src/tunnel.rs, its datagram in common/net/vnetwire): the guest's packet, IPv4 as it sent it, sealed into a UDP datagram to the other host where the registry has it, and opened there into that port's inbox.

Ethernet | IPv4, DF | UDP 39241 -> 39241 | kind 1, network 3, key 4, counter 8 | the packet, sealed | tag 16
  • Where a host is: its underlay address in the registry, its ipc one where it has none, at that address's port where it has one of its own, else 39241 (cluster.md) -- what it listens on, sends from, and is sent to. A datagram leaves from the uplink's own address: a host behind a NAT is reached at the NAT's address and the port the NAT forwards to it, and two hosts behind one address each have a port of their own -- the same number as their ipcnet's, which the registry has already (cluster invite <host> <ip>:<port>), forwarded in UDP as well as TCP. Two hosts the table has at one address and port are said in the log. The registry's address for this host not the uplink's is said once: reached through a NAT, if at all.
  • The switch carries into it (Carrier): a packet to a port's MAC that is no port here, of the sender's network, at the address the table has on another host -- judged going out by the sender's firewall, cut at its length -- and ARP for such a port answered as for one here. Out of the tunnel (Switch::from_tunnel) a packet goes only to the port of its network at its destination, judged coming in by that port's firewall and held to its owner and address as any delivery is. Nothing from the tunnel goes back into it.
  • What it lets through: a datagram under a key this host gave another and still has -- the key's number says which host, wherever a NAT made it come from, each number this host gives one no other key it has given has; with a counter its window has not seen (2048 back); whose tag holds -- the header is the associated data, the counter the nonce of ChaCha20-Poly1305 -- carrying a packet from a port the table has on that very host. Anything else is counted (hv tunnel) and, with trace on tunnel, a tunnel_drop saying why.
  • The cipher is the crypto crate's ChaCha20-Poly1305, CRYPTOGAMS' assembly in the kernel's SIMD sections (tls.md), which hv.ko hands vnetwire (aead.rs, its Aead): a datagram sealed on the guest's CPU and opened in the receive soft IRQ each in a section of its own -- in the integer code where one is open there already. A section marks its CPU's registers nobody's, so the guest whose packet was sealed between two of its entries has its own put back at the next, an XRSTOR it would not have had (What the extension costs while it is on, its x87, SSE and AVX state).
  • Keys go between the hosts' hv over ipc (hv.tunnel, a name the cluster reaches): each host gives every other the key to seal to it with, made anew for every message, its number random, installed to open by before it is sent, for one instance of the other's hv and taken by that instance alone, a number taken once -- the numbers taken kept as long as the host is in the table, its address or port moved or not. A host's new hv -- a reload, a reboot -- has every key to it and from it dropped, as does its going, which it says. Keys are given anew every rekey= seconds (3600), the one before kept keylife= (120): insmod /hv.ko rekey=8 keylife=4. Nothing of them is written anywhere.
  • The echo: every five seconds to each host with a key, every third one as large as the largest packet a cluster network carries, answered as large. A host whose answers stop for twenty seconds is said in the log (answered no echo) and its key asked for anew, so a key's message lost costs that long; a way that carries the small echoes and not the large is an underlay short of the networks' MTU, said too (does not carry a packet of N bytes). A network's MTU is its packets' bound: the tunnel adds 60 bytes to each, so 1440 fills a 1500-byte underlay.
  • Its uplink is NAT's -- the device the default route is on -- put on as soon as there is another host to reach. Sends go only while the uplink keeps room for the stack's own; the next hop's MAC is had beforehand, by the tunnel's task (hv/tunnel).
$ hv tunnel
hv tunnel: instance 5a1c..., node 1, at 10.9.0.1:39241
  b                10.9.0.2:39241        hop known  key to it had  keys given it 2  echo answered 3 s ago, a full one 13 s ago
  c                203.0.113.7:39242     hop known  key to it had  keys given it 1  echo answered 3 s ago, a full one never
  sent 1873, received 1869; not sent: no key 2, no room 0, no hop 0; not taken: unknown 0, replayed 0, forged 0, stale 0; echoes answered 41

The gates: the hv fuzzer's tunnel target -- three hosts' switches and tunnels over a wire that loses, repeats, damages, reorders, misdelivers and forges, keys' messages lost and repeated, tunnels started anew, tables wrong and ports moved; on a third of its inputs two of the hosts behind a NAT, at its address and ports of their own, their datagrams given its address -- or another of its own -- and any port, and a host's port moved under traffic: no key and counter sealed twice, nothing delivered that was not sent, or twice, or from a port the receiver's table has elsewhere, and every port reaching its network's others once the wire is kind -- its vnetwire target, and thirty-three mutants of the tunnel's and the datagram's rules among hv-fuzz.py --mutants; and tests/vnet-test.py --phase v3, three nos with probes on each, keys changed under traffic, a narrow link, a host killed, hv reloaded, a port moved. The fuzzer seals with RustCrypto's ChaCha20-Poly1305 in hv.ko's place, its vnetwire target holding every datagram to the wire built without vnetwire; net-fuzz's aead target holds the crypto crate to the same RustCrypto code.

A public address across hosts

A public address is routed by the provider to one host -- vnet's word for it, vnet ip add 203.0.113.9 ex44 -- and may be put on the port of a VM on any host (vnet ip set 203.0.113.9 <port>; plans/vnet.md V4). vnet's table says every public address on a port: the address, the host it is routed to, and the port's network, address and host.

the world -> ex44's uplink -> NAT one to one -> hv0 -> the switch -> the tunnel (kind 3) -> ax41 -> the port
the port -> its gateway -> the tunnel (kind 2) -> ex44 -> hv0 -> NAT one to one -> the uplink -> the world
  • The host it is routed to serves it (Switch::serve): one to one in NAT to the port's address and MAC (02:00 and the address), at its network's MTU, the network put behind hv0 -- wherever the port is, this host or another. ARP on the uplink answers for it there. A port moving keeps the mapping, its host the switch's to know; an address taken off, moved or removed is unmapped before another takes its place. A public address on a network that does not go out is not served, said once.
  • The world's packet NAT made the port's comes out of hv0 into the switch, in hv0's sink -- where nothing may wait -- and is queued for the tunnel's task, which the queue wakes, to carry to the port's host; there it goes only to the port whose public address is routed to the host that sent it, from the world or from the network's gateway (NAT's refusals), judged by the port's firewall.
  • The port's packet for the world goes to the host its address is routed to (Switch::public_way, told by the keeper), judged going out on the way, and into that host's hv0 -- for the world alone, from a port whose address that host serves, on the host that sealed it -- as one more port's share of hv0's backlog, for NAT to send out from the address. A port with no public address goes out masqueraded from its own host, as before; one whose address is routed to its own host goes out through that host's NAT as V0b's public= does.
  • The keeper asks vnet's table on every host whose hv is loaded, whether or not a VM of its own is on a cluster network: a host may be the way in for a VM on another. A host in no vnet is asked nothing it says no to. hv tunnel lists what the host serves (serves 203.0.113.9 for 10.10.0.12 on node 2).

The gates: the hv fuzzer's tunnel target, two public addresses routed to one host -- on a port of its own and on a port elsewhere -- through the real NAT one to one, the world's packets in at its uplink and the ports' out: a packet of the world's reaches only the port its address is on, and only from the host the address is routed to; a port's goes out of the right host's hv0 -- its address's host, or its own where it has none -- once, from its address; and every public address works both ways once the wire is kind; eight mutants more among hv-fuzz.py --mutants. And tests/vnet-test.py --phase v4: three nos, the world's echo and datagram to an address routed to one host and on a VM's port on another, the address moved onto a third host's port, routed elsewhere, taken off.

Guests that stay up

hv boot is a guest for a set time, run from start to end inside one command. hv start is the same guest left running: the command builds it, hands it to a vCPU task of its own and returns, and the guest is reached from then on by the commands above -- from the shell, over ssh or over the UDP shell alike. They are the lifecycle stage 4's HTTP API is to put on the network (plans/04-control-plane.md); the commands come first because they need nothing but a shell.

$ hv start /bzImage initrd=/initrd cmdline=console=ttyS0 nolapic
hv: vm 0 started on cpu 3 -- /bzImage, 256 MiB, cmdline "console=ttyS0 nolapic"
$ hv exec 0 secs=60 id
... the rest of its boot ...
~ # id
uid=0 gid=0
~ #
$ hv exec 0 uname -r
uname -r
6.18.53
~ #
$ hv send 0 echo nos$((6*7))nos\n
hv: vm 0: 20 bytes queued
$ hv wait 0 nos42nos
hv: vm 0 printed "nos42nos", 58 ms in
$ hv list
vm 0  running  cpu 3  256 MiB  1 s  exits 18237  irq 284  hlt 92  /bzImage
$ hv stop 0
hv: vm 0 stopped -- on request -- nothing in it listens to its power button
  stopped    on request, after 1925 ms
  exits      ...

(From the gate's run under TCG, where the guest is at its shell a second after it starts.)

A VM is a task and a shared record (modules/hypervisor/hv/src/vms.rs). The guest -- its memory, its vCPU, its devices -- belongs to the vCPU task (hv/vm<N>) alone, and is freed there when the guest stops. What the task and the commands share is the console, its last 64 KiB in a ring; the bytes waiting to be typed at it, 4 KiB at most; a stop flag; and the loop's counters, which it publishes at every halt and every 4096 exits. The ring and the input queue are taken whole when the VM is made, so nothing on the guest's datapath allocates. Each vCPU is bound to one CPU the extension is on for, where hv::place puts it (cores.rs): whole cores of its own by default, its disks' task on a core apart where there is one, cpu= naming its first CPU when given (Where its CPUs sit).

hv exec knows where its answer starts. It types the line and a newline and waits for a prompt -- but only one printed after the line's last byte was handed to the guest's UART: the loop notes where the console was at that moment, and only what comes after it can end the wait. So a line typed at a guest that is still booting waits for its shell and comes back with its answer, not with the first prompt the shell printed before it read the line; and a line the guest never reads says so rather than timing out in silence. It prints everything the guest printed since the line was typed. Each line goes in at a prompt of its own: after a newline the UART holds what is typed back until the shell asks where the cursor is again. Typed ahead -- a line queued behind another, a requeued input= after a reboot -- it went in while the shell still ran the one before, and that line's prompt ended the wait: hv exec came back with its answer cut after a character, which hv-linux-test caught once under load.

What reaches a terminal is made safe for one. hv console, hv exec and the report print the guest's console with escape sequences taken out whole, carriage returns dropped and anything above ASCII shown as ?: a guest shell's ESC [ 6 n, printed to the terminal a person is reading nos on, would make that terminal type its answer into whatever reads it next.

The cursor query is answered with the cursor. BusyBox's line editor asks where the cursor is after it prints its prompt, and takes the column it is told as the prompt's end. It was once told column 80 whatever the prompt, and wrapped what was typed at the edge it thought it had reached -- id came back as i, a newline, d. The UART now follows the guest's output as a terminal would -- the column each byte leaves the cursor at -- and answers with that, from a buffer of its own: a guest that asks and never reads the answer costs the host no more than one that asks once, where the answer used to be appended to a queue without bound.

And a move of the cursor is followed too. systemd 257 sizes a serial console as a getty starts by moving the cursor to a far corner (ESC 7, ESC [ 32766 ; 32766 H), asking where it went and putting it back (ESC 8). Told the column its text had got to, it once sized a Debian 13 guest's console 7 columns wide, and every line typed at it in the panel wrapped and was drawn over itself. The UART now follows the cursor's moves -- to a column (CUP, HVP, CHA), right and left (CUF, CUB), saved and put back (ESC 7/8, CSI s/u) -- a move to the right stopping at column 80, so the corner is a VT100's 24 rows by 80 columns: stty size in such a guest says 24 80. A line of text is followed past 80 as before, so a prompt is still told where it ends. A guest whose console has the old size gets the new one at its next login, or at stty cols 80 rows 24.

Stopping is a question, then a flag and a join. hv stop presses the VM's power button, and a guest that shuts down when it is pressed is given secs to (ACPI) -- on the list meanwhile, stopping, its CPUs still counted where a new VM is placed, and off it after; the one above, a kernel without ACPI, never hears the button, and is stopped at once. Then the flag: the loop checks it before every entry, and a halted guest's task sleeps at most 10 ms at a time, so the stop comes within a tick or so, and the command joins the task after, with no lock held while it waits. A guest that stops by itself -- a triple fault, a HLT with interrupts off, a reset, a power-off -- stays on the list as stopped, with its reason, until hv stop takes it off.

A VM's task lives as long as the VM. When its guest stops, the vCPU task gives the guest's memory back and parks on the VM's event, for hv restart -- which builds the guest again from its files and boots it, a stopped guest or a running one, as a reset button would -- or hv stop, which ends it. With restart, a guest that resets itself or triple-faults is booted again by the task straight away: a reboot. Five of those within a minute are taken for a loop -- a guest that panics at boot with panic=1 would otherwise have its CPU for good -- and it is left stopped, reset 6 times in 60 s, left stopped. hv list counts the restarts; the console runs on across them, one log of every boot; a line hv exec typed at a boot that ended says so rather than waiting for a prompt that will not come.

hv attach is the console, live. From an SSH session with a terminal (ssh -t <host> hv attach 0) it shows the last kilobyte of the console, then what the guest prints as it prints it, and types what is pressed as it is pressed -- the guest's line editor, ^C and all -- until ^] detaches, the guest stops, or the session ends. What it passes to the terminal is the guest's output as it is, colours and cursor movement included, but for what a terminal would answer or act on: a status or attributes query (ESC [ 6 n, ESC [ c), whose answer would be typed into the guest after the UART's own, and the string sequences (ESC ] and its kind), which set a terminal's title, clipboard or palette -- nothing a guest should reach on the person's machine. It takes a session that can type: a command reads what is typed through its output (Output::read_input), and only an SSH session's has anyone behind it -- from the console, the UDP shell or /etc/rc it says so and returns. Keys typed at an attached guest are not held back for a prompt the way a script's line is: the person decides when to type.

A guest that reboots stops, and says so. Linux reboots -- a reboot, a panic with panic=N -- by the reset register its ACPI tables name, when it has them (the chipset's reset control, 0x06 to port 0xCF9); then by pulsing the 8042's reset line (0xFE to port 0x64); then by the chipset's reset control where it knows of one; then by a triple fault. Nothing here emulates an 8042 or a chipset, and on the AX41 the first guest that rebooted spun at 100% of its CPU for as long as anyone let it -- 1.3 million reads of the 8042's status in 48 seconds, waiting for a controller that is not there. Both writes now stop the VM (Stop::Reset), the guest asked for a reset, 0xfe to port 0x64 (the 8042's reset line); its ports still read as all ones, as on a PC without one, so Linux spends its kb_wait polling them first -- 65536 reads, a couple of seconds -- and then asks. What a reset should become -- the guest booted again -- is the control plane's to decide.

Idle guests cost their CPU next to nothing, sharing one or not. A halted vCPU sleeps until its guest's next timer edge, and Sleep() blocks (the scheduler): it used to be a loop around schedule(), and two halted guests on one CPU of the AX41 handed it to each other without end -- 46% of it each, the idle task never running -- where one alone took 0.1%. Blocking, the same two take 0.1% each, and sixteen idle guests on the AX41's twelve CPUs -- four of them carrying two -- keep the machine 1.6% busy, 0.1% a vCPU.

A halt that ends soon is spun through (halt polling, KVM's way: the POLL_* constants in hypervisor/hv/src/run.rs). Before its task sleeps, a halted vCPU spins on its doorbell for a while (Doorbell::poll) -- on a host CPU that is its guest's own -- so that a ring that comes within the spin, an IPI from another of the guest's CPUs or a disk's answer, costs no wakeup and no schedule. The spin starts at none, doubles from 10 us after every halt that was short and outlasted it, up to 200 us, and is dropped after a halt longer than that: a guest that idles until its next tick spins not at all, and one whose CPUs wake each other within microseconds -- a pipe between two processes, a database's clients and its server -- is caught spinning. It is never spun up to an edge of the guest's own timers: an edge sooner than the spin is slept to, so the loop always waits once a halt goes unanswered -- and a sleep to its own APIC timer's edge ends 10 us short of it, the rest spun (TIMER_ADVANCE_NS, KVM's timer advance), so that what a wake costs the host -- its timer's interrupt, a schedule, a switch, which made the EX44's guests' timer interrupts 9-10 us late on average -- comes before the edge rather than after it. A ring of a vCPU that spins sets the word it watches and signals nothing (Doorbell::ring), its task not being asleep: the word is stored before the spinner is looked for, and the spinner stops before it looks at the word a last time, so of the two one sees the other. The report counts the halts spun for and those a ring ended in the spin. Under KVM, on the EX44, the polls caught 36 million of a Linux guest's 40 million halts in a benchmark's run, and the pipe's round trip took 6 us where nos's took 14 (plans/vm-performance.md); with the spin, 89% of 50 million and 8.5-9.3 us.

After a write of its TSC deadline, or of an IPI to other CPUs, a CPU goes straight back in -- KVM's fast path for the same two writes, half of a Linux guest's exits. The loop's round -- the mail, what was posted, the devices' work, the APIC's state handed in again -- is left out where the last entry had the CPU deliver the APIC's interrupts and nothing waits: no ring since the last look (Doorbell::take_rung), no mail, nothing posted that the CPU has not taken -- a notification that came as a host interrupt after the exit leaves its descriptor's ON bit set (PostedInterrupts::outstanding) -- no edge of its own timer due, nothing to give back. The host's timer is armed for the timer's edge, which the write may have moved. An IPI that reaches the sender's own APIC changes what the round would hand in, and goes the round. On the EX44 an exit cost the host 545-559 ns handled and 479-496 ns to the next entry, past the world switch.

And those two writes are answered inside the world switch itself (hvarch::x86::fast::FastExit, KVM's handle_fastpath_set_msr_irqoff): after a WRMSR exit, still with interrupts off and the guest's x87, SSE, AVX and CR2 in the CPU, the backend's loop -- vmx::Guest::enter's, svm::Guest::run's -- offers the write to the run loop's FastMsr, and where it is answered steps the guest past it and enters again at once: no XSAVE, no XRSTOR, no round. What answers is the same code as the round's: an x2APIC ICR write of a fixed or lowest-priority IPI to other CPUs alone (Lapic::fixed_ipi, posted or mailed as send does), and a TSC-deadline write (the host's timer armed for the new edge). Everything else is refused with nothing done and goes the exit's usual way: an IPI that reaches the sender, an NMI, INIT or start-up, a reserved bit, xAPIC mode, any other MSR, a guest single-stepping (TF: its #DB after the instruction is the run loop's), and under AMD-V an exit with no next RIP or one that cut an event's delivery short. Each entry of the loop is an entry like any other -- VERW, the L1D flush where it is needed, the guest's SPEC_CTRL over the host's and the host's back after, AMD's IBPB at the exit -- and the kick decides each again (Kick::entering): a ring, mail, or the host timer's edge come since ends it, the write answered, as a kick's refusal of an entry, for the round to take what came. What may run there is what may run with interrupts off: the posts, the doorbells' rings and the tracepoint's record. The report counts the writes answered there (answered) and leaves them out of its average exit; hv-fuzz.py's whole-machine runs offer three in four of their scripted WRMSRs to it, the rest going the round, and hold both to the same invariants.

A HLT that an IPI ends soon is waited out there too (FastExit::hlt, VT-x with posted interrupts): with interrupts on in the guest, nothing in its virtual APIC (RVI 0) and no window asked for, the run loop's FastMsr spins with the host's interrupts off -- for as long as the CPU's halts have lately been ending within (poll_ns), to HLT_SPIN_NS, 50 us -- until something is posted for the CPU, and the loop steps past the HLT and enters again at once: the vCPU is in its guest as posters see it, so the poster sends the notification, which waits on this CPU and is taken in the guest as it enters. On the EX44 the round after a halt's wake took 983 ns to the next entry, and the exit to the halt 381 more (round 22, perf's pipe). A kick -- a ring for mail, a device, a stop --, the host timer's armed edge, or the time up ends the wait with nothing done and the HLT goes the loop's way; a CPU without posted interrupts, and AMD-V, never wait here. The report counts the HLTs ended so (hlt_answered), among the exits and the HLTs, none of them a halt of the loop's.

An edge of its own timers that comes on the way in is taken a round later, not at the host's next tick. The loop looks at its timers, and arms the host's timer for their next edge a few hundred nanoseconds later -- and the host's timer is armed for none gone by: an edge that fell between the two was owed to a guest that then ran on to its next exit, a host tick for one that computes. The EX44's guests saw one 10 ms late at most. The loop looks again after arming, before anything is handed in for the entry, and goes round again where an edge has come. That was not all of it: the EX44's guests still saw an edge 10009 us late at most after it (64d61a78), so the report says where such edges were waited for -- late: the timer interrupts more than 1 ms past their edges (LATE_NS), by what the vCPU's task did before the round that found them (slept to a time with that edge in it and woke more than 1 ms past it, rung or not; woke on time; slept without that edge; spun, or slept for good; came round more than 1 ms after an exit, off its CPU or busy; ran its guest until an interrupt of the host's took it out, or an exit of its own), the sleeps that ended more than 1 ms past their time, and each CPU its own. It said (a68aeb3a): of 12388 such interrupts in a run, 241 after a host's interrupt took a guest out that had computed past its edge -- the 10 ms, a host tick -- and 12078 after sleeps that had the edge and ended 1-3 ms past their time, 0.12% of the sleeps, nearly all by a ring. Those were taken for the machine's own -- its cyclictest's most was 3.1 ms under KVM as under nos, and the scheduler's wake-ups on every CPU came at most 3-4.6 ms late since boot -- and were the host's idle task: out of its idling it was counted as any task, and an interrupt's decision left it the CPU over a vCPU rung just then, which waited out its 3 ms slice (scheduler). With that closed (d92695bc) a run of the suite has no sleep ending more than 1 ms past its time, 2 timer interrupts more than 1 ms late, and cyclictest's most 205 us.

The host's timer is armed for the edge as the entry is made (Kick::arm_at, Kick::entering), with interrupts off on the CPU from there until the guest runs. Armed in the loop's round, a few hundred nanoseconds before, it was lost to any interrupt of the host's timer that came between -- a sleeper's deadline, the slice's end -- whose handler re-arms the timer for the host's next tick (Cpu::local_timer_fired): the guest then computed past its edge until that tick. An edge that has come by the entry turns it back, for the round to take it. The report counts those among the entries turned back (kicked), and its worst line says how the latest timer interrupt of a run was waited for -- after the guest ran, when it was entered, what the host's timer was asked for and when it left. The order in entering is the arming first and the look after: timer_at arms nothing for an edge gone by, and with the look first an edge that went by between the two -- a few hundred nanoseconds -- left the timer unarmed and the guest computing for 10 ms (7ae441c4, whose worst line said: "10009 us past its edge, after an interrupt of the host's took the guest out: the guest entered 0 us from the edge, the host's timer asked for 0 us from it"). hv-fuzz's platform target runs hvarch's Kick as it is (hypervisor/hvarch/src/x86/kick.rs, kept apart from the backends for that), has the host's tick land on the way in, re-arming its timer so, and the clock reach the deadline timer_at is asked for now and then as it is asked, and holds every entry to a timer armed no later than the edge its loop asked for: the arming in the round is found at its 167th input, the look before the arming at its 43rd.

The extension is not pulled from under a guest. hv off refuses while a started guest runs on one of the CPUs it names. That is a courtesy and not what keeps the CPU safe: every entry checks, with interrupts off until the guest is running, that the extension is on and its save area is the one this module gave that CPU, so a guest racing an hv off finds it off and stops, not entered -- on AMD-V; on Intel the CPU itself refuses to go off while a guest's VMCS is current on it (above), so an hv boot or hv run the courtesy check does not see keeps its CPU too. rmmod hv stops every guest before it turns the extension off -- its power button pressed first and the guests given stop_secs= (above) -- the guests first, an hv boot under way among them (stopped at once: it is a diagnostic), so that an hv exec or hv wait waiting on one returns; then the command, whose unregistration waits out every call still running (an hv start still reading its files finds the module going when it comes to add its guest, and stops it itself); and only then the extension, on every CPU.

The gate is tests/hv-linux-test.py with --initrd: two VMs started side by side and one stopped mid-boot, a line typed at the other before its shell is up and another at its prompt, send, wait, console, the refused hv off, and an rmmod that presses the guest's power button, stops it itself when its time is up and leaves nothing on for the next load.

A VM in a folder

A guest started by its kernel's path is gone with its words: the next hv start says them all again. A VM kept in a folder is not. Its folder under /vms -- or wherever insmod was told to keep them (below) -- holds what to boot it with -- vm.toml -- and beside it whatever the file names: its kernel, its initrd, its disks; and its console's log. hv start <name> boots it as the file says (modules/hypervisor/hv/src/store.rs), and every command that reaches a VM takes the name as well as the number:

$ hv create web /boot/bzImage initrd=/boot/initrd disk=root.img mem=1024 cpus=2 net port=3 forward=2222:22 restart cmdline=console=ttyS0 root=/dev/vda rw
hv: /vms/web/vm.toml written -- hv start web boots it
hv: /vms/web/root.img is not there yet
$ truncate /vms/web/root.img 20G
$ hv vms
web  not running  bzImage  1024 MiB  2 cpus  disks root.img  net port 3 (10.0.100.5)  forward 2222:22  restart
$ hv start web
hv: vm 0 (web) started on cpus 2,3 -- /boot/bzImage, 1024 MiB, 2 cpus, cmdline "..."
hv: port 2222 forwarded to vm 0, 10.0.100.5:22
$ hv exec web uname -r
$ hv list
vm 0 web  running  cpus 2,3  ...
$ hv stop web

hv create <name> <words> writes the file from the words hv start takes -- their paths the folder's unless they begin with / -- checked as a start would check them, and never over a vm.toml that is there; it says which of the files it names are not there yet. It gives the VM a UUID too (uuid = "..."), what its SMBIOS tells its OS the machine is (SMBIOS); and network= on its words (network = "...") puts it on a network of the switch's, with the VMs that name the same -- without, it is alone there (A network). hv start /some/where/web boots a folder anywhere by its path, the folder's name the VM's. hv vms lists the folders under /vms, what each boots, and which run.

A VM of a cloud's image

hv create <name> <url> makes the folder of a distribution's cloud image (modules/hypervisor/hv/src/cloud.rs), for hv start <name> to boot it as a cloud does -- with nothing done anywhere but on nos:

$ hv create noble https://cloud-images.ubuntu.com/releases/noble/release/ubuntu-24.04-server-cloudimg-amd64.img size=20G mem=2048 cpus=2 forward=2201:22
hv: https://cloud-images.ubuntu.com/... -- into /vms/noble/ubuntu-24.04-server-cloudimg-amd64.img
download: ... MiB of 592 MiB, ...%, ... MiB/s
hv: /vms/noble/ubuntu-24.04-server-cloudimg-amd64.img: qcow2 version 3, a disk of 3584 MiB in clusters of 64 KiB -- into /vms/noble/disk.raw
hv: /vms/noble/disk.raw: 1785 MiB written of 3584 MiB, the rest holes -- 27971 clusters inflated, 692 copied, 0 zeros, 28681 not there -- in ... s
hv: /vms/noble/vm.toml written -- hv start noble boots it: hvboot, a 20480 MiB disk, cloud-init given 1 key
$ hv start noble

A file copied into /images on the host is the same create without a download: hv create <name> /images/<file> [words], or the host API's file in place of url. The panel's An image from /images choice lists these files (the local_images read), with a refresh for one copied while the form is open. Only a regular file directly in that folder is named; a path elsewhere, including one with .., is refused. The source is never renamed, removed or written: qcow2 is converted into the VM's folder and a raw image is copied there with its holes left out. size=, onto= and the rest of the create are the URL form's.

For a prepared Windows disk, hv create <name> <url> windows takes the same qcow2 or raw image by its URL but boots it by CloudHv with Hyper-V. The image must already contain a UEFI installation, virtio-blk and virtio-net drivers, and its users and remote access: Windows gets no cloud-init seed, and password= or caller-supplied user-data is refused rather than silently ignored. Its defaults are two vCPUs and 4096 MiB, which cpus= and mem= override; the disk and the other words are the Linux path's. The host API's create selects the same mode with "os": "windows" ("linux" is the default), and the panel exposes it as the guest OS choice beside the image URL. start starts either kind by the same API job once made.

  • The image is fetched by the kernel's own HTTP client -- the one wget is -- through kcore::http::fetch (the export kernel_http_fetch, since a module cannot link the network layer): TLS with the certificate checked, redirects followed, and the bulk receive window a download of gigabytes needs, which a module's own TCP connection is not given. Only a 2xx answer is a body -- "the server answered 404" otherwise -- a body cut short is no image, and a file there already is not written over; a failed download leaves no file. The client hands the module how much is in the file as the body comes, and asks it whether to go on: hv says the progress lines, and a stop -- the module going -- ends the download as the next of the body arrives, the file removed.
  • The disk: a qcow2 image is converted (A disk from a cloud's image); a raw download is taken as it is, and a local raw image copied with its holes left out. A download is removed once made into the disk; a local source stays untouched. Anything else is refused by what it is. size= (K, M, G, T) grows the VM's disk with a hole -- never under what the image holds -- for the guest to grow its root into: cloud-init's growpart does, on its first boot.
  • Linux's seed: seed.iso, the VM's second disk, read-only -- an ISO 9660 labelled cidata with Rock Ridge's names (diskimage::iso), which cloud-init's NoCloud finds by its label. Its meta-data names the machine after the VM -- local-hostname, which cloud-init sets the guest's name from -- with an instance-id of its own (nos-<name>-<time>), so that cloud-init takes it for a new machine; its user-data gives the image's own user -- ubuntu, debian -- the keys nos's sshd lets in (/etc/ssh/authorized_keys), and with password= a password, for its console. Every string in it is YAML's double-quoted -- the meta-data's too, a VM named 1.5 or true being no string to YAML bare, and its hostname then not set -- and everything but printable ASCII in it an escape (\u2028), a C1 control or a line separator in a key's comment or a password having once left the user-data unreadable or the password another. The user-data says nothing of the machine, and is kept in the folder as user-data: a clone's seed gives its own first boot the same (below). The host API's create may give user-data of its own instead -- a job, which only an admin starts -- and then no password, which was once dropped without a word: the call is refused.
  • The vm.toml, written last: hvboot as its kernel (/lib/hvboot, the system image's, or hvboot=), which boots the kernel the image's own GRUB would (A guest's own kernel); disks = ["disk.raw", "seed.iso:ro"] for Linux, ["disk.raw"] for Windows, a disk= given after them; on the switch; booted again when it reboots itself; 1024 MiB for Linux or 4096 for Windows unless mem= says otherwise. The other words are hv start's, but a kernel and an initrd: cpus=, port=, forward= -- forward=2201:22 for its own sshd -- cmdline=, which hvboot puts after the entry's own line.
  • Nothing is left of a failure: what the command made -- the download, the disk, the seed, and the folder when it made that too -- goes, and why it failed is said, with anything that could not be taken away. Nor of a stop: the module's going, or the host API's cancel of its job, ends the download as the next of the body arrives, or the conversion at the next cluster, and takes the same away. Before anything is fetched, a disk.raw, seed.iso or user-data in the folder already -- what hv delete <vm> keep-disks leaves -- refuses it: one once failed the create at the end of its download, every time. The name is held while the folder is made: no start of it meanwhile, and no other create, clone or delete; and what it is given meanwhile -- its port=, a device -- is kept with the hold, no other VM's until its vm.toml says so. The URL is said without a user's name and password, a query or a fragment: a job's log is read by every client that may read jobs.

What it does not do yet: check the image against its distribution's SHA256SUMS (TLS's certificate is what vouches for the bytes now), resume a download that broke off -- the client gives up after ten seconds of silence -- or hold less than the download and the disk at once on nos's root while it converts. tests/hv-test.py (x86-64) makes VMs so from a web server of the test's own, and tests/hv-distro-test.py --create <url> makes and boots one, cloud-init provisioned by the seed (Testing): Debian 13's genericcloud image, fetched by nos itself through Debian's redirect, booted by hvboot off its own /boot, its root grown into the 4 GiB disk, and cloud-init done from DataSourceNoCloud [seed=/dev/vdb] 50 s after the VM started -- its user logged in with the seed's password, nos's key in its authorized_keys.

A VM of an image of NBS's

Where the hosts are an NBS cluster (NBS), a cloud's image is made an image of NBS's once -- read-only for good, on three hosts' chunk servers -- and a VM of it on any of them is given a clone, thin: each of its chunks the image's until the VM writes it (N10d3, modules/hypervisor/hv/src/{image,cloud,nbs}.rs):

$ hv image img /boot.raw
hv: /boot.raw: raw, a disk of 32 MiB -- onto nbs:img, 32 MiB, fresh: its zeros left out
hv: nbs:img: 32 MiB written in 0.3 s, flushed and let go of
hv: nbs:img is an image now, 32 MiB, read-only for good -- hv create <vm> image=nbs:img makes a vm of a clone of it
$ hv create v1 image=nbs:img size=64M mem=256
hv: nbs:v1 cloned from nbs:img, 64 MiB -- thin: its chunks copied as they are written
hv: /vms/v1/vm.toml written -- hv start v1 boots it: hvboot, a 64 MiB disk, cloud-init given 0 keys
hv: no key in /etc/ssh/authorized_keys and no password= -- nobody can log in to it
$ hv start v1
  • hv image <name> <file|url> takes a qcow2 image or a raw disk, a URL's downloaded first into the vms' folder (.image-<name>, removed after, however it ends): a volume of the disk's size made on this host, the image poured onto it as hv convert ... nbs: pours one -- its zeros left out, a new volume reading as zeros -- and the volume frozen. The name is held on the host while it is made, and refused where NBS has a volume of it; one that fails leaves nothing -- the volume deleted while it is a volume still and this host's, so an image another host made of the name meanwhile is never taken away.
  • hv create <vm> image=nbs:<image> [size=N] [onto=nbs:<volume>] [words] makes the VM as hv create <vm> <url> does -- a seed for cloud-init, a vm.toml booting it by hvboot -- its first disk nbs:<volume>, a clone of the image: of the VM's name, or onto='s, which NBS must not have yet; grown to size=, never under the image's. A plain volume is refused -- a VM is made of an image or a snapshot -- and a clone made is deleted with the rest of what was made when a later step fails.
  • hv asks NBS through the management bus, as the host API does: nbs-mds's nbs provider (volume, volume_create, volume_resize, volume_freeze, volume_clone, volume_delete), so hv.ko links nothing of nbs-mds's; without it both commands say to insmod /nbs-mds.ko, before anything is downloaded.
  • A volume is a disk of 4 KiB blocks, which hv's device shows its guest in 512-byte sectors, the block its physical one: a cloud's image poured onto it boots as off any disk, its partitions where its GPT says (A disk's sectors). hvboot reads it in sectors, a part of a block served by the device in whole ones.

The host API's create takes an image of NBS's as image, in place of url or the local library's file -- one of the three -- its clone named by onto (nbs:<volume>) where not the VM's, and grown to size_bytes; and a URL's or local file's image poured onto a volume with onto=nbs:<volume>. Its local_images lists the regular files directly under /images; its image makes an image as hv image does, and snapshot takes a snapshot of a VM's volume -- a running one's too, its session paused for it -- of which VMs are made as of an image. The panel has them all: an Images page (NBS's images and snapshots, a new image of a URL, each a click from a VM of it), a Snapshot on a VM's page and the VM's snapshots listed there, and a create that offers NBS's images and snapshots to make a VM of, and its volumes to pour onto.

What it does not do yet: hv delete leaves the VM's clone, as it leaves any nbs: disk -- nbs volume delete takes it away. tests/hv-nbs-test.py makes an image of a disk hvboot boots and two VMs of it on two hosts -- one by hv create, the other by the vm provider's create, as the panel makes one -- each booted by its name off a clone of its own, one written over a chunk the image shares and the other still the image's (Testing).

Cloned, deleted, changed

hv clone <from> <to> [port=N] (modules/hypervisor/hv/src/clone.rs) copies a VM's folder into a new one: a VM of the same machine, its disks as they are now, that boots as a machine of its own.

$ hv clone noble noble2
hv: /vms/noble/disk.raw -- 20480 MiB, 2215 MiB of it data -- into /vms/noble2/disk.raw
hv: /vms/noble2/disk.raw: 2190 MiB written of 20480 MiB, the rest holes
hv: /vms/noble2/vm.toml written -- hv start noble2 boots it, cloud-init given a seed of its own
  • Its disks in the folder are copied with their holes left out: only what the source's filesystem keeps on the device is read -- the image's extents (kcore::fs::Image::extent, over ext2's block map) -- and of that only the blocks that are not zeros are written, into a file grown to the disk's size with a hole first. A read-only disk outside the folder -- an installer's ISO -- is shared by its path; a written one is refused, as two VMs writing one disk wreck it. The source's disks are held to read while they are copied (kcore::fs::Image), so nothing writes them meanwhile -- and the room the copy takes is asked of the filesystem first (kcore::fs::space), with a sixty-fourth and a MiB to spare.
  • Its seed is made anew: a new instance-id and its own name in the meta-data, and the source's user-data, which hv create keeps in the folder -- so that cloud-init runs for it as for a new machine: its own name, its own SSH host keys. A VM made before folders kept it gets the keys of /etc/ssh/authorized_keys, which its disk has already. What cloud-init does not make anew, the clone keeps: systemd's /etc/machine-id, which a distribution writes once, on the disk -- a clone that must have its own clears it before its first boot (systemd-machine-id-setup makes one at the next).
  • Its vm.toml is the source's, the operator's lines and comments kept, with what makes a machine itself made new: a new uuid; a port of the switch -- an address and a MAC -- that no other VM's vm.toml names and no VM on the list holds, when the source had one (port= says which); no forward, which would be the source's ports; no ip= on its command line; and not protected. The port is looked for, and kept with the new name's hold until its vm.toml says so, under the lock vm.toml changes take: two clones at once were once given one port, one MAC and one address.

It is refused while the source is on the list -- hv stop it first -- and when the new name has a folder; both names are held while it runs, so neither starts and nothing else is done to either. A source's user-data that is there and cannot be read refuses it, rather than giving the clone the default keys in its place. What fails, or is stopped -- the module's going, the host API's cancel -- leaves nothing behind, and what could not be taken away is said.

hv delete <name> [keep-disks] [force] (store::delete) takes a VM's folder away: every file in it and every folder under it -- or, with keep-disks, all but the disks its vm.toml names in it, which stay where they are, the folder with them -- told by the file, not by the path's spelling: a vm.toml's ./root.img or sub/../root.img is the file the folder lists as root.img, which a comparison of strings once took away and said it kept -- its vm.toml last, so that a delete that fails part way (a file open, a disk another VM holds) leaves the VM there for another. Disks its vm.toml names outside the folder are not touched. It is refused while the VM is on the list, and for a VM whose vm.toml says protected = true -- or cannot be read -- unless told force. hv vms lists no folder without a vm.toml: what a delete that kept the disks left.

What hv changes in a vm.toml after it is made, it changes key by key (config::rewrite, over conf::edit): the line of a key whose value is another replaced where it is, one taken away taken out, one the file has not added at its end -- and every other line, the operator's comments and blank lines among them, left as it was; the file as it was kept beside it as vm.toml.prev, each written whole before it takes the old one's place -- one change at a time, under one lock, and none while the folder is being deleted: a change beside a delete once wrote vm.toml.prev into a folder the delete had walked, which was left with that alone in it. So does hv forward add -- a forward to a VM with a folder is kept in its forward = [...], for its next start to have it, and hv forward del takes it out -- and so do the host API's edits (below). No disk or download is given a name of the folder's own files -- vm.toml, vm.toml.prev, the .new each is written through, user-data, the console's logs.

On the management bus

The vm provider (modules/hypervisor/hv/src/provider.rs, x86-64) is the VMs as the host API (The host API), the management panel and mgmt reach them -- each by its folder's name -- through the same functions the commands are:

reads list (every VM: its folder's, and those on the list without one), get (its configuration, disks and forwards), host (the extension, the cores, the huge pool, the switch -- and the host's address on it and each port's, the same before the switch is made), networks, local_images (the regular files directly under /images, each with its name, path and size), config_get, console_read (a page of its console from a byte on -- its control sequences taken out, or for a terminal filtered as hv attach filters them, a sequence the page would cut in two left for the next), disks (a device's id and its name this boot among them), disk_io (what each disk of a running VM has done since its guest's boot -- reads, writes and their bytes, flushes, errors, discards, writes of zeros, and wait_ns, the time its backend took over the requests it answered, from the hand-off to the answer, a flush behind a write counted with the write: the virtio disk's own counters -- by the word the VM was started with, and when they were read, the host's boot time; a client makes its IOPS and bandwidth of two, and the guest's restarts say where the counters began anew), forwards, devices (every device of nos's: its id, type, size, who holds it, what is on it, and why it would be refused -- A device as a guest's disk)
actions config_set (a vm.toml checked as a start checks it, the old one kept as vm.toml.prev as its bytes -- so one that no longer parses, a key misspelt by hand, can be mended), forward_add and forward_del (kept in its vm.toml, and made or taken away now when it runs), console_write (keys, control keys among them), disk_add (a new empty disk in its folder), disk_grow, disk_attach and disk_detach (a device given to a stopped VM by its id, force as hv disk attach takes it, and taken off again), snapshot (a snapshot of a disk of the VM's that is a volume of NBS's -- its first, or disk -- as nbs volume snapshot takes one: of a VM running here, its guest's session paused for it, the disk as a power cut would leave it; of one running on another host, refused, naming the host; of a VM of a file or a device, refused: a clone copies it whole)
jobs start, stop, restart, create (a cloud's image by its URL or a file directly under /images, as `hv create <name> <url

A job says as it goes what the command would, as its log, and how far it has got; its cancel -- or the module's going -- stops a download, a conversion and a copy where they are, what they made taken away. A stop's cancel stops its wait for the guest to turn itself off and leaves the guest as it is, its power button pressed -- it was once stopped at once, perhaps in the middle of the shutdown the job had asked for -- and the module's going stops it where it is. A VM whose vm.toml says protected = true -- or whose vm.toml cannot be read, which may say so -- is stopped, restarted and deleted only when the call says force: the panel's own VM has it. When the module goes, the loader closes the provider with the command -- its jobs told to stop -- and the module's stop unregisters it, waiting out its calls and jobs, before the forwards and the VMs go; the loader then waits out the command's calls, and only then is the module dropped (Unloading). Its descriptor is vm.descriptor.json (Descriptors).

Where the folders are

/vms, unless insmod says otherwise: insmod /hv.ko vms=/data/vms keeps them under /data/vms -- an absolute path with no ., .. or empty step in it, its trailing / let go, and not / itself, whose every folder would be taken for a VM's -- and hv says where they are kept. hv create makes the folder, and those above it that are missing; hv start <name> and hv vms look there, and only there. A parameter hv has not got refuses the load, said on insmod's output -- as a misspelt key does in a vm.toml, and for the same reason:

$ insmod /hv.ko vmz=/data/vms
hv: "vmz" is not a parameter of hv's -- vms=<folder>, stop_secs=N, rekey=S and keylife=S are
module: hv: init failed
insmod: /hv.ko failed, error 502
$ insmod /hv.ko vms=/data/vms
module: hv loaded at 0xFFFF8000...
$ hv
hv: AMD-V on for cpu none of 0-3
hv: vms kept in /data/vms, as insmod was told
hv: an unload -- rmmod, nos's poweroff or reboot -- presses the guests' power buttons and gives them 120 s to turn themselves off

Its other parameters are stop_secs=N, 0 to 600: what the module's going gives the guests to turn themselves off (above), and hv says it; and rekey=S and keylife=S, up to a day: how often the tunnel to the cluster's other hosts gives each a key anew, and how long the one before is kept to open by (Across hosts: the tunnel).

rc add insmod /hv.ko vms=/data/vms loads it so at every boot. vms= is at most 205 bytes: the VFS takes paths of 255, and under the folder go a VM's name of up to 32 and the longest file hv writes there, vm.toml.prev on its way in (vm.toml.prev.new). On arm64, which runs no Linux guest yet, hv takes no parameter, and refuses one. How a module is handed its parameters is in Loadable modules.

The file is a strict subset of TOML (modules/hypervisor/hv/src/config.rs): a key = value a line, # to the end of a line a comment, and for a value a string -- "basic", with TOML's escapes, or 'literal' -- a whole number, true or false, or a list of strings in brackets, over as many lines as it takes. No tables, no dotted or quoted keys: what it cannot read it refuses, saying the line, and so a key it does not know and one given twice -- memroy = 4096 would otherwise boot a guest of the default size without a word.

# A VM of nos's hypervisor: hv start <this folder's name> boots it (docs/hypervisor.md)
kernel = "/boot/bzImage"
initrd = "/boot/initrd"
cmdline = "console=ttyS0 root=/dev/vda rw"
memory = 1024
cpus = 2
disks = ["root.img"]
net = true
port = 3
forward = ["2222:22"]
restart = true
console_log = true
key unless said
kernel its bzImage -- (the one key a file must have)
initrd its initramfs none
cmdline its kernel's command line console=ttyS0 nolapic; with several CPUs console=ttyS0
memory MiB 256
cpus, cpu how many CPUs, and the host CPU its first runs on 1, and where it is placed
node the NUMA node its CPUs are placed on and its memory taken from (NUMA): a node the machine has, and cpu one of its CPUs where its first CPU falls, its memory with it
disks its disks, vda first, :ro after one it only reads none
net a NIC on the guests' switch false
port its port of the switch, 0..15: its address 10.0.100.(port+2) and its MAC the same at every start at its first start, the lowest no other VM's vm.toml names and none running holds -- written in, as its uuid is
forward "<nos's port>:<the guest's>"s, relayed once it runs and taken away with it none
restart booted again when it resets itself false
protected stopped and deleted through the host API, and deleted by hv delete, only when told force false
console_log its console to console.log in the folder true
log its console to the kernel log too false
input typed at its first prompt none
ioapic, xapic, apicv, rxmod, offload hv start's words of those names (offload = false is nooffload) as hv start

The name is the folder's: a letter or a digit, then letters, digits, ., _ and -, at most 32 -- a word of a command and a component of a path, with nothing in it either reads otherwise -- and neither digits alone nor all, which the commands read as a VM's number and as every VM (store::reserved). So a word is a name or a number and never both: a VM named 1 was once reached by hv stop 1 -- and by the bus's vm.stop, whose protected was read from another folder -- as whichever VM was number 1. A folder named so from before is listed by hv vms, saying it, and is not started until it is renamed. One VM of a name is on the list at a time: a second hv start web is refused while vm 0 is web, even stopped -- hv restart web boots it again, hv stop web takes it off. Its disks are claimed as any guest's are (disk::Claims), so no other guest writes them meanwhile. What a VM's vm.toml says while it runs -- protected to the bus's stop and delete -- is read from the folder it was started from, wherever that is.

console.log (modules/hypervisor/hv/src/vmlog.rs) is the guest's console as it wrote it, control sequences and all, appended a second at a time by a task of the VM's own (hv/vm<N>/log) from the console's ring -- never by the guest's CPUs, whose exits would otherwise wait on the disk. Between the guest's lines, where they happened, hv's own: --- hv: <date> UTC vm <N> started on cpus 2,3 -- ... ---, booting again -- <why>, stopped -- <why>, and off the list when hv stop -- or the unload -- takes it away. What the ring no longer has when the task gets to it, a guest printing more than 64 KiB in a second, is lost to the log, and the log says how much. Past 8 MiB the file moves to console.log.1, the one before it gone.

What it reaches the folder with is three calls of the file ABI made for it: kcore::fs::list, append and rename (kernel_dir_entry, kernel_file_append, kernel_file_rename in layers/fs/src/files.rs), and remove, which was there already.

/logs/hv.log (File logs) is the host's history of its VMs, every VM's in one file: a VM made (hv create, from words, a cloud's image or an image of NBS's), cloned and deleted -- or not, and why -- from the shell or the host API alike; started, with where and what (vm 3 (web) started on cpus 2,3 -- ...), or restored, and a start that failed and why; booting again and why, reset too often and left stopped, stopped after how long and why, not run; a move to another host and its rounds, pause and bytes, one come from another, and every step of either that went wrong; a split lock a guest made; a disk of NBS's attached, let go of, or out of memory for a request; a cluster network's tunnel to a host that stopped answering or cannot carry the MTU, a port vnet revoked, vnet gone from the host and back. Lines that can repeat -- a failed start a script asks again, a volume asked for again, a peer silent -- go through a limiter. The kernel log keeps the module's own lines: loaded and unloaded, the extension on and off, WARNINGs, the unload's stop of each VM, a host's device given to a guest, and a guest's console when log= mirrors it there.

What it does not do yet: read the file again at hv restart, which boots with what the start read -- hv stop and hv start take a changed file; start a VM when the module loads; or clone a VM that runs, whose disks its guest writes.

Checked by: hv-linux-test.py's VM phase, which makes a folder with hv create -- and is refused a second time -- boots it by its name, types at it by its name, is refused a second start, finds its boot and hv's lines in its console.log, boots it again, and is refused a vm.toml with a key it does not know; then loads hv again with vms=/data/vms, makes a VM there -- and the folder above it -- boots it and types at it by its name, finds its console.log there, and is told /vms's VM is none of this folder's; its network phase (--net), whose VM from its folder asks for port 5 and a forward -- its eth0 has the port's address and MAC, and its httpd answers from outside through the forward its vm.toml asked for; hv-test.py, whose last loads keep a vms= and a stop_secs= and say them, and refuse a parameter hv has not got, a vms= that is no absolute path and a stop_secs= past 600; hv-fuzz.py's config target, which holds the parser to never panicking on any text and render and parse to giving each other back what they were given, a vm.toml with an operator's comments rewritten to say another configuration to being read back as that one, every comment of a line of its own kept in its order, and a clone's command line to every word but ip='s -- and whose switch target claims a port asked for as well as the first free one; and fs-fuzz.py's vfs target, which holds the three file calls to its model of the tree. A clone, a delete and the vm provider: hv-test.py (x86-64) clones a VM made from a URL -- its disk held to the source's by SHA-256, mostly a hole, its seed made anew, its vm.toml the source's with a UUID of its own -- is refused a clone to a name taken, adds a forward through the provider and finds it kept in the vm.toml, the rest of the file as it was and the old beside it, makes a VM protected through the provider and is refused its delete without force, and deletes a VM keeping its disks; api-test.py --arch x86_64 takes the provider through the host API -- a VM of hvboot started as a job and found stopped, its console read and streamed, a reader's typing refused; a VM made of an image, cloned, the clone deleted; a protected VM's delete refused without force; a create of an image served slowly cancelled midway, nothing of it left -- and fs-fuzz.py holds the extents a clone copies by to the model's data.

Moving a VM to another host

A running VM of a folder moves to another host of the cluster while it runs (plans/vm-migration.md, M0-M5): its memory is copied as it goes on writing it, round after round, then it is paused for the last of it and its state, and one of the two hosts runs it from there -- never both, and never on a guess. Its network goes with it: its address, its firewall's flows, and the frames the other hosts still send to where it was.

hv migrate <vm> <host> [cold]      live: rounds as it runs, then paused for the last
hv save <vm> <file>                paused, its state and memory written, and off the list
hv restore <file>                  the VM the file names, running again from it
hv logcheck <vm> [rounds=N]        the dirty log held to it: its memory copied in rounds, then compared paused

The vm provider's migrate job is the same move on the bus (its log the command's lines, its progress the memory sent, a cancel before the last round's end leaving the VM running where it was), and the panel's VM page has it as Move to another host, the hosts the cluster's (cluster.hosts); once it is done, the page on the host it left says where it went, with a link to its page there. While it moves, hv list and the host API say it is moving -- a stop is refused meanwhile, as a second stop is, but the VM runs on -- and saving while hv save writes it; hv logcheck's VM is running all along.

A move from vm-migration-test.py, three nos under TCG on a Mac, the guest writing files of random bytes all the while and a probe on a third host pinging it -- every page through the test's hub in Python, so its times are the emulator's, not a host's:

> hv migrate mig b
hv: mig offered to b: 256 MiB, 1 cpu, 1 file of its folder
hv: mig round 0: 42 MiB of its memory (54723 pages of zeros) and 16 KiB of files in 4081 ms, the pages it wrote meanwhile marked
hv: mig round 1: 2148 pages (41 of zeros) in 569 ms; 695 written meanwhile
hv: mig sent in 3 rounds: 53 MiB of its memory, 16 KiB of files, its state 2 KiB, 53 flows of its firewall -- paused 760 ms so far
hv: mig runs on b -- paused 857 ms; its folder here taken away

The probe's pings, one each 0.3 s, through the moves: 23 of 24 answered across this one, 23 of 25 across the first (paused 1.9 s), 8 of 12 across a cold one (paused 4.6 s) -- what is lost is what came while it was paused.

What moves: a VM of a folder whose written disks are volumes of NBS's -- one at least: its first decides the handover -- whose read-only disks are volumes or files of its folder (a cloud VM's seed), and whose NIC, if it has one, is on a network of the cluster's. What is refused, said, the VM left running as it was: a disk of the host's own that it writes (a file, a device), a NIC on the host's network, forward= or an hv forward to it, public=, a folder with a folder in it or a file over 64 MiB, a vm.toml that names other disks than the VM runs with; on the other host a folder of its name, another CPU model or extension (below), a TSC rate more than 250 ppm off, a network vnet does not have there, no room. One VM comes in at a time.

The CPU a guest is shown has to be the same on the other host: the offer carries the policy's answer to every CPUID leaf and subleaf a guest of its shape can ask (policy::model_answers) and ARCH_CAPABILITIES, and the other host refuses one whose answers are not its own, naming the first leaf that differs. The cache leaves (2, 4, 0x80000005, 0x80000006, 0x8000001D) and the clock's (0x16) are left out: a hybrid CPU's cores answer them each its own way (the EX44's P and E cores), and a guest reads them once, at boot, for what they describe -- its TSC is leaf 0x15's, the host's whatever the core. hv info says the digest of those answers as each of this host's CPUs makes it -- the EX44's, its six P-cores' twelve threads and eight E-cores alike: cpu model c99c33c85afad94a -- what a guest moving here is held to, alike on the 20 CPUs -- or which two differ, and at which leaf.

The state (common/vm/vmstate, version 5, which reads versions 1 through 4 too: a host updated before the others takes their Q35 VMs, whose CPUs then start with MTRRs at reset and without Hyper-V) is every CPU's registers in the shape both backends share -- the general and control registers, the segments, the system MSRs, each vCPU's MTRRs, the debug registers, the XSAVE area checked as it is read back in, a pending event, the interrupt shadow -- each local APIC, the mailboxes, every device's. The VM part names Q35 or CloudHv. A firmware VM with Hv#1 also carries its reference-time epoch and overlay MSRs, crash state, and every VP's SynIC, stimers and VP-assist MSR; their deadlines are relative to the pause like the other timers'. Times are stored relative to the pause, the TSC carried by its offset, so the guest's clocks go on from where they stood, the pause left out (LinuxGuest::rebase). Every field is checked as it is read: a state is another host's word. hv save writes it and the memory into a file on the one host (save.rs).

The dirty log (hypervisor/hv/src/dirty.rs) finds what the guest writes while its memory is copied: every page of its RAM is made read-only in the nested table (npt.rs's and ept.rs's protect, a 2 MiB leaf split into the 4 KiB ones of the same memory first), so the guest's first write to a page is a nested fault, where the page is marked and made writable again; the host's own writes into it -- a disk's read, a frame received -- are marked as they are made. A round takes the marks and protects their pages again as one step under the table's lock, gives the table a new identity, and waits until every CPU of the guest has passed the top of its loop since (sync_tlbs): each entry from then on drops what the TLB kept of the table -- a fresh ASID under AMD-V, an INVEPT under VT-x -- so a page read after that is the guest's latest, and its next write faults. The rounds go on until what is left fits a 300 ms pause at the last round's rate; past five rounds the guest is slowed, 30% of its CPUs' time and 10% more a round up to 90%; past thirty the move is given up. The last round is paused and drained, its state taken as it paused, and the rings its devices write through mappings of their own sent with the marked pages. hv migrate ... cold pauses first and sends everything once.

The handover (common/vm/migwire's handover) is one compare and set in NBS's raft, on the writer of the VM's first written volume: the new host commits by attaching it for writing only from the writer of the generation the old host named (NBS's attach with expect); the old host, hearing nothing in a minute, takes it anew from that same generation itself. Whichever lands first decides, and the other is refused -- NotTheWriter, told apart from no answer, which is asked again with the same token and answered as it was. A side that never hears runs nothing: the VM is left stopped, its volume's writer the side that took it, hv start <vm> force where it is to run. The new host builds the guest with stand-ins behind its disks and NIC when it accepts, puts the state in once its memory is all there, and swaps the volumes it takes and the port vnet moves to it (vnet::port_move) in before the guest's first instruction there. The folder goes with it: written on the new host as it comes, its vm.toml last, at the commit; taken away on the old one once the guest runs there.

The network goes with it (M3). Its port is vnet's, and its address and MAC with it, so the guest's ARP cache stays right; the move tells vnet the port is the new host's (vnet::port_move), and vnet tells hv's keeper on every host of each change it applies (vnetmeta::KEEPER, the mailbox hv.keeper), which asks for its table at once rather than at its next second. Until a host has it, what it sends the port goes to the old host, which carries it on to the new one for ten seconds (Switch::moved_away, MOVED_NS) -- from the moment it hands the VM over, its end there still going; the new host takes those from that host alone, for that port alone, for those seconds, though their sender is a port on a third host (Switch::came_here, the tunnel's arrived) -- the host that had the VM's memory a moment ago is trusted with no more than it was. The port's stateful firewall's flows -- what lets the answers to the VM's own connections in -- are taken as it pauses and made the new port's, each running out as long after as it had left (flows_of, adopt_flows, the message Flows, at most 4096); hv list there counts them. Connections masqueraded through hv0 are lost: NAT's state is the old host's (D1).

VT-x's half -- its TSC offset, its INVEPT on a renewed table, its pending debug exceptions -- runs only where VT-x is (the EX44).

trace on migrate records the rounds, the takes, both sides' ends, the new host's messages and the dirty log's TLB waits (A migration's events). Its gates: hv-fuzz.py's vmstate, handover, migwire, dirtylog and policy targets, its tunnel target (ports migrated between three hosts' real tunnels, the others' tables old, what the old host carries on held to the rules above), vnetswitch (ports moved away) and flowmove (a port's flows made another switch's port's: it refuses nothing the old one lets in); nbs-fuzz.py for the attach's expect; vm-migration-test.py (three nos, a guest on a volume and on vnet's network moved live and cold, back and forth, writing all the while, a probe on the third pinging it); hv-linux-test.py --save; the panel's test of its button; web-test.py for the descriptor.

ACPI

A PC's firmware leaves its OS tables that say what the machine is, and a kernel with ACPI reads them before anything else: where its CPUs are, how to turn the machine off and reset it, where its PCI bus is and which interrupt each device has. Every Linux guest is given them (hv::acpi), and the fixed hardware they describe (hv::devices::pm). A kernel without ACPI, or told acpi=off, finds nothing of it in its way and boots as it always did.

[    0.039122] ACPI: RSDP 0x00000000000E0000 000024 (v02 NOS   )
[    0.042362] ACPI: XSDT 0x00000000000E0240 00002C (v01 NOS    HV       00000001 NOS  00000001)
[    0.047220] ACPI: FACP 0x00000000000E0120 000114 (v06 NOS    HV       00000001 NOS  00000001)
[    0.051699] ACPI: DSDT 0x00000000000E0080 00009B (v02 NOS    HV       00000001 NOS  00000001)
[    0.056005] ACPI: FACS 0x00000000000E0040 000040
[    0.102725] ACPI: PM-Timer IO Port: 0x608
...
[    0.545105] ACPI: Interpreter enabled
[    0.545535] ACPI: PM: (supports S0 S5)
[    0.549186] ACPI: Using PIC for interrupt routing
[    0.565105] ACPI: PCI Root Bridge [PCI0] (domain 0000 [bus 00-ff])
[    0.577561] acpi PNP0A03:00: fail to add MMCONFIG information, can't access extended configuration space under this bridge
[    0.589327] pci_bus 0000:00: root bus resource [io  0x0000-0x0cf7 window]
[    0.593165] pci_bus 0000:00: root bus resource [io  0x0d00-0xffff window]
[    0.597229] pci_bus 0000:00: root bus resource [bus 00-ff]
[    0.631608] PCI: Using ACPI for IRQ routing
[    0.657669] clocksource: acpi_pm: mask: 0xffffff max_cycles: 0xffffff, max_idle_ns: 2085701024 ns
[    0.769271] input: Power Button as /devices/LNXSYSTM:00/LNXPWRBN:00/input/input0
[    0.773949] ACPI: button: Power Button [PWRF]

(The gate's guest of one CPU under TCG: a Linux 6.18 with ACPI, its power button and evdev.)

  • The tables go in the BIOS area from 0xE0000, which the e820 map reserves: the RSDP first, where a kernel scanning for it finds it, and the zero page's acpi_rsdp_addr pointing at it for one that looks there. An XSDT names the FADT and, for a guest whose CPUs have local APICs, a MADT. A legacy FADT names the FACS and DSDT; the firmware machine's FADT is hardware-reduced, with no FACS or legacy PM1 blocks. Tables are ACPI 6.3's, laid out with their checksums into a buffer and copied into guest memory as the MP table is -- nothing of the guest's is kept.
  • The fixed hardware is all on ports (0x600-0x60B, as an ICH lays it out): the PM1 event block's status and enable registers, the PM1 control register, and the PM timer -- 24 bits at 3.579545 MHz, counting the host's time from when the guest was made. The host keeps its time by its TSC -- under KVM by kvmclock, the TSC scaled -- and the guest reads that TSC and is told its rate, so the two agree; Linux, which checks its TSC against the PM timer every half second once it has one, finds them agreeing. The SCI is the 8259's IRQ 9, and a level: requested while an enabled event is set, requested again if one still is when the guest ends the interrupt, withdrawn when none is. There is no SMI command port -- the machine is in ACPI mode from the start, SCI_EN reading set -- and no GPE block. The edge/level control registers beside the 8259s (0x4D0) keep what is written to them, and start with IRQ 9 level-triggered: what a kernel sets them to, and, finding them so, need not warn that it did. The reset register is the chipset's 0xCF9, trapped already: a kernel with ACPI reboots through it first, the guest asked for a reset, 0x06 to port 0xcf9.
  • The firmware machine is hardware-reduced. Sleep control and status are at 0x600 and 0x601, as CloudHv's EDK2 ResetSystem runtime has them: S5 is 0x34 written to control, rather than PM1's different bit positions. The FADT names the same registers. There is no legacy PM1 event block on this machine, so the address does not collide with one; ordinary Q35 keeps PM1 status at 0x600 and does not take that write as power-off. This is what Windows accepts from its CloudHv firmware path; presenting that path with a legacy FADT led to bugcheck 0xA5(0x11, 0x3).
  • The firmware console is described too. An SPCR revision 2 names the 16550 at COM1 (0x3F8), IRQ/GSI 4, 115200 8N1 and VT-UTF8; the DSDT also gives COM1 a PNP0501 device with those I/O and IRQ resources. Legacy Q35's tables are unchanged.
  • The MADT lists a local APIC for each CPU and NMI on every LINT1 -- and, for a guest given one, the IO-APIC, with the two overrides a PC's has: the timer's IRQ 0 on its pin 2, and the SCI a level, active high (The IO-APIC). The MP table is still there: a kernel with ACPI finds its CPUs in the MADT, one without in the MP table, and both are told the same.
  • The DSDT is the one table in AML, and small: \_S5, the PCI host bridge, the processor container CPUS with an ACPI0007 device and _UID for every MADT CPU, and the panic device PEVT (QEMU0001, its port) when the VM has one (A guest that panics) -- which the listing below, of a VM without, leaves out. The bridge has to be there. A Linux with ACPI finds PCI through the namespace alone and never probes the bus -- pci_legacy_init is not even called -- so without one the guest would have no disks and no NICs. Its _CRS gives bus 0-255, the configuration ports, the I/O either side of them and the window its functions' MSI-X pages are in (a BAR outside every window is one an OS moves, and these are fixed); its _PRT routes each device's INTA to the 8259 IRQ its interrupt line register names. As ACPICA's iasl disassembles it, for a guest of several CPUs with a NIC and two disks:
Name (_S5, Package (0x04) { 0x05, 0x05, Zero, Zero })
Scope (\_SB)
{
    Device (PCI0)
    {
        Name (_HID, EisaId ("PNP0A03") /* PCI Bus */)
        Name (_UID, Zero)
        Name (_CRS, ResourceTemplate ()
        {
            WordBusNumber (ResourceProducer, MinFixed, MaxFixed, PosDecode,
                0x0000, 0x0000, 0x00FF, 0x0000, 0x0100,,,)
            IO (Decode16, 0x0CF8, 0x0CF8, 0x01, 0x08, )
            WordIO (ResourceProducer, MinFixed, MaxFixed, PosDecode, EntireRange,
                0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8,,, , TypeStatic, DenseTranslation)
            WordIO (ResourceProducer, MinFixed, MaxFixed, PosDecode, EntireRange,
                0x0000, 0x0D00, 0xFFFF, 0x0000, 0xF300,,, , TypeStatic, DenseTranslation)
            DWordMemory (ResourceProducer, PosDecode, MinFixed, MaxFixed, NonCacheable, ReadWrite,
                0x00000000, 0xFE000000, 0xFE007FFF, 0x00000000, 0x00008000,,, , AddressRangeMemory, TypeStatic)
        })
        Name (_PRT, Package (0x03)
        {
            Package (0x04) { 0x0001FFFF, Zero, Zero, 0x0A },
            Package (0x04) { 0x0002FFFF, Zero, Zero, 0x0B },
            Package (0x04) { 0x0003FFFF, Zero, Zero, 0x0B }
        })
    }
}

Q35's MCFG and the motherboard resource reserving ECAM are beside this excerpt (PCI Express's configuration space). What is left out is MMIO this does not emulate yet (MMIO) -- the HPET; the IO-APIC is there for a guest given one -- and what a guest does without: C- or P-states on the processor objects (only their identity and presence are described), the ISA devices (a kernel finds a PC's serial port, RTC and timer where they always are), GPEs, and any sleep state but S5. A guest of one CPU gets no MADT: it has no APIC.

hv stop asks first. It presses the guest's power button -- sets the fixed button's status, and raises the SCI if the guest's OS has enabled the event -- and gives the guest secs (30 unless told) to turn itself off; one that does ends the guest powered itself off, S5 by its ACPI PM1 control register. A kernel hears the button as a key, KEY_POWER on its input device, and what answers it is userspace's: systemd-logind shuts a distribution down, BusyBox's acpid runs /etc/acpi/PWRF/00000080. What answers it may decline a press, and forget it: logind refuses one while a shutdown is inhibited -- Refusing poweroff operation, shutdown is inhibited by UID 0/root, PID .../unattended-upgr, as Ubuntu's unattended-upgrades inhibits one while it installs -- and the press after that ends is the one it acts on. So a guest that heard the button and runs still has it pressed again every 15 s while its time lasts (REPRESS_S, Shared::press_again), hv stop's and an unload's waits pressing it once between them, and the report's acpi line counts the presses; a press it does not hear after one it heard is of a guest on its way down, its kernel turning the event off as it powers off, and the wait goes on. A guest that hears it and does nothing is stopped when its time is up, its power button went unanswered for 30 s. One whose OS never enabled the event -- no ACPI, acpi=off, not booted that far -- cannot hear it, and the first CPU's loop, which takes the press from the command, says so: it is stopped at once, nothing in it listens to its power button. secs=0 stops a guest without asking, and hv stop all presses every button at once and waits for the guests together.

So does the module's going -- rmmod hv, and nos's own poweroff and reboot, which unload every module on the way down while the files, block I/O and soft IRQs a guest's shutdown writes through are all still there (ModuleTable::unload_all): every guest's power button pressed at once and the guests given stop_secs= of insmod's together -- 120 s unless told, longer than the 90 s systemd gives a service that will not stop before it unmounts the disks anyway -- and those still running then stopped where they are. A guest that turns itself off ends stopped for the unload -- the guest powered itself off, in the kernel log; one whose OS never hears the button is stopped at once, as hv stop stops it. Without it a guest's disk was cut off under it: its last writes still in its page cache, its journal left to replay -- what hv-linux-test.py --disk --acpi now holds nos's own poweroff to, a guest's ext4 left mounted coming back clean. rmmod goes on in the background after five seconds, lsmod saying unloading and the kernel log how each guest ended; the halt waits, and says why in the log before it does (hv: unloading -- 2 vm(s) asked to turn themselves off, given 120 s). stop_secs=0 is the old way, every guest stopped where it is. Meanwhile no guest starts, and the hv command and the vm provider are gone with the module, closed as its unload began (Unloading) -- lsmod shows it unloading and the log how each guest ends; an hv stop already giving one its time then goes on with it, the unload's time and its own both running: the first to end takes the guest off the list. On a machine whose only console is the network the netconsole stays up through all of it -- stopped after the modules and the filesystems, sending what it still holds as it goes (rust_net_stop_netconsole) -- so that the wait is seen.

A power-off is a write to a port, as a reset is: SLP_EN with S5's sleep type in PM1a's control register on legacy Q35, or 0x34 in CloudHv's reduced sleep control at 0x600. ACPICA writes the legacy type first and the enable bit second; CloudHv's ResetSystem writes its one byte directly. Either stops the VM where the guest wrote it -- Stop::PowerOff, which is not a reset: a guest started with restart that turns itself off stays off. A sleep type the DSDT does not offer is left alone, and the report says the guest asked for it.

The gate is tests/hv-linux-test.py --acpi, with a kernel built with ACPI, its button and evdev: the boot's lines above and nothing of a firmware bug, a TSC the watchdog marked unstable or a PM timer that failed its checks; reboots through 0xCF9; the SCI on IRQ 9 and the PM timer a clocksource; hv stop answered by acpid with a power-off; and a guest that hears the button and does nothing, stopped when its time is up. The tables themselves were checked with iasl as they were written. tests/hv-distro-test.py boots Alpine and Debian on their ACPI, and has hv stop shut Debian down -- or, with --acpi-off, boots them as before.

What the machine is: SMBIOS

The other tables a PC's firmware leaves say what the machine is rather than how to drive it (DMTF's SMBIOS, hv::smbios): who made it, what product it is, its serial number and its UUID. Linux reads them into /sys/class/dmi/id, and what reads that knows the machine by it -- systemd, cloud-init, dmidecode, software licensed to a machine -- the UUID above all, which is to stay the same from boot to boot.

[    0.000000] SMBIOS 3.2.0 present.
[    0.000000] DMI: nos nos hv, BIOS dev (unknown) 10/27/2026

(The gate's guest, under nos built in a container with no git: its version is nos's, dev and the commit, which such a build does not know.)

  • The tables are SMBIOS 3's, the 64-bit entry point at 0xF0000 -- where a kernel with no EFI scans for one, in the BIOS area the e820 map reserves, after the ACPI tables -- and SMBIOS 2.1's 32-bit one after it, _SM_ and its _DMI_ half, the same table by its 32-bit address, for a kernel before 4.0 or a dmidecode that knows no other; then the BIOS (type 0, which says the machine is a virtual one), the system (1: maker nos, product nos hv, nos's version, the VM's name for its serial, and its UUID), its chassis (3), the boot (32) and the end (127). Every string is the operator's to have made -- a VM's name -- so each is cut to 64 bytes of printable ASCII, anything else a ?.
  • The UUID is the VM's. A VM's folder keeps it in its vm.toml (uuid = "..."), which hv create writes; a VM whose file was written before VMs had one is given one at its first start, added to the end of the file -- the lines the operator wrote left as they were -- and the same at every start after. One started from its kernel's path takes uuid=, or a random one, kept across its restarts; its serial is its number.
  • So is its port of the switch, and with it its MAC and its address: a VM on the switch whose vm.toml names no port is given one at its first start -- the lowest no other VM's file names and no VM running holds -- and it is written in, as the UUID is (store::keep_port). Taken afresh at each start, a port went by the order the VMs started in: two started the other way round after their host's reboot swapped theirs, and the Ubuntu one's network, its netplan matching its NIC by the MAC cloud-init saw at its first boot, came up with no DNS server.

The gate is tests/hv-linux-test.py --smbios with a kernel built with DMI and DMIID: what /sys/class/dmi/id says, a VM whose vm.toml had no UUID given one and written into the file, the same UUID at its next start, and a VM started with uuid= told it. The hv fuzzer's smbios target builds the tables from random names, versions and UUIDs and reads them back as Linux's dmi_scan does.

A guest that panics: pvpanic

A kernel that panics comes to rest in panic: with panic=N it reboots N seconds later, and without, it spins there for good, a host CPU its own for nothing, and all a report could say of it is that it halted. QEMU's panic device lets it say so (hv::devices::pvpanic): one I/O port, 0x505, which the DSDT describes as QEMU0001 -- what Linux's pvpanic-mmio binds to, as a distribution's kernel has it built -- and which the driver reads for the events the device takes, PANICKED and CRASH_LOADED, then writes as its panic notifier runs, the guest's other CPUs stopped already. PANICKED stops the VM where it is (Stop::Panicked), before its own panic= could reboot it: the report says the guest's kernel panicked, and a VM started with restart is booted again, as after a reset of its own, up to the same limit. CRASH_LOADED -- a crash kernel loaded, which the guest boots itself -- is counted, and the guest goes on.

The gate is tests/hv-linux-test.py --pvpanic, with a kernel built with ACPI and PVPANIC_MMIO: a guest with no init stopped by its panic, before panic=1 reboots it; one with restart booted again at each until the loop is called one; a running guest's driver bound to QEMU0001:00, its init's exit a panic that stops it the same way; and its DSDT taken back out of the guest and through iasl, where the machine has it.

A distribution

The guests above run a kernel built for the purpose, with a BusyBox initramfs. A distribution's is built for every machine instead -- SMP, ACPI, KASLR, high-resolution timers, virtio as modules its initramfs loads -- and Alpine's virt ISO boots under hv start as it ships: its kernel and initramfs taken out of the ISO, and the ISO itself the guest's read-only disk.

$ hv start /alpine/vmlinuz-virt mem=512 initrd=/alpine/initramfs-virt disk=/alpine/alpine.iso:ro net restart cmdline=console=ttyS0 nolapic acpi=off modules=loop,squashfs,sd-mod,usb-storage
$ hv wait 0 secs=600 login:
hv: vm 0 printed "login:", 36004 ms in
$ hv send 0 root\n
$ hv exec 0 cat /etc/alpine-release; uname -r
3.24.2
6.18.52-0-virt
localhost:~#
$ hv exec 0 date
Wed Sep 23 21:32:50 UTC 2026

(Under TCG, twice emulated: 36 s to the login prompt -- recorded before the machine had ACPI, when a distribution was booted acpi=off.) Its initramfs loads virtio_blk, finds the ISO on vda, mounts it and installs the base system from the ISO's packages into a tmpfs, and OpenRC brings it up to a getty on ttyS0. nolapic makes it a PC of one CPU with no local APIC, taking its interrupts from the 8259s. With acpi=off, as above, it finds its PCI devices through configuration mechanism 1 and each virtio device's interrupt line in its configuration space; without, as the gate boots it now, it takes both from its ACPI tables -- the DSDT's host bridge, and its _PRT (ACPI) -- and is at its login prompt 14 s after the VM starts, nested under KVM on the i5-13500. On the switch (net) its initramfs configures eth0 from the ip= the VM is given, and writes the dns0 there to resolv.conf; through NAT it reaches what nos reaches -- apk update from Alpine's own mirror, the name looked up through nos's DNS server -- and apk add openssh-server installs from the ISO, its own sshd reached from outside nos through hv forward. reboot resets it -- through the reset register its FADT names, or with acpi=off the keyboard controller -- and with restart it boots again.

What it took that the purpose-built kernel did not:

  • The PIT's one-shot modes. A kernel with high-resolution timers and a clocksource good enough for them -- the TSC, which the guest calibrates against the PIT by itself on a real CPU -- moves its tick from the PIT's periodic mode 2 to one-shot mode 4, a count at a time. Channel 0 raised IRQ0 only in the periodic modes, so the guest's timers would have stopped at the switch. Under TCG an exit costs more than the calibration loop allows and the guest stays on jiffies and a periodic tick; forced onto the TSC (tsc_early_khz=... tsc=reliable) it runs its tick through mode 4, and sleep 2 takes 2.03 s.
  • A clock. The RTC answered a fixed 2026-01-01, and OpenRC took every file of the ISO for one from the future, and said so at every service it started. It answers the host's wall clock now, read when the guest is made and counted on by the host's clock since boot; what the guest writes to the time registers does not stick.
  • One CPU of its own. The topology CPUID gave was the host's: the guest took the APIC ID of the host CPU its vCPU ran on for its own ("APIC ID mismatch") and listed SVM's features for an extension it is not given.
  • Typing at a login prompt. hv exec and input= wait for a shell's prompt -- BusyBox's line editor asking where the cursor is -- and a getty asks for nothing, and throws away what was typed before it printed its prompt. hv send types now, as at a terminal, and from then on for that boot what exec types goes in as it is typed too; hv wait is what finds the moment.
  • hv wait in the current boot. It searched the whole console, so after a reboot it found the last boot's login:; it looks from where the current boot began.
  • disk=path:ro: virtio's read-only feature, and a write the device refuses itself before any reaches the file.
  • An ip= that names no device. A kernel told eth0 waits twelve seconds for it to appear (DEVICE_WAIT_MAX), and a distribution's NIC driver is a module its initramfs loads after that; with the field empty the kernel finds no device at once and leaves ip= to the initramfs, whose own parser takes the first interface that comes up.

Debian

Debian 13's nocloud cloud image boots the same way: its kernel (6.12.107+deb13-amd64, the generic one) and initrd read out of the image's own /boot, and the image itself -- 3 GiB, a raw file on nos's root -- the guest's disk, whose root partition its initramfs-tools mounts read-write:

$ hv start /debian/vmlinuz mem=768 initrd=/debian/initrd disk=/debian/debian.raw net restart cmdline=root=/dev/vda1 ro console=ttyS0 nolapic acpi=off systemd.set_credential=passwd.plaintext-password.root:nos systemd.set_credential=firstboot.locale:C.UTF-8 systemd.set_credential=firstboot.keymap:us systemd.set_credential=firstboot.timezone:UTC
$ hv wait 0 secs=600 login:
hv: vm 0 printed "login:", 38931 ms in
$ hv send 0 root\n
$ hv send 0 nos\n
$ hv exec 0 cat /etc/debian_version; uname -r; systemctl is-system-running
13.7
6.12.107+deb13-amd64
running

Its root is locked (!unprovisioned) until systemd-firstboot sets it, and firstboot asks at the console for the root password, the locale, the keymap and the timezone -- a typed line that is not one is "Invalid data" -- so systemd.set_credential= on the kernel command line gives it all four, as systemd provisions a machine nobody sits at. systemd then reaches running with no unit failed, 38 s after the VM starts under TCG, and a file written to its root is still there after a reboot. Its networkd has no .network for an ethernet interface -- the image expects cloud-init or the like to write one -- and one more credential is that file: systemd.set_credential_binary=network.network.50-nos:<base64> of [Match] Type=ether / [Network] DHCP=ipv4, which systemd-network-generator puts in /run/systemd/network. networkd then asks the switch's DHCP server, takes its port's address, nos as its router and nos's DNS server for systemd-resolved, and the guest reaches the world through NAT. That command line runs past the 255 characters nos's /etc/rc allowed a line; it allows 1023.

After typing reboot, a script cannot wait for the next login: with a plain hv wait: the boot going down still has the last one on its console, and systemd's reboot gives the shell its prompt back before the system goes. hv wait 0 boot=1 login: waits for the VM's first restart, and then for the text in the boot after it.

(The transcript above is from before the machine had ACPI, booted acpi=off under TCG.) On its ACPI, as the gate boots it now, systemd-logind hears its power button, and hv stop shuts it down -- its services stopped, its root unmounted -- and it turns itself off, nested under KVM on the i5-13500:

$ hv stop 0 secs=300
hv: vm 0 stopped -- the guest powered itself off, S5 by its ACPI sleep control register, at 0xffffffff8f1d5ae3
  stopped    the guest powered itself off, S5 by its ACPI sleep control register, at 0xffffffff8f1d5ae3, after 7624 ms
  ...
  acpi       taken by the guest's OS; 2 SCIs, the power button pressed 1 times
  vda        3072 MiB: 2499 reads (75589 KiB), 215 writes (3805 KiB), 36 flushes, 0 errors

-- 7.6 s for that whole boot, from its start through the login, the gate's commands and the shutdown.

And one thing in the kernel. Rebuilding the rebooted guest under TCG held the page allocator's lock for more than ten seconds, with every other CPU idle, and the watchdog panicked the machine: each page was zeroed under the lock, and QEMU throws away its translations of a page that held a guest's code as the page is written -- a guest that had run for half a minute took 36 s to rebuild. The zeroing is done off the lock now (PageTable::alloc_page).

The gate is tests/hv-distro-test.py --iso alpine-virt-*-x86_64.iso [--debian debian-*-nocloud-amd64.raw] [--internet] (Tests and gates): manual, since the images are downloads; --internet adds what needs the test machine's own way out, a name looked up and a mirror fetched from.

A guest's own kernel: PVH and hvboot

A guest booted as above runs the kernel it was handed, at every restart again: its own /boot is never read, so a distribution's kernel updates are never booted, and its kernel and initrd have to be taken out of the image first. A guest booted by hvboot runs the kernel its own disk's GRUB would, as a cloud's does:

$ hv start /lib/hvboot mem=1024 disk=/vms/ubuntu/ubuntu.raw disk=/vms/ubuntu/seed.iso:ro net restart
hv: vm 0 started on cpu 3 -- /lib/hvboot, 1024 MiB, 1 cpu, cmdline "console=ttyS0 nolapic ip=10.0.100.2::10.0.100.1:255.255.255.0:::off:10.0.2.3", restarted when it resets
$ hv console 0
hvboot: started by PVH: 1023 MiB of RAM, its command line "console=ttyS0 nolapic ip=10.0.100.2::10.0.100.1:255.255.255.0:::off:10.0.2.3 tsc_early_khz=1000019"
hvboot: vda16/grub/grub.cfg: "Ubuntu", the default, 0
hvboot: vda16/vmlinuz-6.8.0-147-generic: boot protocol 2.15, 14710 KiB at 0x1000000, initrd 29988 KiB at 0x3e2b6000, read in 497 ms
hvboot: its command line: BOOT_IMAGE=/vmlinuz-6.8.0-147-generic root=LABEL=cloudimg-rootfs ro console=tty1 console=ttyS0 console=ttyS0 nolapic ip=10.0.100.2::10.0.100.1:255.255.255.0:::off:10.0.2.3 tsc_early_khz=1000019
[    0.000000] Linux version 6.8.0-147-generic (buildd@lcy02-amd64-...) ...

-- Ubuntu 24.04's cloud image as it ships, made raw, and its NoCloud seed: no kernel, initrd or command line taken out of it. hvboot is at the kernel 0.6 s after the VM starts, under TCG; the guest at its login prompt 150 s in, as with its kernel taken out by hand (138 s), the rest of the boot being the guest's own. Debian 13's nocloud image boots the same way, hvboot at the kernel 0.6 s in and the login prompt 34 s in, its root found by the PARTUUID its own grub.cfg gives and its systemd credentials the VM's cmdline=, which goes after the entry's line. After apt upgrade installs a kernel and update-grub names it, the next boot -- a restart included, the VM being built again from its files -- boots that one.

PVH (hv::pvh) is how hv starts it. hv boot and hv start take an ELF as well as a bzImage, and tell them apart by the file's first bytes: an ELF is booted by the x86/HVM direct boot ABI Xen made (its docs/misc/pvh.pandoc), which Linux's vmlinux, QEMU's -kernel, Cloud Hypervisor and the firmware written for them -- rust-hypervisor-firmware, OVMF's CloudHv -- speak. Its loadable segments go at their physical addresses; the entry is the one its Xen note of type 18 (XEN_ELFNOTE_PHYS32_ENTRY) names; and hv lays out an hvm_start_info where a bzImage's zero page would be -- the command line (with what hv adds a bzImage's: the TSC's rate, noapic, ip=), the initrd as its one module, the ACPI RSDP, and the memory map, the same e820 a bzImage is given (linux::e820_entries, one list for both). A guest of several CPUs gets the same MP table. Its first CPU starts at the entry in 32-bit protected mode -- flat segments, paging and interrupts off, EBX at the start info: what reset leaves but for CR0's PE (svm::protected_mode, for both backends). Paging off takes unrestricted guest under VT-x, as a guest of several CPUs' real-mode start does already, and a start where the CPU has none is refused, saying so.

The image is a file of nos's, and its headers are checked before anything in them is used: ELF32 or ELF64, at most 64 program headers and 4 KiB of notes read; a segment outside the file or outside the guest's RAM above the tables written below 1 MiB, two segments over the same bytes, an entry that is not in a segment's file bytes, or two entries -- each refused. hv-fuzz.py's pvh target holds the reader to that over ELFs of either class made from its input, the start info to what the guest was given -- its magic, its one module, a memory map of RAM up to the guest's last byte in order -- and the entry to paging off. hv's unsafe count is still 4.

hvboot (src/crates/hypervisor/hvboot, built by make and kept as /lib/hvboot in the system image) is a PVH ELF of 227 KiB, linked at 1 MiB, that runs in the guest. It reads:

  • its start info: the memory map, the RSDP, its modules -- an initrd= given to hv start, which it does not use, and says so -- and its command line, split where Linux splits its own, at blanks outside double quotes: hvboot.entry= (an entry by number, N>M, title or id, as GRUB's default takes one; titles with spaces in them in double quotes), hvboot.disk=N (look on that disk alone) and hvboot.verbose its own, every other word for the kernel as it was given (start.rs, options.rs);
  • the guest's legacy virtio disks on PCI bus 0, a request at a time with the interrupt never taken: each poll reads the ISR, a port, and the exit that takes is where hv hands back what is done -- a request not answered in 30 s is said, not waited on, and its disk reset and given up: the device still held the chain, whose buffers the loader had given to something else since, and the next request's slot and index were the same, so a late answer was taken for that one's; a disk of blocks larger than a sector (F_BLK_SIZE: QEMU's of a 4Kn disk -- hv's show 512-byte sectors whatever their backend's block) read and written in whole blocks, the part of one at either end of a read or a write through a block's buffer -- a write's read first, changed and written whole (grubenv's) (virtio.rs);
  • each disk's partitions, from its GPT -- header and array each checked by their CRC -- or an MBR, an XBOOTLDR partition (a /boot of its own, as Ubuntu's) first, and a disk with no table looked at whole; a partition that runs past the disk's end is said and passed over (gpt.rs);
  • ext2, ext3 and ext4, read-only but for grubenv's block (below): extents and block maps, 64-bit descriptors, flex_bg, htree directories read as the linear ones they also are, inline data, symlinks, holes; an incompatible feature it does not read is refused by name, said as the filesystem is passed over and again when no filesystem is found -- GRUB 2.06 reads meta_bg and encrypt, which this refuses, and refuses inline_data, which this reads -- and the journal is not replayed, as GRUB does not replay it (ext.rs, over the format crate src/crates/common/storage/extfmt, which the kernel's ext4 driver reads through too);
  • the first /boot/grub/grub.cfg or /grub/grub.cfg (or grub2's) on them -- a path that could not be looked for, a read that failed, ending the search, said, rather than another filesystem's being booted -- and grubenv beside it: the menu, submenus within submenus, each entry's linux, initrd and the search or set root naming its filesystem -- by UUID, label, file or hdN,gptM -- the root set outside the entries, which they start from, and the default, grubenv's next_entry and saved_entry where the script defers to them, as grub-mkconfig's does. A next_entry it boots it empties on the disk first, as that script's save_env does -- grubenv's block rewritten in place, every other line as it was, and only after the bytes there are found to be the ones it read, nor where the journal is not replayed: the one write hvboot makes. grub-reboot's entry is booted once, as under GRUB, and a disk that cannot be written says that the entry will be taken again. It is not GRUB's interpreter: it reads the script's words as GRUB does -- quotes, escapes, comments, variables, a brace a token of its own -- and makes a command's arguments of them as GRUB's script does, an unquoted variable's value split at blanks; it reads the blocks but runs no condition: every branch of an if is read, the last search and linux an entry has win (a linux unloading the initrd before it), a variable has a value only where an assignment outside a condition gives it one, and the chosen entry's body is read with the variables as the whole file leaves them, as GRUB runs it at boot. default names an entry as GRUB's does: a number as strtoul reads one (0x2, 010), a title or an id, > into a submenu and >> for a > of a title's own, a submenu's first entry when the rest names nothing. grubenv is read as GRUB reads it: its signature or nothing, \X as X. Each of these is what GRUB 2.06 does, found by booting it (tests/hvboot-test.py has the cases). What it cannot place it says: another file read for the menu (configfile, blscfg), a variable with no value, a } that closes nothing. What it holds is bounded and said where a bound is met: a grub.cfg of 128 KiB and a grubenv of 4 KiB at most, 2048 menu items, 256 variables, 256 KiB of what their values add, 64 initrds an entry (grub.rs, plan.rs).

It loads the kernel at its pref_address and the initrds high, one after another at GRUB's 4-byte alignment, the bytes between them zeros as GRUB's are, into RAM the memory map has, clear of itself; builds the zero page -- the start info's memory map as its e820, the RSDP -- and the command line GRUB's linux would give, BOOT_IMAGE= first, an argument with a space in it in double quotes and \, ' and " escaped, then its own line's words after the entry's, as hv gave them; resets the disks; and enters the kernel's 64-bit entry, as hv enters a bzImage (boot.rs) -- the header read and the zero page made by the crate hv makes a guest's with (common/boot/bzimage), one copy where there were two. Whatever it cannot do it says on the console and turns the guest off through its ACPI -- the VM stops with "the guest powered itself off", the reason in its console, and when no filesystem or no grub.cfg is found, everything it passed over and why -- rather than sitting halted with nothing said; a fault in it is said too, with where it happened, and a heap run out with what the heap held.

It runs in the guest, and what it reads is the guest's own: a bug in it is the guest's, not nos's, and the host's half of this is the PVH loader above. What it boots is plan's to work out -- the filesystems, grub.cfg, the entry, where the kernel and the initrds go, the command line, and the reading of them into place -- over the disks and RAM it is given and nothing of the platform's; it and the parsers it reads through (gpt, ext, grub, and bzimage's) are plain Rust over byte slices with no unsafe. Its 41 unsafe sites are the platform's: ports, physical memory, the heap (arena.rs: first fit over its free blocks, a block given back merged with its neighbours, in place of a bump allocator that took back only its newest block -- an extent tree two levels deep, or a long enough grub.cfg, spent the heap through blocks it never took back), the virtio rings, the IDT and the jump. The host's harness (tests/fuzz/hvboot) runs plan itself, not a second copy of its rules, under arena.rs over a stretch no bigger than hvboot's heap: read off Ubuntu 24.04's and Debian 13's images, the kernels and initrds come out byte for byte as debugfs reads them, and tests/hvboot-test.py holds it to the entry GRUB would boot on disks it makes -- GPT, MBR and none; ext4, ext3, ext2 of 1 KiB blocks into the double indirect ones; a default, a next_entry, a saved_entry into a submenu; GRUB 2.06's own answers to how a grub.cfg is read; what is said when nothing boots; a grub.cfg as long as is read, of every shape that costs the reading the most, and an initrd whose extent tree is two levels deep, each inside the heap and all of it given back -- and fuzzes each disk's metadata, every run held to the heap the same way.

What it does not do: boot what is not Linux -- Windows has no boot protocol of its own to be entered by, and needs firmware. OVMF's CloudHv is built for that same PVH entry by scripts/build-cloudhv.sh; the machine it needs is the work in plans/windows.md, not a supported Windows guest yet. Nor can hvboot read XFS or btrfs, so not a /boot of the RHEL family's, nor an LVM or LUKS one; read BLS entries (blscfg); or EFI -- the kernel is entered by the boot protocol, as hv enters a bzImage, and has no EFI runtime. And the image is still to be made raw: the disk is a file of nos's, as any guest's.

The gates are hv-fuzz.py (the pvh target), hv-test.py (hvboot started by PVH with no disk: it reads the start info, says it has no disk and turns the guest off, on whichever backend the machine has), hvboot-test.py (host, in CI) and hv-distro-test.py --ubuntu ... --debian ... --hvboot (manual): the same checks as without, a guest provisioned, networked, rebooted -- hvboot run again -- and shut down, and two more: hvboot reached the kernel, and booted the entry the image's own grub.cfg makes its default.

More than one CPU

cpus=N on hv boot and hv start gives a guest N CPUs, up to 16. Each is a task of its own on a host CPU of its own, and where they go is hv::place's to say, over hv::topology -- which reads a CPU's core and cache from its APIC ID and CPUID, and on a hybrid part asks each CPU which kind of core it is (leaf 0x1A) -- by the rule hv cores sets. Two CPUs of one guest never share a host CPU -- a guest CPU spinning while it waits for another would hold the host CPU the other needs to finish -- so a guest has at most as many CPUs as hv on has turned the extension on for.

A guest's cores are its own (hv cores own, the default). Two CPUs on one core's two threads share its execution units, its caches and its buffers -- what every SMT side channel stands on, MDS, L1TF and port contention among them -- so a guest is given whole cores no other guest has a CPU on, its vCPUs or the task that serves its disks, and its vCPUs fill their threads: a vCPU a thread, as a cloud sells them, where a vCPU a core would leave a thread idle beside each. On a hybrid part all of a guest's vCPUs are of one kind of core where one kind has room for all of them -- the faster, or the kind of the CPU cpu= names -- since a guest's kernel takes its CPUs for equals, and an EX44 E-core runs a busy loop 16% slower than a P-core at one clock and 58% slower at their turbos; both kinds only where neither has room alone. The first where cpu= says, or on the free core with the most threads -- CPU 0's last, where the boot CPU's own work runs, and the higher threads of a core first, CPU 0 the last of all -- then the threads left on it, then on cores sharing its last-level cache, the faster kind first. Its disks' task goes on a spare thread of its own cores, then on a core no guest has, of the slower kind where its cache has one -- the task waits on the disk, and a fast core is a guest's; it then holds that core as well -- then beside a vCPU of its own. A guest that would need a core another has -- cpu= on one, or more CPUs than the free cores have threads -- is refused, saying so. The place and the hold on it are taken under one lock (modules/hypervisor/hv/src/cores.rs), so two guests started at once from two shells cannot both be given a core; an hv start guest holds its cores until hv stop -- parked too, for the restart that runs it there again -- and an hv boot guest until its run is over. hv cores says the rule and who holds which CPUs; hv list says where each guest's disks are served.

A guest's CPUs run at the performance preference while they are its. Where HWP picks a CPU's clock (Intel since Skylake, docs/kernel-parameters.md's hwp_epp=), every CPU a guest's vCPUs run on is asked for EPP 0 for as long as the guest runs (kcore::cpu::Performance, held by guest::run_cpus), and given back the boot's preference -- balance_performance unless told -- when the last who holds one lets go. Not the CPU its disks' task runs on: with that E-core at EPP 0 too, its task spinning there for the NVMe, every 4k request took 3.8 us longer from the command to its completion's interrupt on another CPU -- reads and writes alike, 33.5k IOPS at QD1 against 39.5k -- and without it they are back (rounds 15-17). A guest's CPUs idle between its ticks, and at the boot's preference HWP lowered their clock in every idle: on the EX44 the first microseconds after each wake ran five to ten times slower than on a busy core -- the TSC deadline's write that costs a busy core 1.3 us cost 10 there -- and cyclictest in the guest saw 66 us on average, where the same guest under KVM saw 31 and under nos at EPP 0 saw 6 (round 14, plans/vm-perf-todo.md).

What it costs: a guest's own CPUs share their core. On one core's two threads (13 and 12 on the AX41) two busy loops in a Debian guest took 14.7 s where one alone took 9.7; on two cores of one CCX (13 and 11) they took 9.7, and four loops on a guest of four CPUs (13, 11, 9 and 5) 10.0 -- the placement hv cores shared gives: the first on the least loaded core, of the faster kind where loads tie, each other on a core none of the guest's CPUs is on yet where there is one, sharing the first's last-level cache where it can, of the first's kind, the least loaded of those, whoever else is there; and its disks' task on a CPU none of its vCPUs is on, whose core has the fewest vCPUs, its own counted -- chosen by the other guests' load alone, it went to the guest's own second vCPU's CPU while others stood idle, and every completion took that vCPU out of its guest. That is for a machine whose guests are all one's own.

$ hv boot /bzImage mem=256 secs=60 cpus=2 initrd=/initrd cmdline=earlyprintk=serial,ttyS0,115200 console=ttyS0 no_timer_check
  --- ttyS0 ---
[    0.000000] Linux version 6.18.54 ...
[    0.000000] x2apic: enabled by BIOS, switching to x2apic ops
[    0.000000] MPTABLE: APIC at: 0xFEE00000
...
[    0.004000] APIC: Switched APIC routing to: cluster x2apic
...
[    0.388000] smp: Bringing up secondary CPUs ...
[    0.388000] smpboot: x86: Booting SMP configuration:
[    0.412000] smp: Brought up 1 node, 2 CPUs
...
nos-guest: init is up, / on ramfs, BusyBox v1.30.1
nos-guest: 2 cpus, online 0-1
  --- end ttyS0 ---
  stopped    by the host, its time up, after 60006 ms
  ...
  apic       30963 interrupts from the local APICs, 29663 of their timers; 1305 IPIs sent, 1300 taken
  cpus       2, 1 started by the guest (1 INITs, 1 start-up IPIs taken)
  cpu 0      60310 exits, 15477 apic irq, 679 ipi sent, 6593 hlt, slept 97% -- halted, on host cpu 3
  cpu 1      31923 exits, 15486 apic irq, 626 ipi sent, 6629 hlt, slept 97% -- halted, on host cpu 2
$ hv start /bzImage mem=256 cpus=2 initrd=/initrd cmdline=earlyprintk=serial,ttyS0,115200 console=ttyS0 no_timer_check
hv: vm 0 started on cpus 3,2 -- /bzImage, 256 MiB, 2 cpus, cmdline "earlyprintk=serial,ttyS0,115200 console=ttyS0 no_timer_check"
$ hv list
vm 0  running  cpus 3,2  256 MiB  0 s  exits 0  irq 0  hlt 0  kicks 0  /bzImage
$ hv exec 0 grep -e LOC -e RES -e CAL /proc/interrupts
LOC:        266        223   Local timer interrupts
RES:         11         15   Rescheduling interrupts
CAL:        125        144   Function call interrupts

(A Linux 6.18 built for the gate -- hv-linux-test.py --cpus 2 on the AX41, nested under KVM; its output trimmed. noapic goes on the command line by itself, below.)

A guest of one CPU is given exactly the machine it always was -- no APIC in CPUID, no MP table, nolapic on its default command line -- so a kernel that booted before boots the same. What a guest of more is given, and how its CPUs run, is below. hv::run holds the loop and the platform, hv::lapic the local APIC, hv::smp the mailboxes and doorbells, and hv::linux the MP table.

The machine it sees

A local APIC for every CPU, as an x2APIC unless told (hv::lapic). The x2APIC is its registers as MSRs 0x800-0x8FF, and an MSR access is an exit whose register and value the CPU hands over; the xAPIC is the same registers as a page of MMIO at 0xFEE00000, each access a nested fault whose instruction has to be decoded (MMIO). So the APIC comes out of reset with x2APIC mode already on, IA32_APIC_BASE saying EN and EXTD, as firmware leaves it on a machine with more than 255 CPUs, and a kernel that keeps it never touches the page -- or, with xapic, in xAPIC mode, as most PCs' firmware leaves it. A kernel may move between the modes as the architecture allows -- off and back, as nox2apic has Linux do -- and the APIC answers in the mode it is in. The nested table never maps the page: a guest that reaches for it in x2APIC mode, when it is none of the APIC's, is stopped and told why rather than answered wrongly. The boot CPU's APIC starts in virtual-wire mode, with the spurious-vector register enabled, LINT0 ExtINT and LINT1 NMI, as firmware hands it over. What the model has is the register file and what each register does to the others: the ID and the logical ID made from it (x2APIC cluster mode), the task and processor priorities, the in-service, request and trigger-mode registers, EOI -- a level-triggered interrupt's going back to the IO-APIC it came from (The IO-APIC) -- the error register, the local vector table, the interrupt command register, and the timer (below). A write of the spurious register that turns the APIC off masks every LVT entry, as the silicon does.

An MP table (hv::linux, spec 1.4) in the last kilobyte of low memory, at 0x9FC00, where the e820 map has ended RAM and where Linux looks: a processor entry for each CPU, the first marked the boot CPU; the PCI bus and an ISA bus; an IO-APIC entry, marked usable only for a guest given one; and the interrupt assignments -- the 8259's output on the IO-APIC's pin 0 and on LINT0 of the first CPU, each ISA IRQ but the cascade on the IO-APIC's pin of its own number but the timer's, which is on pin 2, each PCI function's INTA on the pin of its line, level-triggered and active low (the ISA entry of that line left out), and NMI to LINT1 of every CPU. Without the assignments Linux complains of a BIOS bug and makes up its own. The MP table is the least a kernel finds its CPUs by; one with ACPI finds them in the MADT (ACPI), which says the same, and takes the MP table only for what the MADT leaves out.

No IO-APIC, unless asked (The IO-APIC). The 8259 pair stays wired to the first CPU's LINT0 in virtual-wire mode, so every device interrupt -- the PIT's tick, the serial port's, the disks' and the NICs' -- is the first CPU's, and its task does the devices' work between its guest's turns, as it did for a guest of one CPU. noapic is added to the command line when it is not there already. Without it, x86-64 Linux looks for an IO-APIC whatever the table says -- it ignores the table's pic_mode -- and on the way setup_local_APIC masks LINT0 on the boot CPU, and the 8259 is cut off from the only CPU it reaches. With ioapic the machine has one, and the command line is left as it is.

CPUID. Leaf 1 says the local APIC is there, and the x2APIC, and gives each CPU its APIC ID in EBX[31:24]; leaf 6 says the timer keeps running in deep C-states (ARAT), which is true of one counted off the host's clock; and where the host's own leaf 0x15 gives its TSC's frequency -- an Intel host's does -- the guest's gives the timer's clock, a crystal of 1 GHz, and the TSC's ratio to it -- what a kernel reads when it is not told the TSC's rate on its command line (tsc_early_khz=, which the module gives a Linux guest and Linux then takes over the leaf). Passed through, the leaf would name the host's crystal, tens of MHz, and a kernel that took the timer's rate from it would have its timer fire tens of times too soon; where the host has no frequency to give, the leaf is blank and the kernel measures. The topology leaves are the guest's own (Where its CPUs sit), and leaf 1 offers the timer's TSC-deadline mode (Time). Of leaf 0x80000007 only the invariant TSC is left: its RAS bits (SUCCOR among them) sent Linux's machine-check code to set up AMD's deferred-error interrupt through the APIC's extended LVT -- MSR 0x852, a register this APIC has not got -- and the #GP came back as an "unchecked MSR access" and two firmware bugs in its log. A guest on an AMD host reads DE_CFG's LFENCE-serializing bit set, as KVM answers it, and HWCR's TscFreqSel set, as every AMD CPU since family 10h has it; read as zero, that one was a "TSC doesn't count with P0 frequency!" firmware bug of its own.

What it needs of the guest's kernel: Linux 6.6 or later. Before 6.6, a kernel given an MP table and an x2APIC already on reads its APIC ID through the xAPIC's page before it switches to x2APIC operations (register_lapic_address -> read_apic_id -> native_apic_mem_read), and faults on the page the guest does not have -- a 5.15 kernel oopses there before its first line of SMP output. And CONFIG_SMP, CONFIG_X86_X2APIC (which needs CONFIG_IRQ_REMAP or CONFIG_HYPERVISOR_GUEST) and CONFIG_X86_MPPARSE. A distribution's kernel has all of them: Alpine's virt 6.18 brings up two CPUs as it ships. An older kernel still boots on one CPU.

Where its CPUs sit

A guest's CPUID tells it where its CPUs are (hv::place::Shape), and tells it what is so. They are one package, each CPU's APIC ID its number, of cores of one thread or two: two where its CPUs 2k and 2k+1 are each one host core's two threads and no other two of them share a core -- as hv cores own, the default, places them, a guest's vCPUs filling the threads of the cores it is given -- and one otherwise, hv cores shared's CPUs on cores apart among them, and the odd guest whose CPUs the numbering cannot pair (a core with one thread to give before the others). Its last-level cache is the package's where all its CPUs are on one host cache, each core's own where not. The placement says so as it is made (Placement::shape), the guest's spec keeps it for every boot, and the leaves give it: leaf 1's count of the package's APIC IDs, with HTT where that is more than one; leaf 4's sharing and core counts, the last level's sharing the package's; the x2APIC topology leaf, 0xB, its SMT level and its core level, each with the CPU's x2APIC ID; and on AMD the package's CPUs and the APIC ID's width in 0x80000008, and -- where the host has TOPOEXT -- 0x8000001D's sharing and 0x8000001E's core and threads. Nothing of the host's topology reaches the guest: its APIC IDs and core counts were once another machine's, and a guest took the host CPU's APIC ID for its own.

It matters twice. A guest's kernel schedules by it: its wakeups look for an idle CPU among those that share the waker's cache, which with each CPU a package of its own, as each was before, was no CPU but its own; and it spreads work over cores before it doubles up on a core's threads. And the side channels between a core's two threads -- MDS, L1TF, port contention -- are between two of its own CPUs, which its kernel can guard its processes against only knowing (core scheduling, STIBP, nosmt): told each CPU was a package, it believed no two of its processes shared a core while two did. Linux 6.18 reads leaf 0xB on AMD as on Intel; an older kernel reads it on AMD only with TOPOEXT, and on an AMD host without TOPOEXT -- QEMU's max under TCG is one -- sees one package of cores, and no threads.

KVM's paravirtual interface, as far as it is backed

The hypervisor's CPUID range answers as KVM's does: its signature, KVMKVMKVM, in leaf 0x40000000, and in 0x40000001 the features of its paravirtual interface -- what a Linux built with KVM_GUEST looks for, and takes no more of than the bits it is given. Two are offered. NOP_IO_DELAY, a fact: an out to port 0x80 delays nothing here and is an exit, and a kernel told so stops making them. And for a guest with APICs, PV EOI: the guest names a word in its memory (MSR_KVM_PV_EOI_EN, aligned to 4 bytes, or a #GP), and where the end of the interrupt in service need not exit -- the highest in service edge-triggered, since a level's end the IO-APIC has to hear of, and nothing requested, which an EOI that does not exit would leave waiting unseen -- the run loop sets the word's bit before the entry (pv_eoi_arm). The guest's EOI then clears the bit and goes on, no exit; at the next exit, before anything else is looked at, the run loop finds the bit clear and does the EOI itself -- or finds it still set, and clears it, so that an EOI the guest makes from there exits as usual (pv_eoi_sync). An EOI written to the register at that exit, of the vector beneath, comes after the one done for the word, as it came after in the guest. Under VT-x with APIC virtualization the CPU takes the EOIs itself and the word is never set. Elsewhere each EOI was an exit of its own, beside the one that brought the interrupt and, in TSC-deadline mode, the next deadline's write; hv boot's report counts the ones saved (pv eoi). INIT turns PV EOI off, as KVM's reset does.

Not offered, and why: kvmclock, the TSC being invariant and the host's (tsc_khz= tells the guest its rate); steal time, and what stands on it -- PV TLB flushes and PV sched yield -- a guest's CPUs having cores of their own (hv cores own); PV unhalt, for the same reason, so a guest's spinlocks stay native (PV spinlocks disabled, no host support); and async page faults, a guest's memory never being paged out. No hypercall is offered either, and each is answered -KVM_ENOSYS in RAX, as KVM answers one it does not know: a driver that probes, as ptp_kvm does for its clock pairing, takes that for not there -- where the old answer, RAX left as it was, read as a positive error. A kernel without KVM_GUEST finds a signature it does not know, and runs as before.

Hyper-V for a firmware guest

firmware hyperv, or hyperv = true beside firmware = true in vm.toml, replaces KVM's paravirtual interface with Hv#1: CPUID leaves 0x40000000-0x40000005, GUEST_OS_ID, HYPERCALL and VP_INDEX, and a read-execute hypercall-page overlay. A call before a guest OS is registered, and an unknown call, is refused rather than answered as success; the unknown call's status is HV_STATUS_INVALID_HYPERCALL_CODE (2). Crash MSRs P0-P4 and CrashNotify carry a Windows bugcheck's code and four arguments into the VM's stop report and /logs/hv.log.

The virtual APIC interface supplies Hyper-V's EOI, ICR and TPR MSRs in either xAPIC or x2APIC mode, and the per-VP assist page MSR. Its EOI-assist word is set before a host-injected edge interrupt when no lower-priority request is waiting; a guest clearing it instead of writing EOI has the EOI completed at the next exit. While an AutoEOI SINT is configured it disables APICv and the host ends its vector as it is injected. Hyper-V's synthetic ICR uses the world switch's remote fixed-IPI fast path as the native x2APIC ICR does. CPUID recommends remote TLB flushes and synthetic cluster IPIs. Without APICv it also recommends the APIC MSRs and VP-assist EOI. With APICv those are not recommended and AutoEOI is deprecated, the same contract as QEMU's hv-avic. If a guest configures AutoEOI anyway, APICv is disabled for as long as that configuration needs host injection. Hyper-V starts with x2APIC enabled; the MADT describes the processors and their NMI with ACPI's 16-byte type-9 and 12-byte type-10 entries respectively.

HvFlushVirtualAddressSpace (0x0002), HvFlushVirtualAddressList (0x0003) and HvCallSendSyntheticClusterIpi (0x000b) are implemented with the simple 64-bit processor masks, in memory and fast register forms. CPUID advertises XMM fast hypercall input: a flush takes its processor mask from XMM0's low half, and a list takes its GVA ranges from the following halves, up to eleven in the six-register input. A list flush conservatively flushes the whole TLB rather than keeping each GVA range; the non-global-only flag is accepted on that path too, for compatibility with KVM's Windows path. A remote target gets an atomic flush request and a doorbell, and marks its backend before the next entry; the calling VPID/ASID is marked directly. The sparse Ex forms are not advertised. Vmstate version 5 adds each VP's assist MSR and reads version 4 with it disabled.

TIME_REF_COUNT shares the reference TSC page: a second read-only overlay, with the TLFS sequence odd while a value is being published and even after, TSC value and scale/offset, and the TSC and local APIC frequencies. Each vCPU has SynIC SCONTROL/SVERSION, SIEFP/SIMP, EOM, SIRBP and SINT0-15, plus four synthetic timers. A timer can request a direct local-APIC vector or a 40-byte HVMSG_TIMER_EXPIRED message (type 0x80000010, 24-byte payload) on its SINT; one-shot, periodic and auto-enable modes use the same host Kick deadline as the other timers, so an edge also wakes a halted vCPU. The hyperv and policy fuzz targets cover this contract, and the Windows boot exercises its reference clock and message-mode timer.

Windows Server 2022 Standard Core then reaches SAC> on the EX44 in about 1.65 seconds; its CMD channel accepts a login, viostor runs the system disk, and NetKVM uses DHCP. shutdown /s /t 0 ends in Stop::PowerOff: Windows reaches CloudHv's UEFI ResetSystem(EfiResetShutdown), which writes 0x34 to its fixed sleep-control port 0x600. A running Windows VM saved with hv save and restored on the EX44 resumes its CMD channel and network, and then shuts down normally. This boot also exercised a VT-x fix worth keeping in the dump: requesting an IRQ window now clears a stale TPR threshold first, since the CPU refuses VM-entry when that threshold exceeds VTPR's class. Both kinds of failed entry preserve the VMCS controls and related fields in the stopped vCPU's report (see VT-x).

The W2 measurements on the same idle Windows guest, over 2.66-second trace windows, reduced exits from 1,657 to 647 (61%): all 1,163 xAPIC nested faults were gone, Hyper-V EOI writes fell from 479 to one, and 195 synthetic ICR writes remained. Measured separately, VP-assist removed 489 of 497 EOI exits in an early-boot window, and answering the synthetic ICR in the world switch reduced its median host cost from 2.2 us to 715 ns. A later 12-second A/B on the same image compared the newest 4,096 exits: 187 memory-form TLB calls before XMM input and 148 fast calls after it. Median time to the next exit on that vCPU fell from 2,091 to 1,992 ns, and the mean from 2,316 to 2,022 ns. This is the hypercall path's cost, not a whole-VM benchmark. The current Windows image stays in xAPIC mode and uses these Hyper-V paths; hardware virtualization of the xAPIC page, AVIC and a same-image KVM benchmark remain separate measurements.

Starting the others

The first CPU starts at the kernel's 64-bit entry, as a guest of one CPU does. The others start the way a PC's do: waiting for a start-up IPI. INIT puts a CPU back in that state -- its registers the reset state's, anything it was about to be injected dropped, its local APIC reset -- and a start-up IPI starts one that waits, in real mode at the vector times 4 KiB, CS the vector shifted left by eight. A second start-up IPI finds the CPU running and is ignored, as the silicon ignores it: Linux sends two. From there Linux's trampoline climbs to long mode itself, through protected mode, PAE and paging, and joins the kernel.

  • Under AMD-V real mode needs nothing new: with nested paging the CPU translates the guest's physical addresses through the nested table whatever the guest's own paging is doing. A CPU that is started is given a fresh ASID, so nothing translated for it before the reset is used.
  • Under VT-x real mode needs unrestricted guest, the secondary control that lets a guest run with paging, or protection, off: a CPU without it refuses a guest of more than one CPU (NoUnrestrictedGuest) rather than starts one whose other CPUs could never start. And the climb is a guest changing CR0.PE and CR0.PG, which VMX will not let a guest do behind the host's back where the "IA-32e mode guest" entry control has to agree with EFER.LMA. So PE and PG are in CR0's guest/host mask with NE, a mov to CR0 or an lmsw that would change one of them exits (Exit::Cr0Write), and the policy does what the CPU would: the checks that make it a #GP -- bits 63:32 set, NW without CD, PG without PE, paging on in long mode without PAE, paging off from 64-bit code or with PCIDs on -- LMA set or cleared as paging goes on or off with LME set, the entry control made to follow at the next entry, and what the TLB holds under the guest's VPID dropped, as the mov would drop it. That also lifts what the VMX backend could not do before: a guest can leave long mode, the way kexec does -- which nothing here has run yet.

QEMU's TCG before 9.2 does not put the accesses of a guest with paging off through the nested table at all -- it takes a guest physical address for a host one -- so a CPU started in real mode there runs out of nos's own memory and corrupts it. hv-test.py and hv-linux-test.py --cpus refuse an older QEMU under TCG; KVM, and a CPU's own extension, have always done it right.

What the CPUs share, and how they reach each other

Each CPU's own state -- its registers, its local APIC -- is its task's alone, and may be inside the CPU under a VMCB or a VMCS at any moment. What the CPUs share is guarded by what it is:

  • Memory is copied into and out of by every CPU at once, as the guest's own CPUs write it: GuestMemory's accessors take &self, and each copy goes through the calling CPU's own slot with interrupts off (kcore::frame), with no reference into a guest page anywhere. The nested table is one for all of a guest's CPUs, and grows under a lock -- the read-only page answering a read of a device the platform does not have (map_absent) is mapped once, whichever CPUs fault on it together.
  • The devices are one platform under one lock, taken for each port access and for each round of the first CPU's device work.
  • What one CPU sends another -- a fixed interrupt, an NMI, an INIT, a start-up IPI -- goes into the target's mailbox (hv::smp), lock-free: a bitmap of the vectors sent and a word each for an NMI, an INIT and a start-up IPI, taken whole by the target before it next enters. The sender then rings the target's doorbell, which wakes its task if it sleeps and, if it is in its guest, interrupts the host CPU it runs on so that it leaves (the same Kick the switch uses for a frame). The vCPU marks itself on its way in before its last look at the mailbox, and a sender posts before it rings, so a message is either found by that look or rings a vCPU that is in its guest or about to be.

The interrupt command register sends to a physical or a logical destination -- a cluster and a bitmap of its CPUs, x2APIC's only logical mode -- or by shorthand, to itself, to all, or to all but itself; fixed and lowest-priority interrupts (the latter to the first CPU it names), NMIs, INIT and start-up IPIs. The first CPU takes interrupts from two places, the 8259 through LINT0 and its own APIC, and when both have one they take turns, so that neither can keep the other out. The APIC's task priority is CR8's, under AMD-V through the VMCB's V_TPR, and under VT-x the virtual APIC's VTPR (below) -- or, on a CPU without one, through the CR8 exits that keep the host's own CR8 out of the guest's reach.

An NMI one CPU sends another needs NMI blocking to be the guest's own: set as the NMI is injected, ended by the guest's IRET, and the next one held until then. Under VT-x that is virtual NMIs, with the NMI-window exit to inject a held one the moment the guest's IRET unblocks it; under AMD-V it is the IRET intercept, whose exit comes before the IRET has run, so blocking ends once the guest's RIP has moved past it -- what KVM does.

Halting. A CPU that halts with interrupts on is not entered again until an interrupt it can take is pending, its task asleep meanwhile, as for one CPU. A CPU halted with interrupts off, or waiting for a start-up IPI, can be woken only by another CPU. It sets its bit in a mask of such CPUs as it goes to wait -- and looks at its mailbox once more after, for mail that came meanwhile -- and clears the bit as it wakes, before it takes anything. So a set bit is a CPU that has sent nothing since it last found its mailbox empty, and a CPU whose own bit makes the mask every CPU's, and that then finds every mailbox empty and the mask still whole, knows nobody is left awake to send anybody anything: the guest has stopped -- halted in its report, as a guest of one CPU that runs cli; hlt is. The order is the point: with the bit cleared by whoever sent the mail instead, a CPU that took its mail before the sender got there would run with its bit set, and the last of the others to halt could stop a guest that is running.

Interrupts the CPU delivers itself: VT-x's APIC virtualization

Where the CPU has the TPR shadow, x2APIC virtualization and virtual-interrupt delivery -- hv info's APIC virtualization; the EX44's i5-13500 has them, and KVM hands them to a nested hypervisor -- each of a guest's CPUs under VT-x has a virtual APIC: a page of its own (hvarch::x86::vmx::Guest) whose task priority, request and in-service registers (VTPR, VIRR, VISR) the CPU itself works. CR8 is VTPR, for every guest, and no mov of it exits.

By default where the CPU has posted interrupts too -- hv info says -- and for a guest that asks for it (apicv on hv boot or hv start; noapicv turns it off), while the guest's local APIC is in x2APIC mode and on, the run loop turns virtual-interrupt delivery on for each entry (hv::vmx::Vcpu::load_apic): where the APIC stands -- what it has requested and in service, and its task priority -- goes into the page, and the CPU, not the run loop, delivers the highest request the priorities let through as soon as the guest can take it, and performs the guest's EOIs, its writes of the task priority and its self-IPIs on the page, none of them an exit. At the exit the run loop takes the page back into the APIC before anything looks at it (Lapic::from_cpu), so the rest of the loop -- a halted CPU's wake-up, a read of IRR, an IPI's acceptance -- sees what the CPU did. The MSR bitmap lets the guest's writes of those three registers through only while this is on; every read of an x2APIC register still exits, since without APIC-register virtualization a read let through would be of the CPU's own APIC. An EOI of a level-triggered vector -- an IO-APIC's, which it has to hear of to send again while its line is up -- the CPU still stops the guest after (the EOI-exit bitmap, from the APIC's trigger-mode register: Exit::Eoi). In xAPIC mode, with the APIC off or software-disabled, on a CPU without APIC virtualization, under AMD-V (whose AVIC is not used) and for a guest that turned it off, the run loop injects every interrupt as before.

Posted interrupts. What comes from outside the CPU -- another CPU's IPI, a device's MSI -- each guest CPU takes posted: its fixed, edge-triggered interrupts go into a descriptor of its own (hvarch::x86::vmx::PostedInterrupts, 64 bytes the VMCS names), and if it is in its guest, or on its way in, the sender sends the CPU it runs on the notification vector, 0xFC (kcore::cpu::notify, Kick::notify): the CPU takes what was posted into VIRR there and delivers it, no exit. A CPU out of its guest is rung as before, and folds what was posted into its APIC before it next looks at it (take_posted); one that left its guest just then takes the notification as a host interrupt that only ends itself. Level-triggered interrupts, NMIs, INITs and start-up IPIs still go through the mailbox and a kick. Posted interrupts need every external interrupt's exit to acknowledge the interrupt -- the host's, delivered to nothing yet -- so hvarch hands each to the host by hand, by an int of its vector through the host's own IDT, once the CPU's entries are let go of, since its handler may switch tasks (deliver_host_interrupt).

Why the default waits for posted interrupts. Without them an interrupt for a CPU in its guest has to kick it out to be handed over, and with no EOI exit for the run loop to find the next one's mail at, more of them do: a kick, an IPI and an exit, is dearer than the EOI's exit it replaced. On the EX44, two guests of two CPUs sending 500 MB of TCP to each other through the switch, 13 runs each way: without posted interrupts the guests exited 25-50% less but took 5.88 s on average (4.3-6.8 s) against 5.70 s (5.5-5.8 s) -- 4.3 s when the sending guest took its NIC's interrupts on its first CPU, whose task does the devices' work and posts the MSI to itself, and 5.9-6.8 s when it took them on its second, its host-interrupt exits going from 132,000 to 179,000. With posted interrupts, 10 runs each way, taken in turns: 3.7-5.9 s (4.85 on average) against 5.6-5.8 s (5.72), faster in 9 of the 10, the two guests exiting 0.67-1.58 million times against 2.3-2.6 million.

Halt polling -- a halted CPU watching for an interrupt a while before its task sleeps -- is not a lever on that load; what looked like one was interrupt moderation, by accident. Measured apart, posted interrupts on, two runs each: a 200 us watch of a CPU's mailbox and its doorbell took the transfer from 3.9-5.1 s to 6.3-6.5 s, a 50 us one to 4.7-6.0 s. A watch hands each frame's interrupt over at once, so the receiving guest takes one frame an interrupt (1.00, against 1.4-2.0 with no watch) and acknowledges every one or two, 265,000-277,000 ACKs against 111,000-151,000, and the sender's TCP, answered that often, sends more and smaller frames -- each one more exit on both sides. The 200 us watch that had taken the transfer from 5.7 s to 3.9 s watched the mailbox alone: on the receiving guest's first CPU, halted, it left the doorbell the switch rings for the devices' work unanswered until it ran out, so the frames for that guest waited up to 200 us and went into its ring together -- 18.9 an interrupt, 41,000 ACKs, 3.9 s; where that CPU was not halted nothing waited, 1.8 an interrupt and 4.9 s. Adaptive watches came to 5-7 s for the same reason: they shrank the first CPU's watch to nothing, and answered the rest at once. Moderation done on purpose -- an interrupt held a bounded while for the frames behind it -- needs a host timer finer than the tick, which there is now (the local timer): the same wait slept rather than spun, which the 100 Hz tick made 5-10 ms, held 260-290 frames an interrupt and took 12.5-14.6 s, the TCP window run dry. It is in the tree now, at 100 us (A network); halt polling is not.

The apicv built-in guest asks for it, and holds both ways to one result: self-IPIs held by CR8 and taken by priority, one nested, IRR and ISR read back, and three levels from the IO-APIC ended by the x2APIC's EOI. The posted guest's second CPU sends its first a thousand IPIs while it spins: taken in its guest, each notified, where the CPU has posted interrupts -- on the EX44 the first CPU left its guest 9 times -- and handed over by the host elsewhere. The hv fuzzer's platform target models the CPU's side -- delivery by priority, the EOI, task priority and self-IPI writes it performs, the EOI exit, a posted interrupt taken in the guest and the notification's exit where it is not -- and holds the run loop to losing nothing the CPU left in the page between an exit and the next entry, to taking what was posted before every entry and to never waiting with it untaken.

Time

A timer's edge, on time. A guest's timers -- the PIT's channel 0 and each CPU's local APIC timer -- have their next edge armed on the host CPU the vCPU runs on: as its task sleeps, halted, until the edge (Event::wait_for, whose deadline arms the CPU's one-shot timer -- the local timer), and before each entry into the guest (kcore::cpu::timer_at), so that a guest computing with no exit is taken out of it at the edge, by a host interrupt, and handed its own then. Both used to wait for the host's next tick, at 100 Hz: on the EX44 a halted guest's usleep 1000 took 10 ms, a hundred of them 0.99 s, and a CPU computing with no exit was given its ticks in bursts of up to ten. Now a hundred take 0.16 s -- halted, and with a CPU-bound loop running in the guest -- on one CPU, whose timer is the PIT, and on two, each with its APIC timer delivered by the CPU itself; twenty of usleep 100000 2.01 s, where they took 2.19. The owed periods below keep the count right whatever the host does, and PAUSE exits keep a spinning CPU prompt. hv-fuzz's stand-in CPU leaves its guest at the deadline it was armed for, as a host interrupt.

Each local APIC has its timer: one-shot and periodic, counting down at a bus clock of 1 GHz -- KVM's, and one that makes a count nanoseconds -- with the divide configuration a guest writes; written while a count runs, the count goes on from where it is at the new rate, its interrupt with it, as KVM restarts its timer for. A periodic timer that fell behind is owed its periods, handed over one at a time as the guest takes each, a second's worth at most, as the PIT's channel 0 is -- but one whose entry is masked, or whose vector the APIC refuses, owes none: every period gone by is skipped, as an APIC loses a masked one, and unmasked it does not hand over the periods it missed back to back. And TSC-deadline mode, which leaf 1 offers with the APIC wherever the host knows its TSC's rate: a write of IA32_TSC_DEADLINE (MSR 0x6E0) arms the timer to run out when the TSC reaches it -- the guest's TSC is the host's, so the deadline is turned into the host's time as it is written, at the rate the kernel measured -- 0 disarms it, it reads back until it runs out and 0 after, a count written meanwhile is ignored and the current count reads 0, and the mode's entry or exit disarms the timer, as the SDM has it (11.5.4.1); in the other modes the MSR reads 0 and takes nothing. Linux takes it over the one-shot count (lapic-deadline): a deadline is one write, and needs the timer's rate measured against nothing.

A kernel measures the timer against the PIT before it trusts it (calibrate_APIC_clock), and while it measures it spins, cpu_relax() -- PAUSE -- round a loop that watches the PIT's ticks go by. A spinning guest made no exit, so it left its guest only at the host's own tick, every 10 ms, and took the PIT's ticks owed since in a burst there: Linux counted ten ticks' worth of APIC timer as one tick, reported a bus of 10005 MHz where there is one of 1000, then saw its APIC timer run ten times too slow and refused it (APIC timer disabled due to verification failure, jiffies delta = 1001). So PAUSE exits now -- under VT-x at a loop of them in the guest's kernel that has spun 65536 TSC ticks (pause-loop exiting, 26 us at the EX44's 2.5 GHz, each PAUSE within 1024 ticks of the last), and at every one where the CPU has no pause-loop exiting, as a nested KVM may not pass it on; under AMD-V every 128th where the CPU has a pause filter and every one where it has not -- and each exit goes round the loop that hands a tick over as it falls due. An exit at every PAUSE cost a spinning CPU an exit's 1.8 us for each PAUSE of tens of cycles. The gap is wider than KVM's 128 ticks: a loop's turn on Skylake and later, whose PAUSE alone is some 140 cycles of a core that may run below its TSC's clock, is longer than that, and a gap too short finds no loop at all. Measured on the AX41, the guest finds a bus of 999 MHz and keeps its timer (jiffies delta = 100, jiffies result ok), as it does on an Intel host (an i5-13500, nested under KVM). A CPU spinning on a lock another of the guest's CPUs holds comes out the same way, and is handed its tick when it falls due rather than at the host's next one.

Under TCG a guest refused it once more before it was told its TSC's rate (below). The check allows two ticks of 100, and a guest there is slow enough that the PIT's ticks owed from the lines it printed with interrupts off just before -- through a UART that is itself exits -- were still being handed over when the check started: it counted 106. It then kept its PIT tick on the first CPU and broadcast it to the others by IPI, which works, and costs an IPI a tick per CPU. Told the rate, it has kept its timer in both runs since.

The TSC's rate, handed over. A kernel on an AMD host measures its TSC against the PIT, every read an exit, and gives up if one read takes ten times the fastest -- which a vCPU sharing its host CPU with the host's own work (sshd, the network stack; cpu 0's, on the AX41) did one boot in two, before SMP and after, and ran on jiffies. So every Linux guest's command line gets tsc_early_khz= with the host's TSC rate, which is the guest's: nothing offsets or scales the TSC a guest reads. Linux takes it as authoritative from 5.7 on; hv leaves one the command line gives alone.

Two CPUs' TSCs agree. Placed on two CCXs of the AX41 (0 and 13), Debian measured its CPUs' TSCs 2052 cycles apart -- "turning off TSC clock" -- where Ubuntu, on the same CPUs, found them in step. Linux's check reads the TSC with lfence; rdtsc after taking a lock the other CPU held, and trusts the LFENCE to hold the RDTSC back until the load before it has completed. On an AMD CPU of families 10h to 17h LFENCE does that only with DE_CFG bit 1 set, which Linux sets on every CPU and nos did not, and the firmware had not: the RDTSC ran ahead of a cache line on its way from the other CCX, and the time that took looked like a warp. nos sets the bit on every CPU now, the BSP's boot log saying when the firmware left it clear (hal::setup_serializing_lfence); a guest of four CPUs across both CCXs (13, 11, 9 and 5) keeps its TSC.

Device interrupts, by MSI-X

A guest with local APICs has its disks and NICs interrupt it by MSI-X, as a PCI device on a real machine does, and not through the 8259. Each virtio function has an MSI-X capability (devices/pci.rs) and a memory BAR 1 of one page: the vector table at its start, the pending bits after it. That page is guest memory -- a region of its own, at 0xFE000000 and a page a PCI slot, in the MMIO window and not in the e820 map -- so a guest writes its table with plain movs and makes no exit doing it, and no instruction has to be decoded. A guest's RAM below 4 GiB ends below these pages (linux::LOW_RAM_END), the rest of it from 4 GiB (How much of it, and where): more below them would run over them, and over the IO-APIC's and the local APIC's, and the guest would read and write its devices' registers as memory, none of them hearing of it -- an APIC in xAPIC mode that is not there, and nothing to say so. The device reads an entry when it has an interrupt to send: the message's address and data (lapic::msi), a fixed or lowest-priority vector to an x2APIC ID or, in cluster mode, to the first cluster's CPUs, the eight an 8-bit field can name -- which is where Linux puts them without interrupt remapping. It goes as an IPI would: into the APIC of the CPU doing the device's work, or another CPU's mailbox, with a ring. An entry masked, or the whole function, sets its pending bit and is sent once it is unmasked. With MSI-X on, virtio's legacy header grows the two vector registers, and the device's configuration moves from 0x14 to 0x18 (devices/virtio.rs). The BAR stays where "firmware" put it: sizing it reads back its size, and another address written reads back the old one.

What that changes is the cost of an interrupt. Through the 8259 each costs the guest six exits -- a mask, two EOIs, an unmask, the interrupt status read and a dummy one -- and at a gigabit a receive interrupt came every other frame; by MSI-X it costs one, the EOI's MSR write. And the guest places each vector itself: Debian put its NIC's receive queue on its first CPU and its transmit queue and its disk on its second. On the AX41 a Debian of two CPUs fetched a gigabyte three times at 117 MB/s -- what TCP carries over gigabit Ethernet -- with no frame dropped, its first vCPU's host CPU 88% busy and its second's 21%, where through the 8259 the first was 96.5% busy, the second idle, the fetch 113 MB/s and a few hundred frames dropped a gigabyte. A guest of one CPU has no APIC, and keeps the 8259 and that ceiling: 111 MB/s and 586 frames dropped.

What it does not do yet

  • The first CPU's task does most of the devices' work. Between its guest's turns it serves a NIC's frames and the chipset's devices, with or without an IO-APIC -- a disk's own task hands over its completions and posts their MSI-X itself (LinuxGuest::serve_disk); only the interrupts that follow go where the guest steers them -- through MSI-X, and with ioapic the PIT's and the serial port's too. Without one, those two reach the first CPU only.
  • Neither an MP table nor ACPI, one CPU. A kernel built with neither X86_MPPARSE nor ACPI finds one CPU.

Gates

Both run under AMD-V -- QEMU's TCG, and nested KVM on the AX41 -- and under VT-x, nested KVM on an i5-13500, where the second CPU's climb from real mode is the two CR0 writes the policy emulates.

  • tests/hv-test.py runs the built-in smp guest on the first and the last CPU: two CPUs, the second started by INIT and a start-up IPI into real mode, climbing to long mode and sending the first an IPI, whose one-shot APIC timer then interrupts it. A run with the start-up IPI ignored, and one with the timer never firing, both fail it.
  • tests/hv-linux-test.py --cpus N boots a real Linux with N CPUs -- smp: Brought up 1 node, N CPUs, and the report's N-1 started by the guest -- then runs the VM phase with them: every CPU online, each taking its own local timer's interrupts, rescheduling IPIs between them, and hv list naming the host CPU of each; the guest's timer the local APIC's in TSC-deadline mode (lapic-deadline, with tsc_deadline_timer among its CPU's flags), its CPUs one package -- and with --cpus 2, placed on one core's two threads, that core of two threads sharing one last-level cache, as its sysfs says. --disk, --disk --nvme-root, --net and --attach take --cpus too. The guest kernel needs what is above, plus POSIX timers for BusyBox's ping, which paces itself with alarm() (a tinyconfig leaves them out).

MMIO

A device whose registers are memory -- the xAPIC's page and the IO-APIC's first, and next the HPET's, a PCIe function's BARs -- is reached by instructions that fault on a page the nested table does not map, and the exit says where and whether it wrote: not the register, not the size, not the value, not the instruction's length. So a device like that is emulated by decoding the instruction, which is three pieces here, none with any unsafe:

  • The walk (hv::walk): the guest's RIP to a guest physical address by its own paging -- long mode's four or five levels and their 1 GiB and 2 MiB pages, or none -- and the instruction's up to fifteen bytes read from guest RAM a page at a time: an instruction may cross into a page mapped elsewhere, or not at all. The permissions are not checked: the CPU fetched the instruction already, and faulted on its data.
  • The decoder (hv::insn): what Linux's MMIO accessors are. readl, writel and their kind are movs in inline assembly -- a register loaded from memory or stored to it, an immediate stored, and movzx/movsx for the narrow reads -- the set Linux itself decodes when it emulates MMIO for a confidential guest (insn_decode_mmio). The memory operand may take any form a compiler picks (a fixmap address is an absolute displacement through a SIB byte), so every ModRM and SIB form is stepped over; the address is not worked out, the fault having given it. Anything else -- another opcode, a string move, a lock, 16-bit addressing -- is refused. It was checked against what clang assembles for 1054 instructions (every opcode over sixteen addressing forms, the registers REX and the high bytes name, immediates of each size), each also cut short at every length -- refused, never mistaken for a shorter instruction -- and against two million random byte strings: no panic, and no length past what was there.
  • The emulator (hv::mmio), in two steps, the device being the caller's. begin fetches and decodes, and checks the instruction against the fault -- that the fault was an instruction's at all, and not an interrupt's delivery pushing to a stack or reading an IDT on the page; a load for a read and a store for a write, which an instruction another of the guest's CPUs changed under the fault need not be; the access inside the page; no load into RSP, which VT-x writes back only on its full sync -- and hands back the access and a store's value. The caller reads or writes its device. finish puts a load's value in its register -- zero- or sign-extended, a 32-bit destination clearing the top half as the CPU's does -- and steps RIP past. Nothing in the guest changes before finish, and an access that cannot be performed stops the guest with its bytes: an access of guest physical 0x... at rip 0x... not performed -- ...; its bytes ....

hv run's mmio guest checks the three together on each backend: a device of 32 bytes of registers in the MMIO window, stored to by an immediate of each size, a 64-bit register, REX's and BH, and loaded from by mov into 32-, 64- and 16-bit registers and AH, movzx and movsx -- fourteen accesses, each value checked where it went. What an access costs, beside an exit the CPU decodes itself, is under What an exit costs: hv bench mmio.

The xAPIC

The first device on it is the local APIC's page. Its APIC comes out of reset in x2APIC mode, and a kernel that keeps it there -- Linux does -- never touches the page; one that leaves the mode, or whose firmware left the APIC in xAPIC mode, now reaches the same register file through the page (Lapic::mmio_read, mmio_write), where the two modes differ as the architecture has them differ: the ID in bits 31:24, a writable logical ID and destination format -- flat or cluster, which the other CPUs' IPIs and a device's MSIs are matched against, each CPU publishing its own -- the ICR in two halves, and what x2APIC mode faults xAPIC mode ignoring. The page stays where firmware put it: a write of IA32_APIC_BASE moving it is a #GP, since a page that is a device to one CPU and RAM to another is no machine. Two guests use it:

$ hv boot /bzImage cpus=2 xapic initrd=/initrd cmdline=console=ttyS0 acpi=off
  --- ttyS0 ---
...
[    0.622101] smp: Brought up 1 node, 2 CPUs
...
  apic       59776 interrupts from the local APICs, 59486 of their timers; 294 IPIs sent, 290 taken; 0 MSIs
  mmio       60828 accesses performed for the guest, its instructions decoded: the xAPIC page's

Linux 6.1 -- Debian 12's -- booted without ACPI, xapic having its APICs come out of reset in xAPIC mode, brings up both its CPUs with every EOI, IPI and timer write through the page. Without xapic it cannot: its MP table path reads the page before it looks at the mode firmware left, and with x2APIC on it had not mapped the page and page-faulted in its own register_lapic_address. With its ACPI it needs neither -- the MADT has it choose the x2APIC driver before anything reads the page -- so a 6.1 of a distribution boots SMP here as it is. And a Linux 6.18 told nox2apic, which takes its APIC out of x2APIC mode itself ("x2apic disabled"), does the same through the page.

The IO-APIC

The second device on it is the IO-APIC (hv::devices::ioapic), for a guest of more than one CPU given ioapic: 24 pins at 0xFEC00000, version 0x20, reached through the page's select register and window, and its EOI register. Each pin's redirection entry says what an interrupt on it is -- a vector, a delivery mode, a destination, physical or logical, masked or not, edge- or level-triggered -- and a device drives its pin as it drives the 8259's line: the PIT's tick on pin 2, the serial port's interrupt on pin 4, the SCI on pin 9, each PCI function's INTx on the pin of its line, 10 or 11; the 8259's own output is pin 0's, as on a PC, and its interrupts go to the first CPU as they always did, while its lines are unmasked there. The tables say so: the MP table marks the IO-APIC usable and routes each PCI function's INTA, level and active low, and the MADT lists it with the timer's and the SCI's overrides (ACPI); noapic is not added.

An edge-triggered pin sends as it rises; a level-triggered one as it rises and again while its line is up once its last interrupt has been ended -- its remote IRR set when a local APIC has taken it, as the 82093AA sets it, and cleared by the EOI of that APIC, which the APIC broadcasts for a vector it took as a level (its trigger-mode register), or by a write of the IO-APIC's EOI register; a line still up then sends again. A level no APIC took -- its destination no CPU's, or the APIC software-disabled, which refuses it, there or as the CPU it was mailed to takes its mail -- is in service nowhere and no EOI will come: its remote IRR stays clear, and it is sent again when a CPU's APIC is turned on or addressed otherwise, as the chip holds such a message and tries it again. Set as the message was made, the pin was dead for good. Only a fixed or a lowest-priority interrupt is ever a level: an NMI is in service nowhere and nothing ends it, so such an entry is edge-triggered whatever its trigger bit says, as the 82093AA treats one -- taken as a level, a guest that pointed the SCI's entry at NMI had one sent at every look while the SCI was up, and its CPU 0 turned back its own entry for each, never to run again (hv-fuzz found it). An entry of INIT, which no PC's firmware wires a device to, is counted and not sent. A message goes as a device's MSI does: into the local APIC of the CPU whose loop sent it, or through another's mailbox, the level bit with it. The serial port had to become a 16550 for this: its transmitter's interrupt pending until IIR reports it or a byte is written, and each byte written a pulse of its line -- the edge an edge-triggered pin sees, where the 8259 was asked again for as long as the line was up. And the PIT's next edge waits for the last to be taken where it went: on the 8259 while its IRQ 0 is unmasked there, and through the IO-APIC while its vector is still requested in the first CPU's APIC.

Its local APICs come out of reset in xAPIC mode. Linux keeps a firmware-enabled x2APIC with an IO-APIC only with interrupt remapping, or under a hypervisor it knows to support x2APIC without -- KVM, Xen, Hyper-V. This one's CPUID names KVM's paravirtual interface (KVM's paravirtual interface), and a Linux built with KVM_GUEST takes that for the answer (x2apic_available is kvm_para_available there); one built without it does not, and finding its firmware left x2APIC on, a Linux 6.1 or 6.18 turns it off, reading its APIC's ID through a page it has not mapped, and faults. So a machine with an IO-APIC is the PC most firmware makes, in xAPIC mode, which every kernel takes as it is -- and which costs a KVM_GUEST kernel nothing: it turns x2APIC on by itself, KVM's interface being there, and runs as one started in x2APIC mode runs. Measured on the EX44 (VT-x; Linux 6.18 with KVM_GUEST, two CPUs, an IO-APIC): started in x2APIC mode, by a build of hv that kept it with an IO-APIC, the kernel said x2apic: enabled by BIOS; started in xAPIC mode, as hv starts it, x2apic enabled; routed by physical x2apic both ways, its serial port's IRQ 4 through the IO-APIC, the CPU delivering its APICs' interrupts and taking their EOIs (APICv), 34 and 38 exits a second idle, and 2,000 sleeps of 500 us in 1.22 s and 16.4 thousand exits each. The same 6.18 without KVM_GUEST, started in x2APIC mode, faults in enable_IR_x2apic as said above. So xAPIC out of reset stays:

$ hv boot /bzImage cpus=2 ioapic initrd=/initrd cmdline=console=ttyS0
...
[    0.081741] IOAPIC[0]: apic_id 2, version 32, address 0xfec00000, GSI 0-23
[    0.225009] APIC: Switch to symmetric I/O mode setup
[    0.232303] x2apic: IRQ remapping doesn't support X2APIC mode
[    0.260088] ..TIMER: vector=0x30 apic1=0 pin1=2 apic2=0 pin2=0
...
  mmio       65657 accesses performed for the guest, its instructions decoded: the xAPIC page's and the IO-APIC's
  ioapic     431 interrupts sent, 0 of them level-triggered, 0 ended by EOI, 0 levels no local APIC took, 0 of no delivery mode sent here

Every access of its APICs is then a decoded MMIO access (What an exit costs); keeping x2APIC mode with an IO-APIC would take an IOMMU's interrupt remapping, or a name Linux trusts. Linux checks the timer through the IO-APIC itself (..TIMER, and its count of ticks unless told no_timer_check), and routes the ISA lines where it likes -- the serial port's, here, to the second CPU, which through the 8259 it could never have been:

  0:         65          0  IO-APIC   2-edge      timer
  4:          0        219  IO-APIC   4-edge      ttyS0

With ACPI it routes interrupts Using IOAPIC, takes its SMP configuration from the MADT with the overrides (INT_SRC_OVR (bus 0 bus_irq 9 global_irq 9 high level)), and the SCI arrives on pin 9 as a level, IO-APIC 9-fasteoi acpi: the power button's one SCI a level-triggered interrupt, ended by EOI, and the guest off by acpid. Told pci=nomsi, a virtio device's INTx comes the same way, fasteoi on pin 11 or 10, each interrupt ended and sent again while the device's status is unread.

hv run's ioapic guest checks it without a kernel: the serial port's pin as an edge -- the enable an edge, a byte's pulse another, one while masked lost, unmasking sending nothing -- then as a level, sent again at each EOI until the handler reads IIR, the entry's remote IRR set in service and clear after; every access of the IO-APIC and every EOI through the pages.

On real hardware

The AX41 (a Ryzen 5 3600, Zen 2) has the whole of AMD-V -- 32768 ASIDs, next-RIP save, decode assists, flush by ASID, VMCB clean bits, AVIC -- and checks a VMCB as QEMU does not. There every built-in guest passes on the first CPU and the last, the extension turns on and off for all twelve, and the Linux guest boots to its shell and runs a typed id, at native speed: Run /init as init process 18 ms into the guest's clock, against half a second under TCG. The PIT calibrates the guest's TSC (3599.5 MHz), the guest takes the TSC as its clocksource, its timer delivers a hundred ticks a second, and idle at its prompt the vCPU's task sleeps 99% of the time.

The first run there stopped twice where TCG had never gone, which is what a run on the real thing is for:

  • CPUID leaf 0x80000001 went through whole but for SVM, and a Zen 2 has MWAITX in it. The guest's udelay became monitorx, whose intercept had no answer. The leaf is an allowlist now, as leaf 1 is, and an intercepted instruction CPUID did not offer is answered with the #UD a CPU without it gives.
  • Linux on a Zen CPU reads AMD's FCH at a fixed address -- the reset-status register, 0xFED803C0 -- whether or not there is one, and takes all ones for "no such device". A read of the platform's MMIO window that nothing answers is now answered with a read-only page of all ones; the absent built-in guest keeps that under TCG, which is no Zen and would never read it.

The second run, 2026-09-24 (8928493, one boot of nos): every built-in guest on CPU 0 and CPU 13 again, asid among them -- two VMs taking turns on one CPU under ASIDs 1 and 2, and a third given 1 again after its generation's flush, each reading its own page, on a CPU that keeps translations; the exit costs above; and both distributions (A distribution) as they ship:

  • Alpine at its login prompt 22 s after the VM starts. It calibrates its TSC against the emulated PIT (3600.143 MHz), takes the TSC as its clocksource and drives its tick through the PIT's one-shot mode 4 (hrtimer_interrupt) -- the path TCG never takes by itself; sleep 2 takes 2.00 s. On the switch it pings nos in 0.05 ms, and ssh -p 2222 root@65.109.93.213, from the dev host over the internet, lands in its own sshd through nos's I210, hv forward and the switch.
  • Debian at its login prompt 8.5 s after the VM starts (systemd-analyze: 1.0 s kernel, 3.5 s userspace), running, no unit failed, its root on the 3 GiB image on nos's nosenv ext2 -- which e2fsck found clean after -- a file written there still there after reboot, and on the switch it reaches nos and the Alpine guest.
  • Idle, the two cost nos 0.1% of its twelve CPUs (top), 560 and 700 exits a second.

And one thing only the real thing showed. Debian's clocksource watchdog, which checks the TSC against jiffies, found them 76 ms apart over 512 ms, called the TSC unstable and fell back to jiffies -- and then kept 25 s of time in 62: at 250 Hz its idle vCPU, woken at the host's 100 Hz tick, was given one timer edge for every two or three periods (a hundred a second), the rest thrown away. Alpine had kept the TSC and its time. The PIT now owes every period that elapsed and hands them over one at a time, as KVM's does (What the extension costs), and hv-distro-test checks each guest's idle clock against nos's: 1.000 with the fix, 0.514 without it under TCG. Over SSH the command line was also cut at 255 characters, too short for Debian's hv start; it takes 1023, as /etc/rc does.

Booted again with the fix (768a56b), the same day: Debian keeps the TSC -- Switched to clocksource tsc at 1.1 s, no watchdog complaint -- and counts 62.37 s of 62.4, Alpine 62.27; both dates the host's. The two boots were faster for it too, Debian at its login prompt in 3.8 s and Alpine in 8.9 s (8.5 and 22 s before): the guests' own timers had been waiting on ticks that never came. Debian's 343-character hv start went through over SSH; an exit cost 742 ns with ASIDs and 959 ns flushed, as before.

The way out, on the AX41 the same day (45df223): with both guests on the switch, NAT went out through the I210 from the machine's own address, and each guest was handed Hetzner's resolver (185.12.64.1) by ip= and by the switch's DHCP. Alpine resolved its mirror, apk updated from it, and fetched 100 MB from Hetzner's Helsinki speed-test server in 0.93 s; Debian took its address and route by DHCP, synchronised its clock over NTP, pinged 1.1.1.1 in 1.2 ms, apt-get updated over HTTPS (28.5 MB), and fetched 100 MB over HTTPS in 1.0 s and 1 GB in 16.6 s (65 MB/s). A connection from another host to a mapped port was refused by nos's own stack and never reached a guest. Over the session NAT carried 10,841 packets out and 943,241 back, and needed no next hop, frame or mapping it lacked.

Two things it showed that are not NAT's. apt-get update fetched those 28.5 MB in 39 s where one download of the same index took 0.2 s, and the guest's port dropped some 1,400 frames meanwhile: apt downloads over several connections at once while it decompresses, and a frame for a guest that is running -- not halted -- waits in the port's 64-frame inbox until its next exit. The switch woke a halted guest and had nothing to hurry a running one; at line rate the inbox fills in under a millisecond. It kicks a running one now, and the inbox is the guest's ring's size (A network). And a command run through nos's sshd for longer than the client's keepalive (ssh -o ServerAliveInterval=) was cut off, the server answering no keepalive while the command ran; commands run beside their session now, which tends the connection meanwhile (sshd).

Booted again with both fixed (50746e4): a 40 s hv wait over ssh with ServerAliveInterval=5 ServerAliveCountMax=2 ran its full 40 s, where it had been cut off at 14; and a gigabyte through NAT into the Debian guest took 9.8 s -- 109.8 MB/s, the link's rate. Not every time: right after a cold apt-get update the same download took 44 to 47 s. The guest had 125 MB of apt's lists to write back, a sync of them took 35 s -- 3.5 MB/s -- and the download after that ran at the link's rate again: the guest's disk writes stall its vCPU, a virtio-blk request being served on the vCPU's own task, synchronously, through nos's ext2 to the NVMe. Its clocksource watchdog saw the stalls too ("Long readout interval", gaps of up to 10 s). That is the disk's next thing to take out, as fewer exits per frame is the network's.

Booted again with the disk working beside the guest and ext2's writes costing what they change (2c72334, A disk), the same guest with 1 GiB, the same afternoon:

in the Debian guest before after
a cold apt-get update, 28.5 MB fetched in 15 to 26 s, 47 to 52 s in all fetched in 2 s, 3.8 s in all
a gigabyte to /dev/null right after it 44 to 47 s, 23 to 25 MB/s 9.9 s, 108 MB/s -- the link's rate
sync of what apt left dirty 125 MB in 35 s 90 MB in 0.36 s
dd 1 GiB, conv=fsync, a new file / over it again 261 / 284 MB/s
reading it back, the cache dropped 231 MB/s
a gigabyte fetched to the guest's disk 13.1 s, 82 MB/s, and sync 0.2 s after

"Long readout interval" came up in none of it. Afterwards e2fsck found nos's nosenv clean, and the guest's ext4 in its image too, taken read-only through a loop device; the image had 0.3 GiB of holes filled on the way. What bounded the rate then was ext2 writing a request's blocks one 4 KiB command at a time, each synchronous: the disk's task was at a whole CPU while the guest wrote, profile putting most of it in the NVMe driver's WaitGroup::wait yielding until the command completed.

Booted once more with a file's blocks going to the disk in batches, 32 commands in flight at once (63a7bb2, Filesystems):

in the Debian guest a block at a time in batches
dd 1 GiB, a new file / over it again 261 / 284 MB/s 363 / 358 MB/s
reading it back, the cache dropped 231 MB/s 397 MB/s
the disk's task, while dd writes a whole CPU 11% of one
sync of what apt-get update left dirty ~90 MB in 0.36 s 102 MB in 0.25 s
a gigabyte fetched to the guest's disk 82 MB/s 87 MB/s

and the guest at its login prompt in 3.5 s, its disk's task having spent a third as much CPU reading the boot in. e2fsck found nosenv and the guest's ext4 clean again. What bounds the guest now is its vCPU, at 85% of its CPU while dd writes: two thirds of that is copying each request's data out of guest memory, a page at a time through the kernel's temporary window and eight bytes at a time inside it (frame_copy, a mem_cpy call a word), and a fifth the guest itself running. A page's part of a copy is one mem_cpy now: under TCG the guest's 48 MiB dd ... conv=fsync onto a whole image takes 0.42 s where it took 0.64, and reading it back 0.24 s where it took 0.44, on virtio-blk and on NVMe alike.

On the AX41 with it (6bf9e84), the same guest:

in the Debian guest a word a call a page a call
dd 1 GiB, a new file / over it again 363 / 358 MB/s 966 / 932 MB/s
reading it back, the cache dropped 397 MB/s 1.3 GB/s
a gigabyte fetched to the guest's disk 87 MB/s 102 MB/s

and its NIC dropped no frame over the downloads, where it had dropped a few hundred a gigabyte. While dd writes 1.5 GiB at 925 MB/s the vCPU is at 99.9% of its CPU and the disk's task at 31%; half of the vCPU's time is now the guest itself running, and most of the rest the copies and the mapping of the temporary window for each page. e2fsck found nosenv and the guest's ext4 clean.

One thing that boot showed is not nos's: apt-get update took 31 s where it had taken 2 -- a flat 30 s of it on one request, then a new connection that had the answer in 20 ms. apt pipelines its requests, and the CDN behind deb.debian.org left the last of them on a connection unanswered: a capture in the guest has every byte the CDN sent acknowledged, and nothing more from it, data or FIN or RST, until the client gave up and closed -- then the CDN's answer went on from the very byte after the last one. From outside nos the same pipelining has the CDN close the connection in the middle of an answer. Whether the faster guest meets it at a new point or the CDN changed that afternoon, apt with -o Acquire::http::Pipeline-Depth=0 takes 2 s again.

Then the mapping itself: a copy's page went through the temporary window's shared slots, under their lock, with a reference taken and two TLB flushes, and that cost the vCPU as much as the copy. Each CPU has a slot of its own for it now (Paging), a page still mapped only for the length of its copy. On the AX41 (56b6da8):

in the Debian guest shared slots a slot per CPU
dd 1 GiB, a new file / over it again 966 / 932 MB/s 1.2 / 1.2 GB/s
reading it back, the cache dropped 1.3 GB/s 1.6 GB/s
dd 1.5 GiB, and the vCPU meanwhile 925 MB/s, 99.9% 1.2 GB/s, 70%
a gigabyte fetched to /dev/null / to the guest's disk 110 / 102 MB/s 117 / 107 MB/s

117 MB/s is what TCP carries over gigabit Ethernet at an MTU of 1500. The vCPU's time is two thirds the guest itself now, the copy an eighth, and what is left of the mapping -- the flush when a slot is cleared -- under 4%. The boot's frame self-test passed on all twelve CPUs, each through its own slot; apt-get update took 2 s with pipelining on and off; e2fsck found nosenv and the guest's ext4 clean.

Then guests of more than one CPU (More than one CPU), the same Debian image with cpus=2 and without nolapic: at its login prompt in 3.2 s, both CPUs online, systemd running with no unit failed, a gigabyte fetched at 113 to 116 MB/s, 1 GiB written with fsync at 1.2 GB/s and read back at 1.5; its reboot came back with both CPUs, a CPU taken offline and back was started again by INIT and a start-up IPI, and its poweroff ended as it should -- "hlt with interrupts off, on every CPU it has". What the first boot of it showed, and the next one fixed:

in the Debian guest 14a03e0 with the fixes
where cpus=2 put it 13, 12: one core's two threads 13, 11: two cores, one CCX
two busy loops, one alone taking 9.7 s 14.7 s 9.7 s
its CPUs on two CCXs a 2052-cycle TSC "warp", jiffies four CPUs on 13, 11, 9, 5: TSC kept, four loops 10.0 s
one CPU, on host cpu 0 TSC lost one boot in two TSC kept, three boots of three
its log an unchecked MSR access (0x852), three firmware bugs none

The frames its port dropped on the way were not new: the kernel and module before these, booted once more for it, dropped 431 and 608 a gigabyte for a guest of one CPU, the module of 14a03e0 on the same kernel 139 and none, and with the fixes a guest of two dropped 256, 500 and 129 -- the ceiling of the vCPU that took every receive interrupt through the 8259, six exits apiece. Its sampled profile over that fetch: 44% of its host CPU the guest running, and the rest the exits, spread thin. MSI-X took the ceiling away for a guest of more than one CPU: three gigabytes at 117 MB/s and not a frame dropped (Device interrupts, by MSI-X). e2fsck found nosenv and the guest's ext4 clean.

How to repeat it -- the kernel, the modules and the guest on the machine's nosenv partition, one boot of nos by nosboot, the shell over ssh -- is in Real hardware for the machine and in the gate's own header for the guest; the session's recipe is short:

# on the AX41, in Ubuntu: build, and put the modules and the guest beside the kernel
make nocheck && cp out/x86_64/modules/*.ko /nosenv/ && mkdir -p /nosenv/hvguest
# bzImage and initrd into /nosenv/hvguest/, then one boot of nos
nosboot -n && reboot
# from outside, once nos is up
ssh root@<box> 'insmod /hv.ko' ; ssh root@<box> 'hv on'
ssh root@<box> 'hv boot /hvguest/bzImage initrd=/hvguest/initrd secs=20 input=id\n cmdline=console=ttyS0 nolapic rdinit=/init'
ssh root@<box> reboot     # the one-shot is spent: back to Ubuntu

The EX44, under VT-x

The EX44 (an i5-13500: six P-cores of two threads and eight E-cores, with EPT, VPIDs and unrestricted guest) is the first Intel silicon VT-x has run on; everything before it was nested KVM. nos booted there from its system image, beside Ubuntu, on 2026-10-20 (Real hardware).

The first run (master's module, f3b0285): hv info ready, every built-in guest passed on a P-core (CPU 0) and an E-core (62), and an exit cost 1.67 and 2.07 µs on them -- against 5.8 µs nested. Linux 6.18 ran with one, two and four CPUs; a virtio disk took writes with fsync at 1.0 to 1.2 GB/s and gave reads at 1.5; a guest fetched a gigabyte through NAT in 9.1 s (118 MB/s) and served a page to the internet through hv forward; Alpine 3.24.2 came to its login prompt in 13 s and rebooted through 0xCF9 into a restart; and rmmod with five VMs running stopped them all and left VMX off on all twenty CPUs. It also showed, on the silicon, the VT-x halves of the review that were still open -- a guest's #DB not given back, its CR4 not intercepted, DR0-DR3 readable by the next VM, no speculation control -- and two things that are not bugs of the extension: a guest of four CPUs placed on one P-core's two threads and two E-cores (where its CPUs are placed knows nothing of P and E yet), and the first write into a sparse disk image's holes at 170 to 180 MB/s, against a gigabyte a second once its blocks are there.

The second (the review's VT-x halves done -- item 1, 7 and 8, bugs 2 and 5): seventeen of seventeen built-in guests on a thread of each of two P-cores (CPUs 0 and 41) and on two E-cores (48 and 62), debug, cr4 and dr among them; every CPU deciding its own mitigations -- enhanced IBRS with BHI_DIS_S, VERW for RFDS, no L1D flush, which is Linux's reading of the same CPU -- and an IBPB between guests, 159 in the session; Linux with one CPU and with two, both online and each taking its own timer, and a disk written at 1.1 GB/s with fsync and read at 1.5; Alpine at its login prompt in 13 s with the TSC its clock and not a line of its log an error, fetching its package index through NAT; rmmod and a load again with nothing left on. What the mitigations cost an exit is in What an exit costs: 7% on a P-core, 20% on an E-core.

To repeat it there: build in Ubuntu, mount nos's root by its UUID, copy hv.ko and the guests onto it, grub-editenv <root>/grubenv set nos_next=nos and reboot -- nos for one boot, Ubuntu after it (Install: nos on a server) -- then insmod, hv on and the rest over ssh as above.

What comes next

From plans/03-hypervisor.md, in order, each a thing that can be shown in half a minute:

  1. a VM object with nested page tables, and a guest of a few bytes that exits where it was told to -- under AMD-V, hv run exits;
  2. a guest in long mode under NPT/EPT -- NPT, hv run hypercall;
  3. an emulated 8250 on port I/O exits, and a bzImage printing its early console -- hv boot, and the guest of A Linux guest below;
  4. a full boot to a shell over that UART, with an initramfs, on one vCPU -- with an initramfs, a BusyBox shell.

All four demos are done, and a guest runs a command typed at its console (hv boot ... input='id\n' → uid=0 gid=0) -- under TCG and on the AX41's real AMD-V (On real hardware). Guests also run until they are stopped, reached from the shell (Guests that stay up): the lifecycle the control plane will serve. The VMX backend is there beside AMD-V, with CR0.NE set on every CPU (The VMX backend). The TLB is no longer flushed whole on every entry (Address space identifiers), guests have disks and a network over legacy virtio (A disk, A network) with a way out through NAT (The way out), a distribution boots as it ships (A distribution), and a guest has as many CPUs as it is given, each with a local APIC (More than one CPU) -- under AMD-V and VT-x both. A guest of more than one CPU takes its devices' interrupts by MSI-X (Device interrupts, by MSI-X), and every guest has ACPI's tables and fixed hardware -- its power button what hv stop presses (ACPI). MMIO is emulated -- the instruction that faulted fetched by the guest's paging, decoded and performed -- and the xAPIC page is its first device, the IO-APIC its second (MMIO); Q35's ECAM is answered there too, 256 buses of it. The HPET is still left out. Beyond stage 3: device work off the first CPU's task, modern virtio, and the control plane's HTTP API (stage 4) -- and before any of it, what a review of the whole found (What a review found).

Two constraints from stage 5 (live update) hold from the first line of it: all VM state is serializable plain data -- the vCPU register set, every emulated device, and one table mapping guest physical pages to the VM that owns them -- and no emulated device holds a pointer into arbitrary kernel memory, only indices and handles that survive a re-init. So far the VMCB and the registers vmrun leaves to software are plain words, and guest memory is regions of pages whose nested table is derived from them.

What a review found

A review of the whole of it on 2026-10-10 -- hvarch, hv and the module, at cf87887 -- by five readers at once, each finding read again in the code before it was written down here, left the list below. Each item says where, what goes wrong and what would fix it, and is struck through when it is done, as the steps above are. Where an item rests on what Linux does rather than on this tree it says so: that part was read in Linux's source, not run.

The order to take them in: the bugs first -- each small, each with the fuzz target or the gate that would have caught it; then the CPUID and MSR policy as an allow-list, which is isolation and speed at once; then the guests' network kept off the host's services and the world's metadata; then the speculative-execution work and whole cores per guest, before any guest is someone else's; then speed.

Bugs

  1. A guest can hold one of its CPUs' tasks in the host for good. Done: a pass takes a queue's worth of chains at most -- all a driver can have available at once -- and leaves the rest to the next round of the devices (PASS in devices/net.rs and devices/blk.rs); hv-fuzz's racing CPU (Racer in tests/fuzz/hv/src/memory.rs) tops a ring up while a notify or a round runs, and found both old loops in its first ten inputs. What it was: the virtio-net transmit loop (Net::send) and the virtio-blk one (Blk::fill) go round until Queue::pop finds nothing, and pop reads the driver's avail index afresh each time -- with no budget, no look at the stop flag, and the platform's lock held (the doorbell's port write runs them under it, as does the first CPU's round of the devices). A second vCPU that keeps the ring topped up, by plain writes to its own memory and no exit, keeps the one in the loop there forever: hv stop waits on its task (finish), and so does rmmod; the host CPU spins, every other vCPU that touches a port waits on the lock, and every frame goes into the switch at memcpy speed. Fix: at most a queue's worth of chains a pass, the rest left for the next round.
  2. An unprivileged process stops its whole VM. Done: the run loop gives a guest its own #AC and #DB back on both backends -- a single step, and ICEBP, stepped past -- once nothing an exit cut short is on its way in (GuestCpu::exception); an instruction of VMX's, SVM's or GETSEC is answered #UD, RDPMC #GP. Under VT-x, whose exit writes no DR6, the DR6 its qualification says goes into the guest's at the exit, and a single step out of an interrupt shadow is marked pending for the entry (The VMX backend). The debug built-in guest single-steps and runs an int1 and its own handler must see both, DR6 right, on both backends; hv-fuzz's platform target gives the run loop the guest's #DB and #AC, now and then over an event still on its way in. What it was: every intercepted exception was a stop (Stop::Exception in run.rs), #DB and #AC are intercepted always (CVE-2015-5307 and 8104), and an exit the run loop does not know is a stop too (Stop::Unexpected). A single step -- gdb's stepi, ptrace, a uprobe -- int1, an unaligned access with EFLAGS.AC set (Linux runs with CR0.AM), or under VT-x any VMX instruction (vmxoff at CPL 3: in non-root operation it exits before the CPL is checked) ends the VM; and since that is not a reset, restart does not bring it back. Fix: keep the intercepts and give the events back -- #DB with its DR6 (the VMCB's under AMD-V, made from the exit qualification under VT-x), #AC with error code 0, ICEBP as a #DB, #UD for the VMX instructions and for RDPMC. Half of the job the VMX backend's debug-register item names.
  3. A virtqueue's indices are copied a byte at a time. Done: a ring's indices and flags are read and written as one aligned access -- GuestMemory::read_u16 and write_u16, over Frame::load_u16 and store_u16 and the kernel's kernel_frame_load16 and store16 -- the load an acquire and the store a release. What it was: read_u16 of avail.idx and Queue::push's store of used.idx go through GuestMemory::read and write to frame_copy, whose mem_cpy is a rep movsb of two bytes: nothing makes the two one access. When a driver on another CPU moves the index across a multiple of 256 while the host reads it, 0x0100 can be read as 0x01FF -- Broken::Overrun, the device dead until a reset Linux never does -- and the guest can read a used index half written. Fix: an aligned load and store of 2, 4 and 8 bytes as one access in kcore::frame, through the CPU's slot, for the ring's indices and flags.
  4. A CPU's x87/SSE owner goes stale when a vCPU moves. Done: a guest that loads its registers on a CPU takes its mark off every other (fp::registers_loaded), so its number is on one CPU at most -- the last it loaded on -- and registers_are means what it says. What it was: fp::OWNER says whose registers a CPU holds, and an entry skips its FXRSTOR when they are the guest's own; nothing takes the mark away when the same guest loads them on another CPU. A task that runs on A, then B, then A again resumes on A with the registers of its first stay there. A Linux guest's tasks are bound to a CPU each, so today only hv run without a CPU can move; anything that moves a vCPU later meets it. Fix: skip the FXRSTOR only on the CPU the guest last loaded its registers on.
  5. CR4.MCE is the guest's. Done -- under AMD-V: hvarch's Guest::run sets MCE in the CR4 the guest runs with and intercepts every write of CR4, whatever the policy asks; hv intercepts the reads too, keeps the CR4 the guest wrote and answers from it (hypervisor/hv/src/cr.rs: the instruction fetched and decoded, insn::decode_mov_cr, since QEMU's and a nested hypervisor's CPUs give no decode assists), refuses with #GP a bit the guest's CPUID does not offer -- PKE where its PKRU is not switched, which closed the PKRU half of item 7 below under AMD-V -- and a write no CPU takes in long mode, and flushes the guest's TLB where the CPU would. The cr4 built-in guest, hv-fuzz's platform target (every read and write held to what it should have done, at the CPU's next entry) and insn-test's control registers are its gates; a Linux guest of one CPU and of two boots through it. The cost is an exit for every mov of CR4 -- two for each of Linux's global TLB flushes, which toggle PGE. QEMU's TCG, where the gates run, stops no read of CR4 (a bug of its own, above): there the reads are checked by the fuzzer alone, and the cr4 guest says which it saw. And under VT-x, where the CR4 guest/host mask was VMXE alone: MCE in the mask with every bit the guest does not own, the guest's value in the read shadow, the register keeping MCE, and a write that changes a bit of the mask performed by crate::cr as AMD-V's are -- the cr4 guest read back what it wrote while the CPU's kept MCE, on the EX44 and under nested KVM. What it was: AMD-V intercepted no CR at all and VT-x's mask was VMXE alone, so a guest could clear MCE -- a kernel built without X86_MCE does, from Linux's source -- and a machine check on that CPU while it ran was a shutdown: the host saw the guest's triple fault, restarted it, and never heard of the #MC. KVM keeps the host's MCE in the hardware CR4 under both vendors.
  6. #GP goes in with an error code whatever the CPU's mode. Done: inject_gp gives the error code only with CR0.PE set, on both backends. What it was: both backends' inject_gp set the error code. A CPU in real mode -- an AP between its start-up IPI and PE -- takes none: VT-x refuses the entry (the guest stops as Invalid) and AMD-V pushes a word its handler does not expect. Fix: no error code with CR0.PE clear.
  7. In the module.
    • hv exec stops working for good after a boot that threw away unread input -- done: what a new boot throws away is counted as fed and noted as lost (Input::lost), and an hv exec waiting on a line of it says the line went with that boot. What it was: Shared::requeue cleared the queue but fed never caught up with queued, so fed_at was None from then on.
    • Forwards and NAT's mappings outlive their VM -- done: hv stop takes a VM's forwards away with it (Forwards::drop_vm), and the switch has NAT forget its address's flows as it gives the port back (Switch::release, Nat::forget, kernel_net_nat_forget); hv-fuzz's nat target forgets guests and holds the table to it, and hv-linux-test.py --net stops a VM with a forward and flows and looks. What it was: hv stop gave the port back to the switch, and the next hv start ... net took the lowest free one -- the same MAC and the same address (port_ip) -- and with it the old VM's forwards and the answers to its flows. And a forward added as its VM was stopped -- forward= of a start whose session was slow to take its line, hv forward add, the bus's forward_add -- could land after the stop's drop_vm and outlive the VM the same way: Forwards::add now asks whether the VM is listed under its own lock as the forward goes in (Vms::on_list), so the stop's drop_vm, which follows the VM off the list, takes it or it is refused; and the stops take the forwards before they give the switch port back.
    • Two VMs can open one image read-write -- done: a guest's disk claims its image as it opens it (disk::Claims), by the file -- its mount and inode (kernel_file_mount, kernel_file_key), so two names of one image are one -- a disk that writes it alone and any number that only read it together, and a start or a boot that cannot have its claim is refused saying whose the image is; the claim goes with the disk. Among the VMs only: nos's own shell is not held to it. hv-linux-test.py refuses a writer and a reader beside a writer, and a writer beside two readers; fs-fuzz.py holds every open file's identity to the model's. What it was: FileDisk::open opened the file read-write for every VM that named it, and the VFS has no exclusive writer -- two ext4s on one set of blocks.
    • Nothing keeps host memory back -- done: a frame is not taken past a reserve the kernel keeps for itself, a sixteenth of the machine and no less than 64 MiB (kernel_frame_alloc, over PageTable::alloc_page_keeping), so a guest too large is refused out of memory rather than taking the last page; and guest::build reads and plans the image before it takes any of the guest's memory. The size of the reserve is a guess to revisit. What it was: mem= was checked against 4064 MiB alone, for up to 16 VMs, guest memory taken a frame at a time from the free list everything else uses -- a start could empty it, and the next infallible allocation anywhere panicked the host.
    • hv stop takes the VM off the table before it waits for the guest to shut down -- done: it stays on the list, stopping, while its power button has its time -- its CPUs counted, hv off and an unload seeing it, a second stop and a restart refused -- and an unload ends the wait. What it was: for up to secs, rmmod did not see it, hv list did not show it, and its CPUs could be given to a new VM.
    • An unload that finds a guest's VMCS still current on a CPU says so -- and then frees that CPU's VMXON page anyway -- done: the machine's drop leaks such a page, and says so, rather than leave a CPU in VMX operation over freed RAM. What it was: Machine::disable kept the page and the machine's drop freed it.
  8. The safe half enters a guest over any table it is handed. Done: both enters are the crate's own and take the &GuestMemory whose table they enter over -- a table comes only from the memory that owns its pages, and the module cannot reach either. What it was: svm::Vcpu::enter and vmx::Vcpu::enter are safe pub fns taking a Nested whose root and id are public, and Vm::vcpu_mut reaches them: the invariant the crate split is for -- a guest's nested table maps its own pages -- is a promise of the one caller, Cpu::enter, not a property of the types. Fix: enter crate-private and taking &GuestMemory, a Nested that only npt and ept can make.
  9. An unchecked add on a guest's RIP. Done: it wraps, as the CPU does. What it was: the VT-x I/O exit's next_rip is rip + length with no wrap, where everything else wraps: an in at the top of the address space is a host panic in a RUSTUB=1 build. The fuzzer does not compile hypervisor/hv/src/vmx.rs, which is why it went unseen.

Before other people's guests

  1. Speculative-execution mitigation: the world switch done, under both extensions; what is not the world switch's, not. Done under AMD-V (What entering a guest cannot be told to do): after every exit the guest's values are cleared out of the registers the run stub returns with, and the return stack is refilled before the host's first ret; an IBPB goes between two guests on a CPU where the CPU has one; and automatic IBRS is on while the extension is where the CPU has that. hv-test runs every built-in guest through the first two on CPU 0 and on CPU 3, and holds hv to at least two switches between guests a guest, each with an IBPB where the CPU offers one. QEMU's TCG offers neither IBPB nor automatic IBRS; the AX41's Zen 2 is where the IBPB first ran, under KVM and on the silicon, and automatic IBRS has run on no machine yet. What it was: none of it, the guest's values left in the caller-saved registers the stub returned with. On Zen 1 to 4 (the AX41), SRSO and Retbleed, and BTI where there is no automatic IBRS. Done by an IBPB after every exit, decided for each CPU from its family and CPUID, with STIBP where a core has two threads and HLT and MWAIT always exits (SMT_RSB) -- what Linux does for a host whose only way in from a guest is an exit (What entering a guest cannot be told to do); hv names what a CPU is open to with nothing to close it, and hv-test gives its machine cores of two threads, so that under KVM on an AMD host it holds every CPU to the STIBP hv on set. Left: the cheaper way to the same end, the host's every ret through an untrained return thunk and its indirect branches through retpolines -- a compiler's job, for the whole kernel, C++, Rust and the modules; a Zen 3 or 4 whose microcode has IBPB_BRTYPE but whose CPUID does not say so, which Linux finds by a write to PRED_CMD and this takes for open to SRSO; Zen 5's cheaper control of SRSO and TSA's VERW (Zen 3 and 4). A guest's own speculation controls -- IBRS, STIBP, SSBD, IBPB -- are offered now, its IA32_SPEC_CTRL switched with it and its IBPBs performed (What the extension costs). Done under VT-x (The VMX backend), decided for each CPU from what CPUID and IA32_ARCH_CAPABILITIES say of it, with KVM's as the reference: the registers cleared and the return stack refilled after every exit, as AMD-V's stub does; the IBPB between guests; IBRS while the extension is on -- enhanced, set once, and on a CPU without it written again after every exit -- with BHI_DIS_S where the CPU has the control; VERW before every entry where MDS, TAA or RFDS apply; and the L1 data cache flushed before every entry where L1TF does. On the EX44's i5-13500 that is enhanced IBRS, BHI_DIS_S and VERW -- RFDS, by its E-cores -- what Linux reports for it ("Enhanced / Automatic IBRS; BHI: BHI_DIS_S", "Clear Register File"); on the Dell's Skylake it would be legacy IBRS, VERW and the L1D flush. hv-test holds VT-x to the switches and IBPBs as it does AMD-V, and hv reads every CPU's IA32_SPEC_CTRL back, warning where it lost what hv on set. On the EX44 they cost an exit 7% on a P-core and 20% on an E-core, most of that BHI_DIS_S (What an exit costs). Left under VT-x: the software sequence that clears the branch history, for a CPU with enhanced IBRS open to BHI and without BHI_DIS_S -- none of the machines here, but nos under nested KVM on QEMU 8.2, which does not pass BHI_DIS_S through, and hv says so -- and L1TF with hyper-threading, which an L1D flush does not reach: the sibling's guest reads the cache meanwhile, and only a guest's whole cores with the host's work kept off them would.
  2. The CPUID and MSR policy is a block-list, and it swallows. Done: both are allow-lists (hypervisor/hv/src/policy.rs, A Linux guest). A leaf the policy does not name is all zeros, as is every leaf past the tops it reports, 0x16 and 0x8000_0021; of leaf 6 a guest is told ARAT alone, of 0x80000008 the address widths -- the physical one the host's, the linear one 48 at most, LA57 not being offered -- CLZERO, the FP error pointers and two attacks the CPU is not open to, of 0x80000021 what is true of the silicon and asks nothing of the host. The speculation controls are offered now, their MSRs behind them (item 1); not INVLPGB nor AutoIBRS; the hypervisor bit is set. An MSR the policy does not name is a #GP both ways; what it names is the guest's own state, the TSC, or a constant that takes a write leaving it as it is and refuses any other: machine checks with no banks, the microcode revision -- the host's on Intel, none elsewhere -- and of each vendor what Linux reads of every such CPU without asking. The guest's own state takes what the CPU would: a PAT entry that is no memory type, an address that is not canonical and an EFER bit the CPUID does not offer (FFXSR) are #GPs, where they were a VMCB vmrun refused; and since NB_CFG says AMD's extended configuration is on, a CONFIG_ADDRESS that names a register past 255 reads all ones. hv-fuzz's policy target holds the policy to a model written from the manuals, with a table of what each CPUID bit promises: nine mutants, the old swallowing and IBPB offered among them, each failed within 1,600 inputs. hv-test.py's msr guest has the run loop refuse VIRT_SPEC_CTRL, FLUSH_CMD -- once SPEC_CTRL and PRED_CMD, which are a guest's own now, and the spec guest's -- an MSR nobody names and an invalid variable MTRR base, read back the MTRRs it writes, and answer the machine-check registers and the PAT; a build that refused MCG_STATUS failed it. hv-linux-test.py holds every boot's console to no "unchecked MSR access error" and no "MCA architectural violation", run with a guest kernel that has machine checks, MTRRs and PAT, as a distribution's does, on QEMU's max, on a Zen 2 (--qemu-cpu EPYC-Rome-v1) and on an Intel CPU given AMD-V (--qemu-cpu Skylake-Client-v1,+svm,+npt,+nrip-save): the Zen 2's kernel probed LS_CFG, SYSCFG and the legacy PMU and was refused each, which it was ready for -- it no longer takes LS_CFG for an SSBD that wrote into nothing -- and the Intel's no longer turns its fast strings off or calls its microcode old; with MCG_STATUS refused, the Zen 2's guest panicked at boot ("MCA architectural violation!") and the check failed. What it was: every MSR the policy did not name read 0 and took any write without a #GP -- though rdmsr's comment promised a None for one -- and every leaf it did not name was the host's. Extended leaf 0x80000008 EBX went through but for two bits, so a guest on AMD was told of IBPB, IBRS, STIBP and SSBD and wrote PRED_CMD and SPEC_CTRL into nothing while its sysfs said it was mitigated: a failure that passes in silence. On AMD newer than the AX41 it was worse, from Linux's source: Zen 3's INVLPGB was offered while the VMCB does not enable it (a #UD in Linux 6.15's TLB flushes), and Zen 4's AutoIBRS was offered while the EFER bit that turns it on was refused -- which Linux does not notice, and ran with neither AutoIBRS nor retpolines.
  3. The guests reach the host's own TCP services. Done: a TCP listener and a connection belong to their device (layers/net/src/tcp.rs, a slot's device) -- a listener takes a SYN only from the device it was opened on, as kcore::tcp::TcpListener always said it did, and a connection a segment or an ICMP error only from its own -- so sshd and hv forward's ports, on eth0, refuse a guest on hv0, at nos's address there and at eth0's, and an ICMP error from a guest cannot abort a connection of nos's over eth0. UDP's listeners were each device's already. net-fuzz's tcp target has a guest send SYNs from a second device; hv-linux-test.py --net has two guests nc nos's sshd and the test machine reach it from outside. What it was: find_listener matched the address and the port, not the device, and sshd listened at every address: a guest connected to 10.0.100.1:22 -- the control run's guests had the banner both ways -- and four connections that never logged in held every slot for logging in, on the Hetzner boxes the only console there is. Forwards still draw on the same 64 connections the machine has, every forward together at most twelve relays -- 24 of them -- where eight of eight each had been 128; and a relay closes its two first, each then waiting out its close for a minute in TIME-WAIT: a client that opened and closed through one forward about once a second held all 64, and nos's sshd and API turned everyone away. The kernel now takes such a slot back for a new connection when none is free -- one in TIME-WAIT the longest first, as Linux does past tcp_max_tw_buckets (Tcp::reclaim in layers/net/src/tcp.rs); net-fuzz's tcp target opens 72 in a row that the machine closes first, each to be answered, and a build without the reclaim refused the 43rd.
  4. NAT lets a guest go anywhere nos can. Done: NAT keeps the guests from link-local, the private networks, the shared space and the uplink's own subnet unless nat allow lets a network through, the DNS server they are given at port 53 aside, and answers a guest's packet for any of them with an ICMP "administratively prohibited" (The way out). hv-fuzz's nat target holds every packet to a model of the rule -- control runs with nothing denied, the DNS server not let through, nat allow ignored and the reject's code wrong each failed within thirty inputs -- and hv-linux-test.py --net has a guest refused at the test machine and at 169.254.169.254 before nat allow 10.0.2.2/32; on the stack before, the guest had the test machine's page and NAT mapped its connection to the metadata address. What it was: routable refused 0/8, 127/8, multicast and the subnet's broadcast and nothing else, so 169.254.169.254 -- the host VM's credentials -- the private networks and the host's own LAN were all open.
  5. What the guests share has no quota. Done. NAT's half: a full table gives a new flow the mapping used least lately of the guest that holds the most -- the asker's own when it holds as many as any -- where it refused every new flow, so one guest that filled it kept every other from the world (The way out). The boot self-test holds the shares to the rule -- a guest's own flow, another guest's taken from the one holding the most, a tie, every slot held -- and hv-fuzz's nat target floods the table and holds each flow taken to it; refusing when full, as before, failed it at once. And the soonest a sweep may find a flow run out is kept as each flow's time is, where a flow made after the last sweep could run out unseen and be counted live for up to two hours. And the switch's: a port takes no more of hv0's 256-frame backlog, between two of the stack's passes over it, than the backlog over the ports in use, and sends to every port at 64 at once and 256 a second (A network); hv-fuzz's switch target bursts a guest's frames past both and holds every port's counts to a model of its own -- no share at all, no rate, a share not divided and one never counted afresh each failed within 40 inputs. What it was: one NAT table of 4096 mappings that refused a new flow when full rather than take the flooder's; one 256-frame backlog for hv0 that a guest sending as fast as it could filled before the others' frames came; a broadcast copied to every port, each a wake or a kick, at any rate.
  6. Two VMs can share a core. Done: a guest's cores are its own (More than one CPU) -- whole cores no other guest has a CPU on, its vCPUs or its disks' task, its vCPUs filling their threads, its disks' task on a spare thread of its own cores, then on a core no guest has; refused where there is none, and hv cores shared for a machine whose guests are all one's own. The place and the hold on it are taken under one lock, so two starts at once are given cores apart. hv-fuzz's place target holds every placement and every refusal to a model of its own over made-up hosts -- threads a core, caches, CPUs missing and off -- and five mutants (later cores not checked, one vCPU a core, the disks' task on a held core, cpu='s core not checked, the disks' task elsewhere before a spare thread of its own) each failed within two inputs; hv-linux-test puts vm 0 and vm 1 on cores apart, refuses a third while both are held, and serves a guest's disk on its own core. What it was: pick_cpus kept a guest's own CPUs off each other's cores, for speed, and nothing kept another guest off them, nor the task serving another guest's disk off the sibling thread. Left: the host's own tasks -- the network stack among them, which carries every guest's frames -- still run on any core; a core of the host's own for them is core scheduling, not placement.
  7. Debug registers and PKRU, under VT-x. Done, under both. Under AMD-V a guest's DR0-3 are its own, every mov of them intercepted and performed on a copy per vCPU, and the CPU's made that copy before each entry -- writing only what differs from what the CPU holds (What entering a guest cannot be told to do). hv-test's dr guest runs two VMs on one CPU, the second reading 0 where the first left its own and each one's breakpoint firing at its own address -- the world switch before this failed it, the second VM reading the first's breakpoint address and pattern, and one without the load, or loading only when the guest's DR7 enabled a breakpoint, never fired the first's breakpoint; hv-fuzz's platform target holds every mov of them -- a read, a write, at CPL 3, under general detect -- to a model of its own, and seven mutants of hypervisor/hv/src/dr.rs each failed within 145 inputs. What it was: DR0-3 switched by neither backend, one guest's breakpoint addresses the next's to read and to move. Under VT-x every mov of a debug register exits and crate::dr answers it -- DR0-3 from the guest's own four, made the CPU's before its entries as AMD-V's are, DR6 from the guest's own, DR7 the VMCS's, which the entry loads (above); the dr guest's second VM reads 0 there too, each breakpoint firing at its own address, all eighteen movs of a debug register the host's, and the platform target holds DR4-DR7 to its model as well -- three mutants of dr.rs (DR6 written whole, the #UD of DR4 and DR5 checked after the CPL, no #GP for a bit above 31) each failed at once. And PKRU: a guest's write of CR4.PKE was a #GP under both (item 5), its CPUID not offering PKU, and WRPKRU then the #UD it is without PKE -- under VT-x it had been the guest's to set, and nothing switched the register. Now PKU is offered where the CPU has it, and PKRU switched with the guest (What the extension costs).
  8. VT-x's controls are taken on trust. Done: a control the host needs that adjust dropped -- the exits for interrupts and NMIs, ports, CR8, MONITOR, MWAIT, RDPMC, every mov of a debug register and WBINVD, EPT, the 64-bit host, EFER's, the PAT's and DR7's switch -- or one the guest was promised, unrestricted guest and its VPID, refuses the guest, naming the field and the bits (Refusal::Controls). What it was: adjust dropped a control the CPU, or an outer hypervisor, did not allow, and only the MSR bitmap was looked at again: a CR8, WBINVD, I/O, external-interrupt or NMI exit gone missing would have gone unnoticed.
  9. A guest's console is the host's log. Done: a guest's console goes to the kernel log a boot's worth at once -- a thousand lines -- and fifty lines a second after that, per VM (modules/hypervisor/hv/src/guest.rs, LogLine::admit); what is left out is counted, and said once a second at most, before the next line logged, and when the boot ends -- a notice for every line logged after a gap would have doubled the rate -- and the console itself keeps every byte. hv-linux-test.py floods one guest's console with twenty thousand lines and holds the log to fewer than half of them -- by dmesg's count of the lines it pushed out, read before the flood and after -- every notice to the gaps in the numbers it came between, and the guest's console to all of them; on the stack before, the log took all of them and said nothing. What it was: hv boot, and hv start ... log, put every console line into the kernel's log at level 0 with no limit -- dmesg, the serial console, netconsole.

The CPU a guest is shown

  1. SSE4.2, and nothing after it. Half done: leaf 7 is open bit by bit -- SMEP, SMAP, UMIP, FSGSBASE, BMI, ADX, ERMS and FSRM, RDSEED, SHA, CLFLUSHOPT and CLWB, SERIALIZE, MD_CLEAR -- PCID is offered, and ARCH_CAPABILITIES reads as the host's but for what is not a fact of the CPU (A Linux guest). Alpine's kernel on the EX44 said before "meltdown: Mitigation: PTI" -- its page tables isolated, a whole TLB flush at every system call, no PCID -- MDS and RFDS "Vulnerable: no microcode", L1TF mitigated by PTE inversion, and none of SMEP, SMAP or UMIP in its flags; after, Meltdown, MDS, L1TF and the iTLB multihit "Not affected", RFDS "Mitigation: Clear Register File", and every one of those in its flags. PCID it turns off itself there ("Incomplete global flushes", an Alder Lake and Raptor Lake erratum); on another CPU it is used. XSAVE is offered now, XCR0 switched with the guest and leaf 0xD made up for what is switched, the x87, SSE and AVX (above) -- and with it AVX, FMA, F16C, AVX2, VAES and VPCLMULQDQ: the whole of x86-64-v3's list, for a distribution built for it (RHEL 10 and its rebuilds). And the speculation controls, the guest's IA32_SPEC_CTRL its own and its IBPBs performed: Spectre v2 by enhanced IBRS in a guest whose host has it, its store bypass its own to close. (The hypervisor bit, clear until the policy became an allow-list -- the guest believing it was on bare metal -- is set now: above, item 2.)
  2. MSRs that read 0 and should not. Intel's MISC_ENABLE without fast strings, which Linux answered by turning REP MOVS's fast paths off ("Disabled fast string operations"), has them as the host has now. MTRRcap now advertises fixed ranges, WC and eight variable pairs, and DEF_TYPE and the fixed and variable registers are each vCPU's own. They start at reset's zero and a firmware or guest write of a valid type reads back, so firmware can turn on write-back instead of leaving PAT unused.
  3. Devices, smaller. The 16550 never sets IIR's FIFO bits, so Linux takes it for a 16450 and writes it a byte an interrupt; the RTC never interrupts (status B is read-only, C always 0, IRQ 8 never raised), so no update, alarm or periodic interrupt ever comes; the 8259 takes ICW4 and ignores it, auto-EOI with it; virtio-net offers no MTU, so a guest that raises its own past 1500 loses those frames; MSI-X entries start unmasked, their table being zeroed guest memory; VT-x never loads the PDPTE fields, so a 32-bit PAE guest that turns paging on faults.
  4. The guest's kernel is nos's file. A guest booted by hvboot boots the kernel its own disk's grub.cfg names, at every restart again (A guest's own kernel); one booted by its bzImage still boots that. BLS entries are not read yet.

Speed

  1. The CPU a guest is shown, above, is the largest lever on Intel. One piece of it: the microcode revision a guest reads (IA32_BIOS_SIGN_ID) is the host's on Intel, as KVM tells it, where it was 0 -- Ubuntu's 6.8 then took the EX44's Raptor Lake for one with the INVLPG erratum's old microcode and turned PCID off ("Incomplete global flushes, disabling PCID"), a whole TLB flush at every switch of process.
  2. The disk is one request at a time, machine-wide. A guest's image is held and read and written off the VFS's lock (fs::image): its block map resolved under it, the blocks moved without it, a flush the device's unless a write into a hole went through the VFS -- so one guest's disk no longer waits behind another's, nor behind nos's own files. What it was: Vfs::read_at and write_within held the VFS's one lock across the whole synchronous ext2 read or write, and a guest's FLUSH was a sync of the whole filesystem under it. On the AX41, nested under KVM, with two guests at once each reading 4 KiB four at a time off its own image: 1.30 and 1.35 s each where it was 1.86 and 1.69, reads of 64 KiB 0.74 where they were 1.02, writes of 4 KiB 1.55 and 1.61 where they were 1.84 and 1.69; one guest alone the same, within the spread. Then (2026-10-31, plans/vm-performance.md, after a comparison with QEMU/KVM on the EX44 found a guest's first write into its disk at 1% of KVM's speed and its queued reads at 8%): the image holds the file's map and takes no lock of the VFS's at all; a write into a hole grows the file by the 16 MiB chunk around it, zeroed by the device, a commit a chunk rather than one a batch; the NVMe driver's commands are as big as MDTS lets them be, a batch's contiguous blocks one command named by a PRP list, where every 4 KiB block was a command of its own waited for alone; and a disk's task serves every request waiting at once as one batch, where it served them one at a time. Four tasks a disk -- the image's reads side by side in lanes of their own, its writes one at a time -- were tried before that and left out: slower wherever they differed, two guests' four writers of 64 KiB 8.5 s each where they were 1.2, since four lanes' batches of up to 16 pieces took every one of the NVMe driver's 64 command IDs and the one left waiting slept 50 microseconds at a time, and each extra task's wakeup is an IPI that nested under KVM is an exit.
  3. Fewer exits a request. EVENT_IDX done (A disk): the receive ring's refills no longer notify, and a disk with every buffer out takes no notify it cannot act on. Left: NO_NOTIFY, the flag's way of the same for a driver without EVENT_IDX, which every Linux takes; and a guest of one CPU has no local APIC, so no MSI-X -- six exits an interrupt through the 8259.
  4. The EX44's E-cores first, with shared cores. Done: hv::topology asks each CPU of a hybrid part which kind of core it is (leaf 0x1A), and placement puts a guest's vCPUs on one kind where one has room for them all, the faster first; a tie under hv cores shared goes to the faster kind; and a disks' task given a core of its own takes a slow one. The hv fuzzer's place target holds it to hybrid hosts made up an input, and three mutants -- no kind kept, the slower first, a disks' task on a fast core -- each failed at its first input. What it was: no rule knew a P-core from an E-core; hv cores shared gave a tie to the highest CPU, which on the EX44 is an E-core, and a guest of four CPUs went on one P-core's two threads and two E-cores.
  5. PAUSE. Done under VT-x: pause-loop exiting where the CPU has it (More than one CPU), every PAUSE where it has not. On the EX44 a guest of two CPUs booting for twenty seconds exited 99,297 times where it had exited 299,508, its APIC timer calibrated as before (jiffies result ok). Left: AMD-V sets the pause filter's count and leaves its threshold unused.
  6. The larger ones. APICv and posted interrupts done under VT-x, in x2APIC mode (Interrupts the CPU delivers itself); a NIC's receive interrupts moderated done (A network), halt polling having turned out to do it by accident; left: the xAPIC page's virtualization, and AMD's AVIC; device work off the first CPU's task, with a lock a device (the ring pages mapped once rather than at every access done, Its memory) -- tried for a NIC, a task of its own on its guest's spare thread, polling with the driver's notifies off, and left out: for a guest of one CPU, the only kind its own cores leave a thread for, whose interrupts come through the 8259 and take it out of its guest all the same, no faster -- dd | nc 2.7-2.8 s against 2.66, BusyBox's httpd 0.42-0.59 s against 0.21; guests with MSI-X and a CPU to spare are where it could pay; nested leaves of 2 MiB and 1 GiB, over guest memory taken in runs that size; the VMX preemption timer, which would take a computing guest out at its timer's edge without the host interrupt that does it now (Time); virtio-net's offloads done both ways (A network): a stream between two guests is a fortieth of the frames it was, and a driver's scatter-gather, which cost a sender of one segment at a time 7% while every ring access mapped a page, 4% since -- inside the spread.
  7. What has not been measured. The time each kind of exit takes inside LinuxGuest::run; fio and iperf in a guest. (An exit under VT-x on silicon is measured now: What an exit costs.)

Lifecycle, and stages 4 and 5

  • A host poweroff or reboot stops every guest as rmmod does (stop_all with no grace): no power button is pressed. Done: the unload presses every button and gives the guests stop_secs= (ACPI).
  • finish and FileDisk::drop wait for their tasks with no deadline: a disk task stuck in a read hangs hv stop, rmmod and the host's shutdown with nothing said. Done for every join in the kernel (Task::wait, Scheduler): a wait still going after ten seconds is reported -- who waits, for which task (hv/vm3, hv/vm3/vda, hv/vm3/cpu1), for how long, and where that task is, its frames named, or the CPU it is on that takes no interrupt -- and again each time the wait has doubled. It still waits: a task that has not exited is still using what its waiter would free.
  • Stage 4 needs what the shell's strings stand in for today: a typed start(Spec) -> Result<id> and status, names, VM definitions kept across a reboot, images handled -- claims, copies -- and quotas.
  • Stage 5's constraints, above, do not hold yet. Guest memory is frames of 4 KiB from the general allocator, with no machine-wide table of who owns them; the devices' timers keep absolute boot_time_ns stamps a new kernel's clock would not continue; the guests run on the host's TSC with no offset; there is no pause and no snapshot of a guest. A first milestone that needs all of it and no kexec: rmmod hv and insmod hv with the guests kept running.

Tests

  • CI runs insn-test.py and hv-fuzz.py on the host and never loads the module. hv-test.py --arch aarch64 can go in as it is; x86 under TCG wants QEMU 9.2 or later for the smp guest, or a way to skip it.
  • hv-linux-test.py and hv-distro-test.py are run by hand; a pinned tinyconfig bzImage and a BusyBox cpio, built once and cached, would put the first in CI.
  • tests/fuzz/hv compiles neither hypervisor/hv/src/{svm,vmx,vm,machine,npt,ept}.rs nor any of hvarch but the VMCB's layout, nor the module's vms, guest, disk and forward, and puts its own memory.rs in the real one's place. Three targets would have caught this review's bugs: the exit decoders over made-up VMCBs and VMCSs (bug 9), a model of the input queue's type_in, requeue and fed_at (bug 7's hv exec), and a second vCPU that keeps re-posting chains (bug 1 -- there now, in the blk and net targets).
  • No gate covers leaks over many starts and stops, a mem= past free memory, sixteen guests, rmmod or poweroff with I/O in flight, a port or a forward used again, one image given twice, or a run of hours.
  • Hardware: VT-x has run on the EX44's silicon by hand (On real hardware), and its gates run under nested KVM; the Dell's Skylake, whose paths -- legacy IBRS written after every exit, the L1D flush -- no other machine here takes, never; the arm64 backend reports and does not enter.