Appendix A: sharing memory between virtual machines

A parcel-handoff record measured crossing between two throwaway KVM guests three ways, shared memory, a vsock socket, and a shared virtio-fs directory, as a latency ladder spanning three orders of magnitude.

⏱ 30 minutesChapter 12Appendices

Learning objectives

By the end of this appendix you can:

  • Name the three ways two guests on one host can hand a record to each other: a shared PCI memory region, a socket, and a shared filesystem.
  • Back ivshmem with a /dev/shm file rather than host HugePages, and still get a data path with no kernel call and no host process in it.
  • Read a round trip timed on the client’s own steady_clock, and say why the one-way figure beside it is half the round trip, labelled as derived rather than measured.
  • Say why a latency-sensitive core polls a shared ring instead of taking an interrupt, even though the interrupt would spend less CPU.
  • Put ivshmem, vsock, and virtio-fs on one latency ladder and match each to the job it fits.

Diagram

Two KVM guest boxes on one host. Three paths connect them: a shared PCI BAR backed by a /dev/shm file with a lock-free ring inside it, drawn as the shortest, most direct path; a vsock socket from guest A to a host echo and back, routed through the kernel; and a shared virtiofs directory, routed through two virtiofsd processes on the host, drawn as the longest path.
Figure A.1: Three paths between the same two guests: a shared memory region with no kernel and no host process in the data path, a vsock socket through the kernel, and a shared virtio-fs directory through two virtiofsd round trips.

Why this matters

Every chapter so far measured scan-to-divert inside one box: one process, one set of cores, one memory space. A sortation line rarely stays that contained. The scanner that reads a parcel’s barcode and the service that decides its chute often run as separate guests on the same physical host, split apart for isolation, for patching on different schedules, or because one of them came from a vendor image neither team wants to touch. The decide step still has a deadline. Crossing a VM boundary to reach it is not free, and the three ways to cross it do not cost the same.

So measure the crossing directly. Send one small parcel-handoff record from a client guest and echo it back, over a shared memory region, over a socket, and over a shared file, each timed the same way. The ladder between them is the finding. The whole lab runs without touching the host: two throwaway Fedora KVM guests boot directly under qemu-system-x86_64 as an unprivileged user, with no libvirt, no sudo, and no change to the host’s kernel or boot parameters, the same constraint every chapter in this guide holds to. The usual treatment of this topic assumes a RHEL real-time guest; this lab runs plain Fedora with no subscription, so nothing here depends on kernel-rt.

The setup

Two guests, named A and B, boot from the same qemu invocation pattern “Taming the host” uses for its own disposable lab, with three devices added to let them talk to each other and to the host:

  • One ivshmem-plain PCI device, -device ivshmem-plain, backed by a file in /dev/shm. This lab uses no host HugePages. /dev/shm is a tmpfs, world-writable here, and ivshmem-plain asks nothing more of it than a regular file an unprivileged qemu process can open and map. Both guests attach the same backing file, so the same bytes of PCI BAR space are visible to both.
  • One vsock device per guest, exposing AF_VSOCK so a guest can open a socket toward the host without any virtual network interface, bridge, or IP address in between.
  • One unprivileged virtiofsd per guest, each sharing a host tmpfs directory into its guest as a virtio-fs mount.

Every one of these is a per-guest qemu command-line device, not a host kernel change: the host supplies a shared-memory file, a vsock transport already built into the kernel it already runs, and a userspace virtiofsd process per guest. None of it asks the host to isolate a core, raise a priority, or load a module it does not already carry.

The three transports, and how each one is measured

Every number in this appendix is a round trip, timed on the client’s own steady_clock so no cross-machine clock skew can enter it. The one-way figure reported beside each round trip is that round trip divided by two, labelled as derived: nothing here ever measures one-way latency directly, because the two guests have no shared clock to measure it against.

ivshmem-plain, the headline lane. Both guests mmap the same PCI BAR, found by walking /sys/bus/pci/devices for a device reporting vendor 0x1af4 and device 0x1110, then opening its resource2 file. A lock-free single-producer single-consumer ring, the same design “Wait-free synchronization” measured inside one process, lives in the mapped region instead of inside one address space: one guest’s request ring, one guest’s response ring, each slot written with a release store and read with an acquire load. No kernel call sits in the data path once the region is mapped, and no host process reads or forwards a single byte of it. The client spins on try_push and try_pop rather than waiting on an interrupt, the same reason a hot path inside one process prefers a wait-free ring to a condition variable: a spin that finds data immediately costs less than the wakeup latency of anything that has to block and be signaled.

ivshmem-doorbell, named but not measured. The same shared region can add MSI-X interrupts through an ivshmem-server process, so a write on one side raises a doorbell that wakes the other side instead of leaving it to poll. That trade runs backward for a latency-sensitive core: an interrupt still has to be delivered, routed to a core, and scheduled in, and all three steps add the jitter that cost a hot path in “Taming the host”: timer ticks, context switches, and IRQs. A core that is already spinning to stay quiet does not want to be interrupted to be told something is ready; it wants to see the ready flag the instant it appears. Polling costs CPU time the doorbell would have saved. The lab spends that CPU and leaves the doorbell variant unmeasured.

virtio-vsock. The client opens an AF_VSOCK socket to VMADDR_CID_ANY on the host side, which answers as an echo. Guest-to-guest AF_VSOCK is not a native path (the protocol routes through the host, not directly between two guests), so this lane measures guest-to-host, not guest-to-guest; everything it costs is the ordinary socket copy and syscall path, connect, send, recv, the same kernel work any TCP socket pays, minus the network stack underneath it.

virtio-fs. A host tmpfs directory is shared into both guests through virtiofsd, mounted with cache=never so a write one guest makes is visible to the other immediately, instead of waiting out an attribute cache timeout the way a cache=auto mount would. The client writes a request file; the echo side polls the directory, reads it, and writes a response file; the client polls for that response. Each ping-pong is several distinct filesystem operations, a write, a directory poll, a read, a write back, a poll, a read, and every one of them is its own round trip through virtiofsd on the host, not one local system call.

Measure

These numbers come from two 2-vCPU KVM guests, so they are VM-shaped, not comparable to bare metal, and they move from run to run with whatever the host scheduler happens to be doing to those vCPU threads at the time. What is stable across runs is the ladder’s order and the size of the gaps between its rungs, not the exact microsecond figures below. All values are microseconds; sample counts match each lane’s own run (virtio-fs took fewer samples because a round trip there runs in milliseconds, not microseconds, so a smaller sample is still representative).

Lane Samples RTT p50 RTT p99 RTT p99.9 One-way p50 (derived) protocol_errors
ivshmem 20000 0.569 0.672 37.99 0.284 0
vsock 20000 163.1 5556 9318 81.6 0
virtio-fs 2000 3380 (3.4 ms) 21924 39411 1690 0

The gaps are the finding. At the median, vsock runs about 287 times slower than ivshmem; virtio-fs runs about 5900 times slower than ivshmem and about 21 times slower than vsock. Three orders of magnitude separate the fastest rung from the slowest, inside one host, for the same 64-byte record. ivshmem’s own p99.9 jumps to 37.99 microseconds from a p50 under a microsecond, a guest-scheduling stall on an otherwise flat distribution; a shared-memory ring removes the kernel and the host process from the data path, but it cannot remove the two vCPU threads underneath it from the host’s own scheduler, the same ceiling “Taming the host” named for a single guest’s own hot path. vsock’s tail stretches further still, p99 at 5556 against a p50 of 163, because every round trip pays a socket copy and a syscall, and any one of twenty thousand can land behind other guest or host scheduling work. virtio-fs holds the widest spread of the three: a p50 already in milliseconds, before any tail is even considered, because every ping-pong is several virtiofsd round trips stacked in sequence, not one shared write.

Trade-offs

Reach for ivshmem when both ends of the handoff are under your control and the deadline is tight enough that a hundred-plus-microsecond socket round trip would already blow it. The cost: a lock-free ring across a shared PCI region is more to build and to get right than opening a socket, and polling spends a core’s own cycles rather than sleeping between messages, the same spend-CPU-to-save-latency trade “Wait-free synchronization” made inside one process. Doorbell-interrupt ivshmem trades some of that CPU spend back for added jitter, so it fits only a workload where the two guests mostly sit idle and an occasional wakeup beats a core that never stops spinning.

Reach for vsock when a zero-config socket is worth the kernel’s own copy and syscall cost, which is most everything that is not itself on the sortation line’s scan-to-divert path: control-plane traffic, health checks, a management connection between two guests that only need to talk occasionally and do not want to provision a shared memory region or a shared directory to do it.

Reach for virtio-fs when the data already is a file and the two guests already read and write it as one, a shared configuration directory, a log drop point, an image or model artifact one guest produces and the other consumes. It is the wrong tool for a hot-path handoff, visible in the milliseconds the ladder shows for a 64-byte record that would cross in well under a microsecond over shared memory.

Past all three of these sits a heavier path this appendix does not measure: DPDK’s vhost-user transport over shared HugePages, which moves a user-space packet ring between a guest and a host-side poll-mode driver at line rate, bypassing the guest kernel’s own network stack entirely. It is the next step past ivshmem for a workload that needs to move packets, not records, at the highest rate a NIC can sustain; this lab’s unprivileged, no-HugePages constraint keeps it out of scope here, named as where this goes next rather than measured alongside the three transports above.

Build, run, observe

cd examples/12-inter-vm-ipc && ./demo.sh build && ./demo.sh provision && ./demo.sh run

run ships the benchmark binary to both guests, runs all three lanes in sequence, and writes one profile-labelled file per lane into results/{ivshmem,vsock,virtiofs}.txt. Read each file for its rtt_p50_us figure first and line the three up against the ladder above; then check protocol_errors=0 on every lane, the count of echoed records that came back with the wrong sequence number, which should read zero on every run this lab produces. A nonzero count there means a lane answered out of order or dropped a record, not merely that it answered late, and is worth more attention than any one quantile.

Exercise it yourself

The section above reports the ladder. This one walks you through producing it on your own machine, one step at a time, with the output to expect at each step and a note on what you are reading. The whole run takes about thirty minutes, most of it the first build and the two guests booting.

Before you start

This demo runs on the two-guest KVM lab. If you have not stood that up yet, the Lab setup page has the full prerequisites (KVM, qemu-system-x86_64, the /dev/kvm, /dev/vhost-vsock, and /dev/shm device nodes, virtiofsd, and the one-time toolchain bootstrap) and the one-time steps. The lab runs as your own user, with no sudo and no change to the host. Clone the repository and work from its root:

git clone https://github.com/patterncatalyst/latency-patterns-in-cpp.git
cd latency-patterns-in-cpp

Step 1: Build the benchmark

The guests run Fedora with an older glibc than a current host, so the benchmark is built with a static libc++ stack (the C library and the loader stay dynamic), the same recipe “Taming the host” uses for its own guest binary. One command builds it:

cd examples/12-inter-vm-ipc
./demo.sh build

It prints the path it wrote and then the binary’s dynamic dependencies:

built: <repo>/build-release-static/examples/12-inter-vm-ipc/cpp/ipc_bench
--- ldd (expect only libc/libm + loader) ---
        linux-vdso.so.1
        libm.so.6 => /lib64/libm.so.6
        libc.so.6 => /lib64/libc.so.6
        /lib64/ld-linux-x86-64.so.2

What you are looking at: the C++ standard library is linked in statically, so it is absent from that list. Only the C library, the math library, and the loader remain dynamic, and every one of those is present on the Fedora guest. That is what lets a binary built on the host run unchanged inside an older-glibc guest.

Step 2: Provision the two-guest pair

./demo.sh provision

This boots guests A and B from one qemu invocation pattern, with the shared ivshmem device, a vsock device each, and a virtiofsd each already attached, then waits until both answer over SSH. It finishes once both guests are reachable. The two guests are disposable: ./demo.sh down at the end removes them and their backing files.

Step 3: Run the three lanes

./demo.sh run

run ships the benchmark to both guests and drives each transport in turn, printing a banner per lane and then the head of each lane’s distribution:

== ivshmem lane ==
== vsock lane (host echo) ==
== virtio-fs lane ==
results written to results/{ivshmem,vsock,virtiofs}.txt
transport=ivshmem
ivshmem_rtt_p50_us=0.569
ivshmem_rtt_p99_us=0.672
ivshmem_rtt_p999_us=37.991
transport=vsock
vsock_rtt_p50_us=163.129
vsock_rtt_p99_us=5556.484
vsock_rtt_p999_us=9318.210
transport=virtiofs
virtiofs_rtt_p50_us=3379.659
virtiofs_rtt_p99_us=21924.329
virtiofs_rtt_p999_us=39411.337

What you are looking at: the ladder from the “Measure” section, straight off your own guests. The exact microseconds will differ from the ones above and from one run to the next, because two 2-vCPU guests share the host scheduler. What holds steady is the order of the three rungs and the size of the gaps between them, three orders of magnitude from the fastest to the slowest for the same 64-byte record.

Step 4: Read a full distribution

The one-line output above is the head of each file. Open a file to see the whole distribution, including the histogram:

cat results/ivshmem.txt
profile_label=ipc-ivshmem
cpu_class=2-vCPU KVM guest
...
protocol_errors=0
ivshmem_rtt_p50_us=0.569
ivshmem_rtt_p99_us=0.672
ivshmem_rtt_p999_us=37.991
# ivshmem rtt histogram (bucket range in microseconds, count, bar)
     0.431 us -    137.468 us | ######################################## 19989
   137.468 us -    274.505 us |  1
   ...

What you are looking at is a full distribution, reported across every quantile with no mean anywhere in the file. Nearly every one of the twenty thousand round trips lands in the first bucket, under a microsecond; a handful scatter out into the tail, which is why p99.9 sits at 37.99 microseconds while p50 stays at 0.569. That long-tail shape is the guest-scheduling stall the “Measure” section named. Check protocol_errors=0 in each of the three files before you trust any quantile: a nonzero count means a lane answered out of order or dropped a record, which matters more than answering late.

Step 5: Run the ring test without a VM

The lock-free ring at the heart of the ivshmem lane has its own in-process tests that need no guest at all. They cover the ring’s edge cases, and the last one drives a producer and a consumer thread over one ring and asserts every record arrives once, in order:

cd ../..            # back to the repo root
ctest --preset default -R ShmRing
    Start 1: ShmRing.TryPopOnEmptyRingReturnsFalse
1/5 Test #1: ShmRing.TryPopOnEmptyRingReturnsFalse ...............   Passed
...
5/5 Test #5: ShmRing.ConcurrentProducerConsumerLosesOrDuplicatesNothing   Passed
100% tests passed, 0 tests failed out of 5

What you are looking at: the correctness of the ring, separated from the latency of the transport. The VM lanes measure how fast the handoff is; ConcurrentProducerConsumerLosesOrDuplicatesNothing proves the handoff never loses or reorders a record under a concurrent producer and consumer, and the whole suite stays clean under the ASan, UBSan, and TSan lanes.

Teardown

cd examples/12-inter-vm-ipc
./demo.sh down

This stops both guests and removes their disk images, the ivshmem backing file, and the shared directories. The host is left exactly as it was before Step 2.

What you learned

  • Two guests on one host can hand a record to each other through a shared PCI memory region, a socket, or a shared filesystem, and the three do not cost the same by a wide margin.
  • An unprivileged lab can still back a shared-memory device with a /dev/shm file instead of host HugePages, with no host kernel change and no sudo on the host.
  • A round trip measured on the client’s own clock avoids cross-machine clock skew; a one-way figure derived from it as half the round trip is a convenience, not a second measurement.
  • A latency-sensitive core polls a shared ring instead of taking a doorbell interrupt, because the interrupt’s own delivery and scheduling cost is exactly the jitter a quiet core is built to avoid.
  • Measured here, ivshmem, vsock, and virtio-fs span three orders of magnitude at the median, from under a microsecond to several milliseconds, for the same 64-byte record on the same pair of guests.

For deeper coverage

  • “ivshmem-spec” (QEMU project): the device specification the ivshmem-plain lane implements against.
  • “virtio-fs” (virtio-fs project): the shared-filesystem transport the virtio-fs lane measures.
  • vsock(7) (Linux kernel documentation): the AF_VSOCK address family the vsock lane connects over, and why guest-to-guest is not a native path within it.

Full citations, with links, are in the bibliography.