Red Hat
AI-assisted summary of Porting KVM to SmartOS - Brian Cantrill, Joyent, KVM Forum 2011 — original source. Check the original for full context.
Source published:
Key ideas
- Joyent ported Linux's KVM subsystem to SmartOS (an illumos/OpenSolaris derivative), combining hardware-assisted virtualization with native enterprise features like ZFS, DTrace, Zones, and Crossbow network virtualization. (0:01)
- The port restricts scope to 64-bit x86 hosts running Intel VT-x with EPT, strictly locking guest physical memory to eliminate unpredictable latency from memory oversell and swapping. (4:13)
- To compensate for illumos's inability to return anonymous file descriptors from ioctls, Joyent introduced the KVM_CLONE ioctl, keeping upstream QEMU diffs down to roughly ten lines of code. (26:30)
- Joyent hardened their deployment model by executing each userland QEMU process inside its own stripped illumos Zone, neutralizing hypervisor escape exploits within an unprivileged container. (30:08)
Detailed notes
## Background Published on YouTube by Red Hat on September 26, 2011, this video features Brian Cantrill, VP of Engineering at Joyent, presenting 'Experiences Porting KVM to SmartOS' at the KVM Forum 2011 in Vancouver, Canada. According to the description, Cantrill covers SmartOS's heritage from OpenSolaris and illumos, the enterprise features it inherits—such as ZFS, DTrace, Zones, and Crossbow—and the detailed engineering hurdles, constraints, and community contributions encountered while porting KVM to the platform.
## TL;DR To bridge the gap in hardware-assisted virtualization on illumos, Joyent ported Linux's KVM subsystem to SmartOS while maintaining userland compatibility with QEMU. The engineering team solved complex early-boot and driver translation challenges—building out 16-bit disassembly in MDB, instrumenting VM exits with DTrace, and untangling severe bugs like thread migration identity swaps and FPU register corruption during memory copies. Joyent deliberately locked down guest memory, encapsulated untrusted QEMU processes inside unprivileged illumos Zones for defense-in-depth security, and harnessed ZFS and Crossbow for scalable I/O and networking. The resulting integration enables high-frequency, out-of-guest observability into guest scheduling and interrupts via hypervisor-level DTrace probes and real-time visual heat maps.
## Atmosphere & style The presentation is electric, hilariously irreverent, and intensely technical, delivered in Brian Cantrill's trademark rapid-fire, animated speaking style. It plays out like a gripping war story from the low-level kernel trenches, replete with dark humor about 'the kiln of pain' and 'the kernel developer suicide hotline' alongside playful banter with audience members like upstream KVM maintainer Avi Kivity. The atmosphere balances terrifying engineering near-catastrophes with sheer technical joy, leaving the audience both laughing and deeply impressed by the audacity of illumos systems engineering.
## Bulletin - [00:01](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1s) Joyent ported Linux's KVM subsystem to SmartOS (an illumos/OpenSolaris derivative), combining hardware-assisted virtualization with native enterprise features like ZFS, DTrace, Zones, and Crossbow network virtualization. - [04:13](https://www.youtube.com/watch?v=cwAfJywzk8o&t=253s) The port restricts scope to 64-bit x86 hosts running Intel VT-x with EPT, strictly locking guest physical memory to eliminate unpredictable latency from memory oversell and swapping. - [26:30](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1590s) To compensate for illumos's inability to return anonymous file descriptors from ioctls, Joyent introduced the KVM_CLONE ioctl, keeping upstream QEMU diffs down to roughly ten lines of code. - [30:08](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1808s) Joyent hardened their deployment model by executing each userland QEMU process inside its own stripped illumos Zone, neutralizing hypervisor escape exploits within an unprivileged container.
## Key takeaways - [02:45](https://www.youtube.com/watch?v=cwAfJywzk8o&t=165s) Joyent and the illumos community believe the operating system itself is the superior hypervisor foundation, avoiding the historical pitfalls of proprietary thin hypervisors. - [04:13](https://www.youtube.com/watch?v=cwAfJywzk8o&t=253s) The port project constrained scope to 64-bit x86 hosts and Intel VT-x with EPT, deprioritizing AMD SVM while preserving QEMU/KVM kernel ABI compatibility. - [06:04](https://www.youtube.com/watch?v=cwAfJywzk8o&t=364s) Rather than emulating the Linux kernel, Joyent directly ported KVM code, using '#ifdef XXX' stubs coupled with DTrace probe traps to expose unported dependencies at runtime. - [09:38](https://www.youtube.com/watch?v=cwAfJywzk8o&t=578s) Overcoming real-mode BIOS hangs required extending MDB with 16-bit disassembly and guest-to-host address mapping, alongside DTrace probes reading VMCS registers. - [14:15](https://www.youtube.com/watch?v=cwAfJywzk8o&t=855s) Severe early debugging hurdles included lost CPU identity during thread migration due to corrupted GS_BASE registers and silent memory corruption from an FPU save routine clearing CR0.TS. - [18:56](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1136s) An apparent 5% performance advantage for SmartOS KVM over Linux KVM was debunked when traced to dynamic overclocking from Intel Turbo Boost and ambient temperature shifts. - [21:47](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1307s) Memory oversell and kernel same-page merging (KSM) were deliberately omitted to prevent latency spikes, leaving high-density multi-tenancy to native illumos Zones instead. - [26:30](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1590s) The custom KVM_CLONE ioctl bridged illumos's driver model with QEMU's per-vCPU file descriptor expectations without extensive changes to upstream QEMU. - [27:13](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1633s) KVM vCPU preemption hooks were mapped to illumos context ops (ctxops), and hypervisor timers were backed by the high-resolution cyclic subsystem. - [28:47](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1727s) ZFS integration eliminated the need for userland image formats like QCOW2, unlocking instant snapshot cloning, ARC-backed read caching, and WAN-based replication. - [30:08](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1808s) Isolating QEMU instances inside dedicated OS Zones ensured that hypervisor break-out vulnerabilities were trapped inside an unprivileged sandbox. - [31:14](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1874s) Crossbow VNICs provided guest networking with out-of-the-box hardware rate limiting, anti-spoofing enforcement, and fine-grained bandwidth accounting. - [32:22](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1942s) Instrumenting KVM with DTrace and the newly ported kvmstat exposed hypervisor bottlenecks, including high exit frequencies caused by console screen blanking timeouts. - [35:46](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2146s) Hypervisor-level high-frequency sampling of the guest %cr3 register allowed real-time visualization of guest process scheduling and priority adjustments without in-guest agents. - [38:18](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2298s) Joyent proposed community collaboration centered on cross-pollinating performance findings from production DTrace analysis and developing an automated test farm with quirky operating systems like IBM OS/2.
## Detailed walkthrough ### [00:01](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1s) Introducing SmartOS, illumos, and Inherited Strengths
Brian Cantrill introduces himself as the VP of Engineering at Joyent, presenting their experiences porting KVM to SmartOS at the KVM Forum 2011. SmartOS is an operating system derived from illumos, which is the community-driven, truly open-source fork of OpenSolaris. Cantrill jokes about Oracle's stewardship following the Sun acquisition, quipping:
> “lumos is a true open source Fork of open Solaris U and has been um aided enormously by by Oracle seeming to wanting to drive uh employees out of Oracle sabotage the operating system and so on it's been great for the open source effort so thank you again Larry”
As an illumos derivative, SmartOS inherits several battle-tested, enterprise-grade capabilities developed over years of production deployment:
* **ZFS (Zettabyte File System):** An enterprise-class storage stack. Cantrill defines "enterprise grade" by noting that engineers have walked the trail of tears and suffered in the "kiln of pain" to handle the Byzantine, failure-prone behaviors of real-world storage hardware. ZFS has since spread beyond Solaris to FreeBSD and Mac OS. * **DTrace:** A comprehensive facility for dynamic, ad-hoc system instrumentation. * **OS-Based Virtualization (Zones/Containers):** First-class, highly contained operating system virtualization operating at native hardware speeds, functioning like "jails on growth hormone" to enable high multi-tenancy density. * **Crossbow (Network Virtualization):** A complete virtual NIC infrastructure delivering fine-grained bandwidth management and resource control.
```mermaid flowchart TD accTitle: SmartOS Ancestry and Core Technologies accDescr: Diagram tracing SmartOS heritage from OpenSolaris through illumos, showing the key inherited features.
subgraph Heritage["Lineage"] OS["OpenSolaris"] -->|"True Open Source Fork"| IL["illumos"] IL --> SO["SmartOS (Joyent)"] end
subgraph Features["Inherited Enterprise Features"] SO --- F1["ZFS (Storage stack)"] SO --- F2["DTrace (Dynamic tracing)"] SO --- F3["Zones (OS-based virtualization)"] SO --- F4["Crossbow (Network virtualization)"] end ```
[02:45](https://www.youtube.com/watch?v=cwAfJywzk8o&t=165s) The Missing Piece and the Hypervisor Philosophy
Despite this broad feature set, SmartOS lacked hardware-based virtualization. Intel and AMD have made hardware-assisted virtualization practical and performant, which opened the door to closing this gap. Cantrill outlines Joyent's foundational architectural belief:
> “we emphatically believe um we joint um we I would I dare say the lumos Community emphatically believe that the best hypervisor is the operating system that is to say anyone attempting to implement a quote unquote thin hypervisor I won't name any proprietary names but we all know who I'm thinking of anyone who attempts to implement a quote-unquote thin hypervisor will go ahead and repeat 20 years of os implementation history and I think that we would all we can all agree that that's actually the wrong path to take”
KVM shared and pioneered that exact philosophy, demonstrating that an existing general-purpose kernel makes the best foundation for virtualization. Recognizing KVM as best-of-breed—backed by strong competitive SPEC performance numbers and an active community—Joyent decided that porting KVM to SmartOS was an imperative.
[04:13](https://www.youtube.com/watch?v=cwAfJywzk8o&t=253s) Scoping the Port and Architecture Boundaries
Treating the port like an ordinary user-space program was impossible. To make the work tractable, Joyent deliberately constrained the scope:
* **Host Architecture:** Joyent focused exclusively on 64-bit x86 (`x86_64`) host support. While Cantrill notes potential edge interest in 32-bit x86 for low-power architectures like Intel Atom, 64-bit was the firm priority. * **Guest Support:** Strictly limited to `x86` (32-bit) and `x86_64` guests. Despite Cantrill's fond nostalgia for RISC after spending 14 years at Sun, platforms like POWER7 were deliberately left out of scope. * **CPU Virtualization Extensions:** They focused exclusively on Intel VT-x with EPT (Extended Page Tables) for immediate business and resourcing reasons (noting Joyent is Intel-backed, though joking Andy Grove wasn't leaning on them), while being careful not to preclude future AMD SVM support. * **Compatibility Target:** While Joyent was willing to diverge from KVM's internal implementation details to accommodate illumos conventions, maintaining strict compatibility with the userland QEMU/KVM kernel ABI was paramount. Cantrill highlights that projects like `kvmtool` creating alternative userlands actually help firm up this kernel-user interface for everyone.
[06:04](https://www.youtube.com/watch?v=cwAfJywzk8o&t=364s) Early Engineering Strategy and the DTrace Trapdoor
KVM was explicitly designed around Linux kernel primitives rather than portability. Joyent immediately ruled out trying to emulate Linux kernel functionality—the approach taken by the FreeBSD Google Summer of Code 2007 effort—because illumos internals diverge far too deeply. Instead, because KVM's Linux 2.6.34 foundation was solid and proven in worldwide production, Joyent diverged cleanly from the Linux implementation while preserving the ability to import future community improvements.
Getting the code to compile was a massive, inherently serial effort. In late fall 2010, Joyent engineer Max Bruning took on the challenge alone:
* **Pre-processor XXX Fencing:** Max temporarily bypassed unported Linux code by wrapping large blocks in `#ifdef XXX`. * **DTrace Detection Traps:** Rather than leaving missing blocks silent, Joyent inserted `#else` branches containing custom DTrace probes parameterized with `__FILE__` and `__LINE__`. * **Dynamic Gap Tracing:** Whenever the system hit unported code during execution, custom DTrace scripts immediately flagged the exact source file and line number that triggered the failure, making missing dependencies visible as they were hit.
By late March 2011, Max succeeded in launching a VM. Initially running for only three instructions, it quickly advanced to running indefinitely without panicking the host kernel. However, the guest did no actual work—getting stuck in the real-mode BIOS code. In early April 2011, Robert Mustacchi and Brian Cantrill joined Max to parallelize debugging, building specialized introspection tooling to observe guest execution and diagnose the early-boot hang.
[09:38](https://www.youtube.com/watch?v=cwAfJywzk8o&t=578s) Tooling Enhancements: MDB, 16-Bit Disassembly, and DTrace Probes
To make progress on bringing up KVM, the team had to significantly enhance their debugging toolkit. Brian Cantrill explains that they added new capabilities to MDB (Modular Debugger), their primary postmortem and in situ debugger for both kernel and userland. First, they added support in MDB to map guest physical frame numbers (PFNs) to QEMU virtual addresses (VAs). Second—much to Cantrill's astonishment—they had to implement 16-bit disassembly support. Cantrill laughs that he swore he would never live to write 16-bit disassembly, let alone do it not as an act of pedantry, but to crack an honest-to-God real problem. Pairing the address mapping with 16-bit disassembly allowed them to disassemble the BIOS and trace execution directly. Armed with DTrace probes, they could see the CPU stepping through an eight-instruction sequence where programmed I/O (PIO) had been botched, enabling them to fix the issue and get execution back on track.
```mermaid flowchart TD accTitle: Debugging Guest BIOS with MDB and DTrace accDescr: Flow showing how MDB enhancements and DTrace probes uncovered programmed IO failures in 16-bit guest BIOS. subgraph MDB_Enhancements["MDB Enhancements"] M1["Map Guest PFNs to QEMU VAs"] M2["16-bit Disassembly Support"] end subgraph DTrace_Probes["DTrace VM Instrumentation"] D1["Probes on VM-entry and VM-exit"] D2["vmregs built-in variable to read VMCS"] end MDB_Enhancements --> TRACE["Disassemble & Step Guest BIOS Execution"] DTrace_Probes --> TRACE TRACE --> BUG["Pinpoint screwed-up Programmed I/O (PIO)"] ```
In addition to MDB improvements, the team placed DTrace probes across VM-entry and VM-exit paths. A pivotal feature was exposing VM state directly inside DTrace scripts via a newly introduced `vmregs` variable. This permitted developers to programmatically extract the exact hardware registers stored within the Virtual Machine Control Structure (VMCS) while debugging a specific transition. Cantrill remarks that while the debugging cycle sounds clean in hindsight—finding a blocking bug caused by an unported piece, pulling that piece in, and iterating—the emotional reality was starkly different: “Every time you're actually scared out of your mind that this is the bug that is actually going to put you out of business, this is the one that is actually you're not going to be able to find.”
[11:25](https://www.youtube.com/watch?v=cwAfJywzk8o&t=685s) The "XXX" Metric, Booting Milestones, and haiku Appreciation
Tracking the port's trajectory can be seen through a commit-history graph of unresolved placeholders (`XXX` comments) across the codebase. Early in the port, Max Bruning struggled just to get the source tree compiling, causing the `XXX` count to steadily climb. The count spiked when whole missing source files were pulled into the tree entirely commented out with `XXX` markers. By April, the tide turned: code was pruned, missing pieces were cleanly filled, and the `XXX` count plummeted.
```mermaid flowchart LR accTitle: Milestones in Porting KVM to SmartOS accDescr: Sequence of operating system milestones reached during the SmartOS KVM port. M1["1. Boot kmdb (Guest Kernel Perspective)"] --> M2["2. Boot Linux (Terrifying 10-Day Bug Hunt)"] M2 --> M3["3. Boot Windows"] M3 --> M4["4. Boot Haiku (Clock & Stress Validation)"] ```
The first major operational milestone was booting `kmdb` (the in situ Illumos kernel debugger) inside a guest VM, which gave the engineers direct visibility into architectural state from the guest’s own perspective. That breakthrough accelerated everything. Soon after, they booted Linux, though getting it running required what Cantrill calls "the 10 most terrifying days of my life," feeling more like several agonizing years of troubleshooting self-inflicted wounds. After Linux, they booted Windows, and shortly thereafter, Haiku OS. Cantrill pauses to lavish praise on Haiku as an operating system testing target, highlighting how useful its eccentric behavior is for hardware virtualization testing: “Haiku does such weird [stuff] to the system, you know it... runs the clock really high, it just does a bunch of weird stuff, and so we—I love Haiku, man, I think Haiku is awesome.”
- The commit graph of `XXX` tags reflected the three development phases: compilation stubs, sudden spikes when entire files were imported, and systematic burndown as functional logic was finalized. - Booting `kmdb` provided architectural visibility into guest execution that eliminated reliance on external blind tracing alone.
[13:11](https://www.youtube.com/watch?v=cwAfJywzk8o&t=791s) Upstream Code Quality and the Lone QEMU Signal Bug
Cantrill notes that despite months of deep testing, the SmartOS engineers sent almost no bug fixes upstream to KVM. He emphasizes that as inherently cynical systems engineers, they were shocked by how clean the code was: “In the course of this port, we did not discover a single bug that you would call a bug in KVM.” He pays tribute to Avi Kivity and the upstream KVM community for building a remarkably solid system.
The only defect they discovered across both KVM and QEMU was an issue where QEMU invoked `signal()` instead of `sigaction()` when handling `SIGIPI`. Cantrill jokes about the long, tortured historical debate over `signal()` versus `sigaction()`, reminding the audience that `signal()` should never be used to set a disposition to anything other than `SIG_IGN` or `SIG_DFL`. Because Linux and Illumos implement slightly different signal semantics under those conditions, the call failed on Illumos; otherwise, both codebases performed flawlessly.
[14:15](https://www.youtube.com/watch?v=cwAfJywzk8o&t=855s) Self-Inflicted Wounds: Thread Migration and the Swapped CPU Identity
Cantrill details the brutal "self-inflicted wounds" that occupied that terrifying week of getting Linux to boot. One bizarre issue stemmed from QEMU configuration, but another critical bug centered on thread migration and the CPU base register `GS_BASE`. In Illumos, `GS_BASE` points to the per-CPU state (`cpu_t`), whereas Linux relies on a different mechanism. During an interaction with Avi Kivity in the audience, Avi asks how Illumos manages it; Cantrill notes that when using `GS_BASE` for per-CPU pointers, Illumos must restore it across thread migrations. Avi interjects that if Illumos hits that, Linux might have a bug as well, prompting Cantrill to joke, “Oh my god, I feel so happy!”
This bug surfaced under sustained system load when a kernel thread migrated to another physical CPU, but its `GS_BASE` register was not properly restored. Cantrill explains the catastrophic and surreal consequence: > “I had two different CPUs, one of which believed that it was the other from a software perspective.”
Because the per-CPU pointer defines identity—telling the core what thread it is executing and who it is—the CPU executed code while operating under a completely false perception of its own identity. The kernel threw nonsensical assertion failures when a CPU believed it was running on a completely different core across the machine. Cantrill points out that after 15 years of operating system work, this was a totally unprecedented failure mode. The team ultimately solved it using DTrace postmortem instrumentation, running a trace buffer during execution and extracting the postmortem trace directly out of the crash dump when the kernel panicked.
[16:37](https://www.youtube.com/watch?v=cwAfJywzk8o&t=997s) FPU Save Side Effects and Floating-Point Memory Corruption
A second major self-inflicted wound arose from replacing Linux kernel functions with native Illumos primitives. In the upstream KVM code, saving floating-point state executed an `FXSAVE`. The Illumos port replaced this with the internal Illumos kernel FPU save helper. However, the Illumos function did not merely execute `FXSAVE`; it also explicitly cleared the Task Switched (`TS`) bit in control register zero (`CR0`).
Under standard x86 kernel conventions, clearing the `TS` flag prevents the CPU from raising a Device Not Available (`#NM`) fault on subsequent floating-point instructions. Operating systems rely on `#NM` exceptions to lazily reload a thread's floating-point context. Because the `TS` bit was cleared prematurely, threads executed floating-point instructions without trapping to reload their saved register state, silently operating on whatever stale garbage remained in the physical FPU registers.
Because optimized string and memory routines like `memcpy()` utilize floating-point or SSE registers to move large buffers, threads constantly trampled one another's data. This manifested as bizarre build errors inside a guest VM, such as corrupted compiler object files. Cantrill jokes that when you encounter that brand of low-level corruption, you find yourself looking for the "kernel developer suicide hotline" to be talked down off the roof.
```mermaid flowchart TD accTitle: Mechanism of FPU Memory Corruption Bug accDescr: Sequence diagram illustrating how clearing TS in CR0 led to silent floating-point register corruption during memcpy operations. A["Illumos FPU save routine called"] --> B["Executes FXSAVE"] B --> C["Clears TS bit in CR0"] C --> D["Task switch occurs to new thread"] D --> E["Thread calls memcpy using FP/SSE registers"] E --> F{"Is TS bit set?"} F -- "No (#NM suppressed)" --> G["FPU state never reloaded"] G --> H["Thread operates on stale FPU register data"] H --> I["Silent data corruption in memory / object files"] ```
[18:02](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1082s) CPU Benchmark Parity and the "5% Faster" Mystery
When testing CPU performance using pure compute benchmarks (such as SPEC CPU), the SmartOS port delivered identical speeds across bare metal, Linux KVM, and SmartOS KVM. However, reaching this expected parity uncovered another head-scratcher: in initial testing, SmartOS KVM was dead-reproducibly 5% *faster* than Linux KVM.
Cantrill remarks that experienced engineers know how dangerous such "good" benchmark surprises can be: “Those of you that have done benchmarking know that this is how tough benchmarking is, 'cause, hey, you're 5% faster, hey, go home! It's like, no, that doesn't make sense... we're all talking to the same hardware here, we can't be 5% faster.” The test machines shared identical Intel processors, motherboards, memory, and hardware configurations, meaning any performance delta had to be investigated rather than celebrated as a false triumph.
- Pure CPU workloads showed absolute performance equivalence across bare metal, Linux KVM, and SmartOS KVM once configuration differences were understood. - Unexplained speedups on identical physical hardware were treated with skepticism rather than accepted at face value.
[18:56](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1136s) Cracking the Benchmark Discrepancy: Intel Turbo Boost
Brian Cantrill recounts how the Joyent engineering team was initially puzzled by erratic benchmark numbers between Linux KVM and their ported version on SmartOS. The mystery was cracked by Brandon Grant, who realized that the systems were exhibiting dynamic overclocking through Intel's Turbo Boost technology on the Nehalem architecture. Cantrill cautions anyone conducting performance comparisons to keep this hardware feature turned off. Because Turbo Boost scales CPU frequency dynamically based on ambient temperature and operating conditions—while the Time Stamp Counter (TSC) frequency remains constant—it produces wildly confusing benchmark variations unless true CPU frequencies are checked via ACPI registers.
Once Turbo Boost was disabled across the test systems, the anomalies vanished. Cantrill quips, “I would love to tell you that we're 5% faster but we're not so when we went to turn that off everyone was the same speed which was a relief.” The overarching goal of Joyent's benchmarking was not necessarily to claim a performance victory, but simply to verify that they had avoided breaking anything after suffering several self-inflicted wounds along the development path. A Sysbench MySQL benchmark demonstrated that bare-metal performance sat at the top, while Linux KVM and SmartOS KVM tracked each other with virtually identical, statistically indistinguishable numbers.
- Dynamic overclocking (Intel Turbo Boost) distorted early benchmark runs due to ambient temperature variations. - TSC frequency stays static despite frequency throttling or boosting, making raw cycle counting unreliable without reading ACPI registers. - Sysbench MySQL results proved SmartOS KVM matched Linux KVM throughput, with only minor crossover points that Cantrill attributed to slight differences in CPU scheduling.
---
[20:18](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1218s) Port Status, Availability, and the Windows 7 Surprise
Joyent announced the public availability of their KVM port on GitHub, accompanied by a lightly patched branch of QEMU 0.14.1. From Joyent's perspective and defined scope, the port is already at or near production quality for Intel VT-x. However, Cantrill points out an important caveat: if the target hardware relies on AMD SVM, it is completely unsupported and therefore not production-ready.
Cantrill shares an amusing anecdote that occurred just forty-five minutes after releasing the code that morning. The team behind OpenIndiana—another distribution based on illumos—pulled the freshly published bits and successfully booted a Windows 7 guest. The Joyent team had previously verified Windows Server 2008 R2 and other variants, but had not yet tested Windows 7 itself. Seeing an OpenIndiana user post a screenshot of Windows 7 booting cleanly produced a huge sigh of relief among the engineers, proving the code was immediately usable in the wild.
- Source code published to a dedicated public GitHub repository. - Companion QEMU branch based on version 0.14.1 with minimal diffs. - Supports Intel VT-x hardware virtualization; AMD SVM is currently completely absent. - OpenIndiana community validated the release within 45 minutes by booting Windows 7.
---
[21:47](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1307s) Architecting Around Multi-Tenancy: The Decision Against Memory Oversell
Cantrill turns to the deliberate limitations and trade-offs made in their KVM port, foremost among them being that guest memory is strictly locked down. Because Joyent operates as a large-scale cloud provider serving tens of thousands of customers across thousands of physical servers, their architectural decisions are heavily guided by practical operations. In high-density multi-tenant environments, memory oversell works reasonably well for completely idle VMs, but falls apart when active tenants heavily stress their systems. The unpredictable, variable latency introduced by swapping and paging overhead simply does not justify the marginal revenue.
As a result, failing to lock down guest memory on SmartOS will cause VM initialization to fail. While this constraint could be solved in software, Joyent has no business interest in pursuing it, preferring to leave memory oversell implementations to outside community contributors. Cantrill argues that when massive density is required, hardware virtualization is fundamentally the wrong tool. While hardware virtualization is indispensable for running arbitrary, heterogeneous operating systems, operating-system-level virtualization (illumos Zones) provides a far lighter footprint. In production, Joyent packs up to 400 active tenants onto a single 2U server with 96 GB of RAM using Zones—a density feat that hardware-assisted hypervisors cannot replicate regardless of tuning.
```mermaid flowchart TD accTitle: Joyent Virtualization Strategy by Workload accDescr: Diagram contrasting high-density OS-level Zones with hardware-level KVM virtualization on SmartOS. subgraph Host["SmartOS Physical Host (e.g., 2U Server, 96 GB RAM)"] subgraph OSLevel["OS-Level Virtualization (Zones)"] Z["Single illumos Kernel"] Z --> Z1["Tenant Zone 1"] Z --> Z2["Tenant Zone..."] Z --> Z400["Tenant Zone 400"] end subgraph HWLevel["Hardware-Assisted Virtualization (KVM)"] K["KVM Subsystem"] K --> K1["Guest OS (Linux)"] K --> K2["Guest OS (Windows)"] K --> LCK["Guest Memory Locked Down\n(No Oversell / No Paging)"] end end ```
- Guest physical memory is locked down at startup; inability to allocate and lock memory aborts instance launch. - Memory oversell is rejected as a business and engineering anti-pattern due to tail latency under heavy multi-tenant loads. - illumos Zones handle platform-as-a-service density (up to 400 tenants per 2U machine with 96 GB RAM), whereas KVM is reserved for workloads requiring foreign OS kernels.
---
[23:28](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1408s) Community Dialogue: Memory Deduplication and Nested Virtualization
Cantrill addresses the absence of kernel same-page merging (KSM) or memory deduplication in SmartOS KVM. While technically feasible within illumos, Joyent does not face an urgent need for it due to their locked-memory philosophy. Cantrill solicits feedback from the audience regarding real-world deduplication savings. An audience member explains that systems like Windows XP aggressively zero out freed memory rather than utilizing it for disk cache, allowing KSM to collapse millions of zero pages and identical shared text segments into single physical pages—yielding substantial savings in virtual desktop infrastructure (VDI) deployments. Cantrill acknowledges the merit for VDI and notes that if implemented, deduplication would be added generically at the illumos kernel level.
The discussion then moves to nested virtualization, which SmartOS does not support. Cantrill expresses skepticism about supporting nested VT-x due to the immense complexity and ugly edge cases in Intel's virtualization hardware design, noting that AMD's SVM handles nested states far more cleanly. When Cantrill asks the audience whether nested virtualization is actually used in production or remains an internal development toy, an attendee quips that “it's currently a solution looking for a problem,” noting that the code is notoriously complicated and easily puts developer minds into a deadlock. Cantrill agrees that while nested virtualization would be wonderful to have inside tools like VMware Fusion for developer testing, the maintenance burden does not warrant Joyent implementing it for production workloads.
- Memory deduplication (KSM equivalent) is omitted in SmartOS, though acknowledged as valuable for collapsing zero pages and shared binaries in Windows/VDI environments. - Joyent expressed concern regarding the continuous background CPU scanning overhead associated with page deduplication. - Nested virtualization on Intel VT-x was deemed too complex and brittle, with audience consensus confirming it is primarily used for developer test harnesses rather than production deployments.
---
[26:30](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1590s) QEMU Divergences and the `KVM_CLONE` ioctl
Cantrill highlights the divergences between upstream Linux KVM and their SmartOS implementation, specifically focusing on interactions with QEMU. Joyent's primary design goal for QEMU was to minimize the patch footprint on top of the upstream codebase. Under Linux, KVM relies on an internal kernel capability (`anon_inode_getfd`) to create a new file descriptor directly from inside a driver's ioctl handler, enabling a clean one-to-one mapping between an open file descriptor and a virtual CPU (vCPU).
Because illumos lacks a kernel mechanism to manufacture an anonymous file descriptor from inside a device driver's `ioctl` routine, Joyent had to rethink the vCPU dispatch model. They briefly considered passing the vCPU target as an explicit parameter to every single ioctl, but that would have caused massive drift from upstream QEMU. Instead, they reverted that change and engineered a targeted compromise: they introduced a custom `KVM_CLONE` ioctl. This ioctl instructs the kernel driver to point its internal state to another instance, accompanied by roughly ten lines of specialized code in QEMU to manage vCPU instantiation cleanly without disrupting the broader KVM subsystem conventions.
- Upstream Linux KVM relies on `anon_inode_getfd` inside `ioctl` to return new file descriptors representing each vCPU. - illumos does not permit arbitrary file descriptor creation from within an in-flight driver ioctl. - Joyent avoided rewriting QEMU ioctl interfaces by creating a custom `KVM_CLONE` ioctl, restricting changes to approximately ten lines of QEMU setup logic.
[27:13](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1633s) Context Ops and Timers: Bridging Illumos and KVM
Brian Cantrill details how Illumos handles vCPU management cleanly at the userland-kernel boundary: QEMU reopens `/dev/kvm`, calls `KVM_CLONE` on the new instance specifying the previous one, and creates a vCPU on it, with built-in kernel protections preventing multiple vCPUs per single instance. Although this required a tiny bit of `#ifdef` in QEMU that they would prefer to avoid, the abstraction works smoothly.
Cantrill highlights a minor technical divergence involving Illumos "context ops" (`ctxops`), an old facility designed to virtualize CPU performance counters. As an aside, he jokes about the original motivation: > “In part because we were trying to understand a microprocessor that was enormously non-competitive, which was SPARC, so we really needed every bit we could get.”
In KVM, these context ops map cleanly to the semantics of `kvm_sched_in` and `kvm_sched_out`, giving the kernel a hook to run code right as a vCPU is preempted or scheduled off-CPU.
```mermaid flowchart TD accTitle: vCPU Scheduling and Timers in SmartOS accDescr: Mapping between Illumos primitives and KVM virtualization facilities
subgraph CtxSub["Context Operations"] CO["Illumos ctxops"] -->|"maps to"| SC["kvm_sched_in / kvm_sched_out"] SC -->|"notifies when"| OffCPU["vCPU taken off-CPU"] end
subgraph TimeSub["Cyclic Timers"] CSub["Cyclic Subsystem<br/>(Late 1990s high-res timer)"] -->|"configured as"| OS["Dynamically reprogrammable one-shots"] OS -->|"powers"| KT["KVM Timers"] KT -->|"vCPU moves CPU"| Poke["Poke target CPU via cross-call<br/>(No cyclic migration)"] end ```
For timers, Cantrill points back to the arbitrary-resolution interval timer facility he personally implemented in the late 1990s—the `cyclic` subsystem. Originally built for high-resolution interval events and used to drive the system clock itself, cyclics can bind to CPUs or processor sets and fire at distinct interrupt levels. Having been updated to support dynamically reprogrammable one-shots, all KVM timers on SmartOS run directly on cyclics. The only divergence from Linux is that when a vCPU migrates between physical CPUs, SmartOS does not migrate the cyclic; it simply pokes the target CPU from the existing cyclic handler.
---
[28:47](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1727s) ZFS Integration: Replacing QCOW2 and Boosting IO
Moving to storage, Cantrill explains that Joyent did not modify ZFS at all to support KVM; an administrator simply creates a ZFS volume (zvol), points QEMU at it, and lets it run. However, bringing ZFS to KVM solves major storage headaches. With a light jab at earlier conference talks, Cantrill remarks: > “By using ZFS, you get a couple of enhancements, for one you can stop the experiment of the user level file system in QCOW2, which was tough to sit through... I mean it's very earnest work and I don't mean anything against the presenters.”
ZFS gives KVM several immediate architectural benefits: - **Instant Snapshots and Clones:** Constant-time cloning of instances on the fly while the VM is live and running, which Joyent relied on heavily during test cycles. - **Unified Caching via the ARC:** The Adaptive Replacement Cache (ARC) caches guest I/O efficiently within host DRAM, unlocking massive potential performance improvements for random I/O depending on spatial and temporal locality. - **Wide-Area Migration:** ZFS remote replication (`zfs send`/`receive`) provides a robust foundation for offloading VM cloning and migration across WAN environments.
---
[30:08](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1808s) Containment and Security: Trapping QEMU in Zones
While SmartOS does not mandate that KVM instances execute inside OS-level virtualization, Joyent chose to run every QEMU process isolated inside its own exclusive zone (container). Initially, this was chosen purely for operational mechanics: resource accounting, Quality of Service (QoS), I/O throttling, and billing isolation.
However, this design paid massive security dividends when hypervisor escape exploits surfaced at Black Hat: > “If you somehow burrow out into QEMU, in our implementation you just find yourself having burrowed out into a much larger, much more secure prison, which is a container.”
Cantrill commends the KVM community, pointing out that the reported vulnerabilities were not in KVM itself, but inside userland QEMU. By wrapping QEMU entirely within an Illumos zone with stripped privileges—fewer privileges than an ordinary container—any guest breakout compromises only an empty sandbox, drastically shrinking the attack surface.
```mermaid flowchart LR accTitle: Joyent Security Containment Model accDescr: A guest breakout into QEMU is stopped by the Illumos container jail
subgraph Guest["KVM Guest"] GApp["Guest Payload / Exploit"] end
subgraph Zone["Illumos Container (Zone)"] QEMU["QEMU Process<br/>(Sole process in Zone)"] end
subgraph Host["SmartOS Host Kernel"] KVM["KVM Kernel Driver"] HostCore["Host OS / Other VMs"] end
GApp -->|"Hypervisor exploit breakout"| QEMU QEMU -.->|"Trapped! Lacks privileges"| Zone Zone x-..-x|"Blocked from accessing"| HostCore QEMU <-->|"ioctl"| KVM ```
---
[31:14](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1874s) Network Virtualization via VNICs
SmartOS brings deep OS-level network virtualization into the guest stack. For every KVM instance, SmartOS provisions a dedicated virtual NIC (VNIC) and attaches it to VirtIO through simple glue layers. Cantrill notes they set a baseline goal to push 1 Gbps to and from a guest; once that worked reliably, they moved on to other challenges.
Beyond raw throughput, VNICs grant capabilities that are complicated and fragile to configure under Linux with `iptables` and `ebtables`: - **Anti-Spoofing:** Built directly into the VNIC configuration; the interface only transmits packets matching its assigned MAC address, dropping spoofed packets automatically. - **Flow Management and Rate Limiting:** Administrators can carve a physical 10 GbE pipe cleanly into ten 1 Gbps slices across guests, ensuring no single tenant floods the link. Cantrill emphasizes this is critical in parts of the developing world where upstream bandwidth is strictly metered and premium-priced. - **Observability:** Granular host-side bandwidth, throughput, and error accounting per VNIC and therefore per guest out of the box.
---
[32:22](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1942s) Observability: kstats, KVM Stat, and the Blanking Mystery
To bring low-overhead instrumentation to KVM, the port translates Linux's internal `kvm_vcpu_stat` structure directly into the Illumos `kstat` (kernel statistics) framework. Cantrill pushed a dedicated `kvmstat` tool upstream that consumes these statistics and prints real-time, per-second, per-vCPU throughput and exit counters.
Cantrill shares an entertaining debugging story encountered while analyzing new VM boots: > “We were seeing that when a machine first booted it would take 1,300 exits per second, and then as we were debugging it, it would go away. And then, what the hell, you go reboot the instance and then it would come back: 1,300 exits per second. And we're debugging and debugging and debugging, it would go away, and finally Josh Wilsdon—who's a Joyent engineer, he's in the room—Josh is like, ‘Wait a minute, I wonder if this is due to the screen blanking?’”
Sure enough, the mystery load traced directly to the five-minute console screen blanker timeout, which triggered repetitive EPT (Extended Page Table) violations as the guest console repeatedly refreshed or wiped video memory before going idle.
---
[33:45](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2025s) DTrace Integration and Cloud Real-Time Analytics
Cantrill highlights the historical irony that QEMU 0.14 already contained DTrace provider probes upstream, despite never having run on a platform that actually supported native DTrace—the probes were originally added to satisfy Linux's SystemTap tracepoints. SmartOS enabled these dormant probes, lighting them up immediately.
```mermaid flowchart TD accTitle: DTrace Observability Stack for KVM accDescr: QEMU and KVM probes feeding into DTrace and Cloud Analytics
subgraph Instrumentation["Tracepoints & Probes"] QP["QEMU USDT Probes<br/>(Originally added for SystemTap)"] KP["KVM SDT Probes<br/>(Replaced trace_* calls)"] VR["vm_regs Accessors<br/>(Dynamic register inspection)"] end
subgraph Engine["Tracing Engine"] DT["DTrace Engine<br/>(Zero probe effect when disabled)"] end
subgraph Visualization["Analytics Pipeline"] KS["kvmstat CLI"] RA["Joyent Real-Time Analytics<br/>(Cloud-wide Heatmaps & Visualizations)"] end
QP --> DT KP --> DT VR --> DT DT --> KS DT --> RA ```
Additionally, Joyent replaced all kernel `trace_*` invocations in KVM with Statically Defined Tracing (SDT) probes, granting absolute zero probe effect when uninstrumented. Combined with custom DTrace subroutines to read guest virtual registers (`vm_regs`), operators can dynamically slice hypervisor behavior per VM, per thread, and per exit reason without taking the guest down.
Running a basic D script aggregating guest exits by PID, TID, and exit code on a simple `fork`/`exec`/`exit` loop revealed an unexpected discovery: > “When you start a Linux process, it executes CPUID three times in userland... Maybe that's faster, maybe there's no other way to do it. I was surprised by that... We were seeing 8,000 exits per second running this workload that just forks, execs, and exits.”
Cantrill concludes this section by demonstrating Joyent’s cloud-scale real-time visualization platform wired up to these KVM DTrace probes. Displaying a heat map of `ext3` write offsets over time (with logical block offset on the Y-axis and wall time on the X-axis), he illustrates how the system exposes guest file system behaviors—such as the sequential ascending sweeps across platters as a guest program writes, deletes, and rewires 3 GB data blocks.
[35:46](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2146s) Peeking into the Guest via CR3 and Sub-Second Visualizations
Brian Cantrill shifts into a series of visualizations showing what can be deduced about guest behavior purely from the hypervisor layer looking up. While the host kernel cannot directly read the guest's internal process table to know what process is executing by name, it does have direct access to the `cr3` register, which holds the guest MMU context and page table base address. Because `cr3` values correlate strongly with distinct processes, the host can monitor thread and process scheduling within the guest simply by tracking changes in `cr3` hex values over time. Cantrill displays a visualization of a single-vCPU guest running two compute-bound workloads: the machine sits idle initially, and then the Linux scheduler begins alternating between the two tasks.
```mermaid flowchart LR accTitle: Inferring Guest Scheduling via Host MMU Context accDescr: Host samples guest cr3 register at high frequency to visualize guest scheduling without guest cooperation.
subgraph Host["SmartOS / Host Hypervisor"] DTrace["DTrace Sampling<br/>(999 Hz)"] CR3["Read Guest %cr3<br/>(MMU Context)"] Viz["Sub-second Visualization<br/>(Time vs. Sub-second Offset)"] end
subgraph Guest["KVM Guest VM"] Sched["Linux Scheduler"] P1["Process A<br/>(%cr3 = 0x67d800)"] P2["Process B<br/>(%cr3 =...)"] end
Sched --> P1 Sched --> P2 CR3 -.->|"inspects context"| Sched DTrace --> CR3 CR3 --> Viz ```
To push this technique further, Cantrill increases the sampling frequency to 999 Hz and modifies process priorities with `nice`. When one compute-bound workload is reniced, it immediately drops off and only surfaces sporadically, producing striking visual stair-step patterns. “I'm sure there's a not a doctoral thesis, but maybe a master's thesis, probably an undergraduate thesis waiting to be written on what's going on there,” Cantrill quips. He explains the geometry of the visualization: the x-axis represents elapsed time, while the y-axis shows the sub-second offset of each sample. If each vertical strip were rotated 90 degrees and tiled end-to-end, it would reveal the raw Linux scheduling pattern (e.g., yellow process, blue process, yellow, blue), identifying them only by hex markers like `0x67d800`.
- Sampling guest MMU context (`cr3`) allows host-side tracing of guest context switches without installing in-guest monitoring agents. - Adjusting `nice` levels yields distinct visual shifts in the sub-second scheduling frequency bands. - Cantrill also highlights a heat map of IRQ requests broken down by sub-second offset and interrupt vector, revealing rigid horizontal bands for absolute periodic timer vectors, diagonal bands for relative timers, and smeared distributions representing non-deterministic I/O interrupts.
---
[38:18](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2298s) Proposals for KVM Community Collaboration
Cantrill turns to how Joyent hopes to collaborate with the broader upstream KVM community, highlighting three concrete areas of common interest:
1. **KVM Performance and Shared Diagnostics:** Cantrill notes that because SmartOS and Linux KVM implementations share so much underlying hypervisor architecture, performance optimizations identified via DTrace on SmartOS are likely to directly benefit Linux KVM as well. As Cantrill forcefully frames their common goal: “Let's work together and let's just let's go kick the snot out of proprietary hypervisors by understanding KVM better and better and better on arbitrary guests in production.” 2. **Collaborative Testing and Oddball OS Images:** Joyent hopes to assemble an automated test farm of exotic and legacy operating system ISOs. Recalling an old school friend who was an early engineer at VMware, Cantrill relates that VMware internally considered themselves ready to ship only once they successfully booted IBM OS/2, because OS/2 took extreme, unorthodox liberties with every architectural corner of x86. Having an automated test harness with OS/2 would provide high confidence in hypervisor correctness. 3. **Benchmarking and Standard Workloads:** Cantrill mentions SPECvirt_sc2010, though he admits his own fraught relationship with the organization: “SPEC and I have a long and complicated history with one another; it's like a girlfriend with whom I had a violent breakup.” While Joyent is interested in standardizing virtualization benchmarks, Cantrill clarifies that benchmarking is lower priority for them than performance diagnostics and deep test coverage.
---
[39:58](https://www.youtube.com/watch?v=cwAfJywzk8o&t=2398s) Acknowledgments and Conclusion
Cantrill wraps up his presentation by extending thanks to several people and teams who made the SmartOS KVM port possible:
- **Josh Wilsdon and Robert Mustacchi** from Joyent, who were sitting in the room and were instrumental in the porting and implementation work. - **Brendan Gregg** for his extensive performance analysis, heat map visualizations, and profiling. - **Fabrice Bellard**, whom Cantrill calls “the unspoken spirit in the room, for lighting the path with QEMU.” - **Intel** for providing fast processors and hardware virtualization primitives like Extended Page Tables (EPT). - **Avi Kivity and the upstream KVM team** for architecting and maintaining KVM. - **The illumos community** for their enthusiastic support of the platform.
## Notable quotes > [30:08](https://www.youtube.com/watch?v=cwAfJywzk8o&t=1808s) If you somehow burrow out into QEMU, in our implementation you just find yourself having burrowed out into a much larger, much more secure prison, which is a container. — Brian Cantrill
## Mentioned Brian Cantrill, Joyent, KVM Forum, Red Hat, SmartOS, illumos, OpenSolaris, Oracle, Larry Ellison, ZFS, DTrace, Crossbow, Intel, AMD, KVM, QEMU, FreeBSD, Mac OS, kvmtool, Max Bruning, Robert Mustacchi, MDB, Haiku OS, Avi Kivity, Linux, Windows, Windows Server 2008 R2, Windows 7, OpenIndiana, Brandon Grant, Sysbench, MySQL, VMware Fusion, Josh Wilsdon, Brendan Gregg, Fabrice Bellard, SPECvirt_sc2010, OS/2, IBM
## Video description Brian Cantrill, vice president of Engineering at Joyent, presents "Experiences Porting KVM to SmartOS" at the KVM Forum 2011 in Vancouver, Canada.
Cantrill talks about SmartOS, a derivative of a truly open source fork of OpenSolaris called Illumos. Key functionality inherited from OpenSolaris/Illumos includes enterprise-grade CFS, dtrace, OS-based virtualization, and network virtualization. Hardware-based virtualization is an ongoing project, though there have been advances by Intel and AMD in this space.
Cantrill goes over the process and pains of porting KVM to SmartOS, the limitations and standards of their work, and the roadblocks they encountered along the way. He highlights contributions from members of the Illumos community as well as on-going innovation.
More information about the KVM Forum: http://www.linux-kvm.org/page/KVM_Forum_2011
Presented by Red Hat, Inc.
[Source](https://www.youtube.com/watch?v=cwAfJywzk8o)