Chapter 19 · Part VII
virtio-net without a networking entitlement
Course progress: chapter 19 is 20 of the 26 chapters written so far (numbering starts at 00)
Warm-up: three questions from earlier chapters
Answer each one in your head or on paper before you open its answer. They change on each visit.
From chapter 18: virtio-blk: a root filesystem that persists
A virtio-blk request header reads, as little-endian fields,
type = 0,reserved = 0,sector = 16, and the chain carries one 4096-byte writable data buffer and a 1-byte writable status. Which bytes of the image file does the device read, and whatlengoes in the used ring when it succeeds?Show answer
Type 0 is IN (a read). The offset is
16 × 512 = 8192, so it reads bytes 8192 to 12287 of the file (4096 bytes, eight sectors). The usedlencounts the bytes the device wrote into guest memory: 4096 data bytes plus the status byte, 4097.From chapter 18: virtio-blk: a root filesystem that persists
A guest asks to read 512 bytes at
sector = 2^55. Why cansector * 512 + len <= capacitypass in C, and what must the device answer instead?Show answer
2^55 × 512 = 2^64, which wraps to 0 in 64-bit arithmetic, so the check sees offset 0 and passes, and the device would read sector 0, a sector the guest did not ask for. Withchecked_mulandchecked_addthe overflow is an error, and the device answers the statusIOERR(1) without touching the file. (In Rust with overflow checks on, the plain*panics instead: a guest-triggered crash.)From chapter 18: virtio-blk: a root filesystem that persists
A request's last descriptor is device-readable, so there is no writable byte anywhere in the chain. Why does the device not answer
IOERR, and what does it do?Show answer
The status byte is the last writable byte of the chain; with none, there is nowhere to write any answer, so
IOERRcannot be delivered. The chain breaks the protocol itself, so the device setsDEVICE_NEEDS_RESET(chapter 15) and stops using the queue until the driver resets it. A bad sector number, by contrast, is answered withIOERRand the queue carries on.From chapter 18: virtio-blk: a root filesystem that persists
The driver accepted
VIRTIO_BLK_F_FLUSH. A guestOUTrequest completes with status OK. Is the data on the Mac's drive yet, and what makes it so?Show answer
Not necessarily: with FLUSH negotiated the device is write-back, and an OUT is a
pwriteinto the host's page cache. The data is durable only after a later FLUSH request completes, which our device answers OK only afterFile::sync_all,fcntl(F_FULLFSYNC)on macOS, returned success. Without FLUSH negotiated the device must be write-through and sync after every OUT.From chapter 18: virtio-blk: a root filesystem that persists
A guest sends request type 11 (a type our device does not implement). What does it answer, and why is that different from the answer for a write to a
,rodisk?Show answer
Unknown types get
UNSUPP(2): "I do not know this request". An OUT on a read-only disk getsIOERR(1): the request is understood but cannot be done. Neither resets the device; both are ordinary answers the driver handles. The device also offersVIRTIO_BLK_F_ROfor a,rodisk, so a correct driver never sends the write at all.From chapter 18: virtio-blk: a root filesystem that persists
You start a second
macvmmwith--disk disk.imgwhile a first one is running on the same file. What happens, and why does a crashed first VMM not leave the file locked forever?Show answer
The second one prints
disk image is lockedand exits with code 2 before creating a VM: every--disktakes anflock(exclusive for read-write, shared for,ro) on its open file. The lock belongs to the open file, so the kernel releases it when the process's file descriptor closes, which also happens when a process dies. It is advisory: a program that never callsflockis not stopped.From chapter 18: virtio-blk: a root filesystem that persists
Your VMM answers FLUSH by doing nothing. You
kill -9it right after the guest'sdd ... conv=fsyncreturns. Are the guest's bytes in the image file?Show answer
Yes. The device already handed them to macOS with
pwrite; they sit in the host's page cache, which belongs to the kernel, not to our process, so killing the process loses nothing. Only a power cut or a kernel crash before the drive wrote them shows the difference. That is why the no-op FLUSH passes every test: the experiment shows latency, not corruption.From chapter 18: virtio-blk: a root filesystem that persists
GET_IDarrives with a 64-byte writable data buffer. How many bytes does our device write there, and what are they?Show answer
Twenty at most (the virtio-blk ID is 20 bytes):
macvmm-disk0for the first--disk, padded with zero bytes. It writesmin(20, buffer length)bytes, and the usedlenis those bytes plus 1 for the status. Linux shows the string in/sys/block/vda/serial.From chapter 16: Split virtqueues: shared memory with an adversary
A queue of size 8 last served up to
next_avail = 0xFFFE. The device now loadsavail.idx = 0x0002. How many new requests are there, and in which ring slots are their heads?Show answer
Four:
0x0002 - 0xFFFEin wrappingu16arithmetic is 4 (0x10002 - 0xFFFE). The slots are the indices modulo 8:0xFFFE & 7 = 6, then 7, 0 and 1. Nothing special happens at the wrap, because the indices are free-running counters and only the slot is reduced modulo the size.From chapter 16: Split virtqueues: shared memory with an adversary
Same queue,
next_avail = 0, and the device loadsavail.idx = 9. What does it do, and why is "serve 9 requests" wrong?Show answer
It refuses: the queue is marked broken and the transport sets
DEVICE_NEEDS_RESET. Only 8 slots exist, so an honest driver can never be more than 8 requests ahead; a jump of 9 (or 65535) is a broken or hostile driver, and looping over it would re-serve stale slots or burn time the guest chose.From chapter 16: Split virtqueues: shared memory with an adversary
The driver places a size-256 used ring at
0x4000_5002. Which check refuses it, and how many bytes would the ring have needed?Show answer
The alignment check: the used ring must be 4-byte aligned, and
0x...02is not. Had it been aligned, the ring needs6 + 8 × 256 = 2054bytes (flags, idx, 256 elements of{id, len}, andavail_event), all inside one RAM region, computed withchecked_mulandchecked_add.From chapter 16: Split virtqueues: shared memory with an adversary
Descriptor 0 of a size-8 queue is
{addr: 0x0900_0000, len: 8, flags: 0, next: 0}. Every number fits its field. Why does our walker refuse it, and what would a device that accepted it do?Show answer
0x0900_0000is the PL011's MMIO window, not RAM, socheck_rangefails and the walker returnsBufferOutOfRam. A device that accepted it would read or write its "buffer" through whatever lives at that address: a guest could aim the device's own memory accesses at device registers or firmware, the bug class our copy-only, RAM-only memory API exists to rule out.From chapter 16: Split virtqueues: shared memory with an adversary
A chain is
[0: writable, NEXT → 1],[1: readable]. Each descriptor passes its own checks. What doesinto_validatedreturn, and why does the order matter?Show answer
ReadableAfterWritable. The spec has the driver put every device-readable buffer before every device-writable one, so a device can read the whole request before it writes any reply. A device that accepted the mixed order would have to guess which part is the header and which the reply, and a naive one writes its reply into a buffer the guest meant only to be read.From chapter 16: Split virtqueues: shared memory with an adversary
Why can a walker stop a self-looping chain by counting hops instead of remembering which descriptors it visited, and what is the limit?
Show answer
A legal chain uses each descriptor at most once, so it can never be longer than the table: N hops for a queue of size N, or
len / 16inside an indirect table. A walk that wants hop N + 1 must have revisited something, which is a loop or a chain no driver may build. A counter needs no allocation whose size the guest chooses.From chapter 16: Split virtqueues: shared memory with an adversary
A device validates
desc.len, then later readsdesc.lenfrom guest memory again to decide how much to copy. Name the bug and the fix.Show answer
A double fetch, the TOCTOU (time of check to time of use) bug: another guest vCPU can change
lenbetween the check and the use, so the device uses a length it never checked. The fix is to copy the whole descriptor once withread_obj, validate the copy, and use only the copy.From chapter 16: Split virtqueues: shared memory with an adversary
Which two guest-memory accesses of the split ring are ordered, and what does each one order?
Show answer
The acquire load of
avail.idx, which keeps every later read (ring entries, descriptors, buffers) after it, so we see what the driver wrote before it published the index; and the release store ofused.idx, which keeps every earlier write (the used element and the buffer data) before it. Everything else is a plain copy. A fullSeqCstfence also sits between ourused.idxstore and our load ofavail.flags.From chapter 16: Split virtqueues: shared memory with an adversary
The device wrote 150 bytes into a request whose writable buffers total 200. What goes in the used element's
len, and what goes wrong if you put 200?Show answer
150, the bytes actually written. The driver trusts
len: with 200 it would treat 50 bytes the device never wrote, whatever was in that memory before, as data, for example as random numbers or as file contents.From chapter 12: Why an interrupt controller, and why in the kernel
A device tree node says
interrupts = <0 5 4>under a GICv3. Which INTID will the device's interrupt arrive as, and how is it triggered?Show answer
INTID 37. The first cell 0 means SPI (shared peripheral interrupt), and SPI n is INTID 32 + n, so SPI 5 is INTID 37. The third cell 4 means level-sensitive, active high.
From chapter 12: Why an interrupt controller, and why in the kernel
The
/timernode lists<1 11 4>for the virtual timer. Which INTID is that, and why is it not an SPI?Show answer
INTID 27. The first cell 1 means PPI (private peripheral interrupt), and PPI n is INTID 16 + n. Each CPU has its own timer, so its interrupt is private to that CPU and lives in that CPU's redistributor, not in the shared distributor.
From chapter 12: Why an interrupt controller, and why in the kernel
An interrupt handler reads
ICC_IAR1_EL1and gets 1023. What happened, and should it writeICC_EOIR1_EL1?Show answer
1023 is the spurious INTID: nothing was pending by the time the CPU asked (another CPU took it, or the line dropped). There is nothing to handle and nothing was made active, so the handler returns without an end-of-interrupt write.
From chapter 12: Why an interrupt controller, and why in the kernel
Your VMM calls
hv_gic_createright after creating vCPU 0. What comes back, and where must the call go instead?Show answer
An error,
HV_BUSYon our Mac (beforehv_vm_createit isHV_NO_DEVICE). The GIC must be created after the VM and before any vCPU, because each vCPU gets its own redistributor and CPU-interface state when it is created.From chapter 12: Why an interrupt controller, and why in the kernel
A UART model raises its level line when a byte arrives but never lowers it. The guest's handler reads the byte and writes EOI. What does the guest see next?
Show answer
The same interrupt again, at once, forever: at EOI the GIC sees the line still high and makes it pending again. The guest makes no progress (an interrupt storm). The device must lower the line when the cause is gone: the FIFO drained, the cause cleared in
ICR, or the source masked inIMSC.From chapter 12: Why an interrupt controller, and why in the kernel
GicSpi::newis asked to wire INTID 27 to a device. What does it answer, and why is refusing at machine build time better than lettinghv_gic_set_spifail later?Show answer
It refuses with
NotAnSpi: 27 is a PPI (the virtual timer), outside the SPI range 32..1020. Refusing at build time turns a wiring bug into a start-up error with a message; a later failure would happen on a path the guest triggers (every UART access) and could only be logged and ignored.From chapter 12: Why an interrupt controller, and why in the kernel
A 2-vCPU machine puts its redistributors at
0x080A_0000. How much space must the GIC node's secondregentry cover, and where does vCPU 1's redistributor start?Show answer
Two frames of 128 KiB (
0x2_0000), so0x4_0000bytes. The second frame starts at0x080C_0000; the frames follow the order in which the vCPUs were created, so the guest finds its own by reading each frame's affinity.From chapter 12: Why an interrupt controller, and why in the kernel
The chapter 11 timer guest made 10 VTIMER and 10 WFI exits for ten 100 ms sleeps. How many of each does the same workload make with the in-kernel GIC, and why?
Show answer
Zero of each. The kernel delivers the virtual timer's interrupt through its own GIC and handles WFI by parking the vCPU until an interrupt is pending, so neither event needs our VMM. What remains are the exits our devices cause, such as UART register accesses.
From chapter 12: Why an interrupt controller, and why in the kernel
A key arrives while the guest's only vCPU sleeps in WFI under the in-kernel GIC. Which thread raises the interrupt, and what does it call?
Show answer
The stdin reader thread: it pushes the byte into the UART model, which recomputes its level and calls
hv_gic_set_spi(33, true)through itsIrqLine. That call works from any thread and wakes the vCPU inside the kernel; no kick and no VM exit is needed.
Concepts you'll need
Chapters before this one: chapter 18, virtio-blk: a root filesystem that persists.
- Core, taught here: virtio-net and its two queues; the 12-byte
virtio_net_hdr; frame-size caps; drop-and-count; theNetBackendtrait;Companionthreads; theunixgrambackend and its checks; why "no network entitlement" is not containment. - Core, from earlier: the test initramfs and
Ctrl-A x(chapters 09 and 14); the second quit signal (chapter 09);QueueNotifyandDEVICE_NEEDS_RESET(chapter 15);into_validatedand copy-then-validate (chapter 16); the worker thread and--stats(chapters 11 and 17); counted failure (chapter 18); rate-limited warnings (chapter 08). - Primers (read first):
unix-sockets(datagram sockets, socket files and their permissions, stale sockets,ENOBUFS, checking a sender);codesign-entitlements(its "going deeper" section on restricted entitlements). - Pointers: Ethernet, ARP (Address Resolution Protocol), IPv4 and ICMP (body text and an Aside); network offloads (an Aside);
vmnet.framework(a link); the macOSsampletool andnc(a sentence at first use). - Forward definitions: the macOS sandbox and the startup umask (chapter 25); several vCPUs sharing one device (chapter 20).
Two Linux guests on one Mac, with no network anywhere: no Wi-Fi, no cable, no network permission for the program that runs them. The first pings the second five times, gets five answers, then sends it 32 MiB, and both print the same sha256. Along the way, the second guest's virtual machine monitor (VMM) threw away six frames its guest asked it to send, counted them, and carried on. Is that a bug? And where did the packets that did arrive travel?
This chapter finishes row 8 of chapter 00's problem ledger, bulk I/O at reasonable cost, with the fourth virtio device: a network card. By the end, two of your virtual machines (VMs) talk Ethernet through two socket files, and you can say which frames were lost and why.
Objectives: by the end you can
- Implement virtio-net: the 12-byte header with
flagsandgso_typechecked,F_MAC, transmit chains capped at 12 + 1514 bytes, and a receive path that drops and counts instead of blocking. - Design a
NetBackendtrait and implement--net unixgram:LOCAL,peer=REMOTE[,mac=..]over Unix datagram sockets in a private directory, so two VMs talk with no entitlement and no root. - Predict, then observe, what a guest does with frames framed by a 10-byte header instead of 12.
- Diagnose, from a
sampleof a hung VMM, why a device that waits for its guest deadlocks it. - Explain why
vmnet.frameworkis not on the default path, and why "no network entitlement" is not containment.
Before you start. From the repository root, run scripts/learner start 19; it copies this chapter's journal to learner/journal/19.md. You need .cache/macvmm/Image-virt and .cache/macvmm/initramfs-test.img from chapter 14. Two sittings of about 3 hours: the device and its host-only tests, up to the "Good place to stop" marker; then the wire, the runs and the break, at your Mac.
A network card is two queues
A network card moves packets between the operating system and a wire, each as an Ethernet frame: a 14-byte header (destination address, sender address, and a two-byte type saying what follows, such as IPv4, Internet Protocol version 4) and up to 1500 bytes of payload, so at most 1514 bytes (a real wire adds a 4-byte checksum, which never crosses virtio). Each address is a MAC address (media access control address), six bytes such as 02:6d:76:00:00:01, one per network interface card (NIC). A leading 02 marks a locally administered address, which no manufacturer owns. To send to 10.0.0.2, a guest first needs that address's MAC, so it broadcasts an ARP request (Address Resolution Protocol), "who has 10.0.0.2?", to ff:ff:ff:ff:ff:ff, and the owner replies with its MAC.
Aside
Inside a frame sit more headers. An IPv4 header carries addresses like 10.0.0.2; an ICMP message (Internet Control Message Protocol) is what ping sends. ARP is RFC 826.
A virtio network card, virtio-net (device ID 1, virtio 1.2 section 5.1), does this job through two virtqueues. Queue 1, the transmit queue, works like virtio-console's: the guest posts a chain holding one frame and rings the doorbell. Queue 0, the receive queue, works like virtio-rng's: the guest posts empty, device-writable buffers ahead of time, and the device fills one whenever a frame arrives.
We offer two feature bits: VERSION_1, and F_MAC (bit 5): the 6-byte configuration space holds the card's MAC. Every other feature stays off. (In code comments, a number such as 5.1.2 is a virtio 1.2 section.)
/// `receiveq1` (§5.1.2).pub const RX_QUEUE: usize = 0;/// `transmitq1` (§5.1.2).pub const TX_QUEUE: usize = 1;/// `VIRTIO_NET_F_MAC` (§5.1.3): the config space holds the device's MAC.pub const F_MAC: u64 = 1 << 5;/// The features offered (module docs).pub const NET_FEATURES: u64 = features::VERSION_1 | F_MAC;/// The size of `struct virtio_net_hdr` with `VERSION_1` (§5.1.6).pub const HDR_LEN: usize = 12;/// The longest TX chain accepted: one header and one full frame.pub const MAX_TX_CHAIN: usize = 1526;/// The shortest TX chain accepted: one header and an Ethernet header. The frame rule only/// requires/// `≥ 12`; a frame shorter than its own Ethernet header could only be dropped by the peer, so/// it is dropped (and counted) here instead.pub const MIN_TX_CHAIN: usize = 26;/// The config space: `mac[6]` only (§5.1.4; `status`, `max_virtqueue_pairs` and `mtu` exist only/// with features we do not offer).pub const NET_CONFIG_LEN: u32 = 6;Twelve bytes in front of every frame
Every buffer, in both directions, starts with a struct virtio_net_hdr (virtio 1.2 section 5.1.6). With VERSION_1 it is always 12 bytes, little-endian:
| Offset | Field | With no offload negotiated |
|---|---|---|
| 0 | flags (1 byte) | the driver must send 0 |
| 1 | gso_type (1 byte) | the driver must send 0, "no segmentation" |
| 2 | hdr_len (2) | ignored |
| 4 | gso_size (2) | ignored |
| 6 | csum_start (2) | ignored |
| 8 | csum_offset (2) | ignored |
| 10 | num_buffers (2) | on transmit the driver writes 0; on receive the device writes 1 |
The last field has a history: before virtio 1.0, a device without "mergeable receive buffers" (an offload, in the Aside below) used a 10-byte header with no num_buffers. On transmit we check flags and gso_type, because a non-zero value would ask us to do work to the frame; num_buffers means nothing to a device on transmit, so we do not look.
/// The TX header rule (§5.1.6.2 with no offload negotiated): `flags == 0` and/// `gso_type == GSO_NONE`. The other fields carry no meaning without offloads and are ignored.fn header_ok(hdr: &[u8]) -> Result<(), TxDrop> { let flags = hdr.first().copied().unwrap_or(0xff); let gso_type = hdr.get(1).copied().unwrap_or(0xff); if flags != 0 || gso_type != 0 { return Err(TxDrop::Header { flags, gso_type }); } Ok(())}It is handed a slice of a copy, never guest memory; the transmit section shows why. Here is an ARP request from VM A, the first virtual machine in this chapter's runs, as the device sees it:
offset bytes field0 00 flags: 01 00 gso_type: 0, no segmentation2 00 00 00 00 00 00 hdr_len, gso_size, csum_start: unused8 00 00 csum_offset: unused10 00 00 num_buffers: 0 on transmit12 ff ff ff ff ff ff Ethernet destination: broadcast18 02 6d 76 00 00 01 Ethernet source: VM A's MAC24 08 06 EtherType 0x0806: ARP26 00 01 08 00 06 04 00 01 ARP: Ethernet, IPv4, sizes 6 and 4, request34 02 6d 76 00 00 01 0a 00 00 01 sender MAC, sender IP 10.0.0.144 00 00 00 00 00 00 0a 00 00 02 target MAC unknown, target IP 10.0.0.2Frame dissector
Split one virtio-net buffer into its 12-byte header, Ethernet, ARP or IPv4 and ICMP fields, then see what macvmm's device and the receiving guest do with it.
Runs in browserOpen full page: Frame dissectorLoading the lab. If nothing appears, your browser may have JavaScript turned off or the lab failed to load.
Aside
The ignored fields exist for offloads, work the guest hands to the device. Checksum offload: the guest leaves a TCP (Transmission Control Protocol) or UDP (User Datagram Protocol) checksum blank, and csum_start and csum_offset say where the device must store it. Segmentation offload: the guest hands over one packet of up to 64 KiB, and gso_type and gso_size say how to cut it into frames. Mergeable receive buffers: one received packet may fill several buffers, and num_buffers says how many. Each makes the device faster and makes it trust more guest-written numbers.
Predict Suppose the device strips a 10-byte header from every transmitted frame, as an old device would, while the guest's driver writes 12. VM A pings VM B. Does B's guest see (a) valid packets, (b) corrupted packets it complains about, or (c) nothing at all? What do the first 14 bytes B reads look like for the ARP broadcast above?
Write your guess and one sentence of reasoning under ## Predict in your journal. The section "Two bytes off" runs it.
Transmit: copy once, check the copy, never punish the guest
A frame to send arrives like every virtio request: the guest writes a chain, rings QueueNotify, and the device's worker thread from chapter 17 processes the transmit queue. In learner/crates/vmm/src/virtio/net.rs, the heart of process_tx, once per chain:
let Some(chain) = a.tx.pop(mem)? else { break;};// Structure only: the hop budget bounds the walk; the length rule is// the device's own and a violation is a drop, not NEEDS_RESET.let req = chain.into_validated(u64::MAX)?;match Self::tx_one(mem, &*self.backend, &req)? { Ok(len) => { bump(&self.counters.tx_packets, 1); bump(&self.counters.tx_bytes, len as u64); } Err(why) => { bump(&self.counters.tx_dropped, 1); crate::guest_warn!("virtio-net: TX frame dropped: {why:?}"); }}a.tx.add_used(mem, req.head, 0)?; // a TX chain has nothing for us to writeused = true;Every chain goes back on the used ring with length 0: a transmit chain gives the device nothing to write. A dropped frame is a counter and a rate-limited warning, never an error. Only a broken ring (a loop, an index jump, a buffer outside RAM) reaches a ? and puts the device into DEVICE_NEEDS_RESET. A bad frame vanishes, as on Ethernet, and TCP resends it.
So into_validated gets u64::MAX as its cap, unlike chapter 16's tight limits: an over-long frame is a dropped packet, not a broken ring. The length rule lives in tx_one, checked before anything is allocated; the hop budget still bounds the walk:
/// Send one popped TX chain: shape and length first, then **one** copy out of guest memory,/// then the header check on the copy, then the backend (module docs). Returns the/// frame length sent, or why it was dropped. A guest-memory failure (memory changed shape/// under a validated chain) is the only `Err`.fn tx_one( mem: &dyn GuestMemoryOrdered, backend: &dyn NetBackend, req: &super::ValidatedChain,) -> Result<Result<usize, TxDrop>, VirtioError> { if !req.writable.is_empty() { return Ok(Err(TxDrop::Writable)); } let total = req.readable_len; if total < MIN_TX_CHAIN as u64 || total > MAX_TX_CHAIN as u64 { return Ok(Err(TxDrop::Length(total))); }A chain with a device-writable descriptor is refused, and the total must lie between 26 (header plus a bare Ethernet header) and 1526 (header plus 1514). Then one copy:
// `total` ≤ 1526 (checked above), so this allocation is bounded by us, not the guest. let len = usize::try_from(total).map_err(|_| VirtioError::Device("tx length"))?; let mut pkt = vec![0u8; len]; let mut off = 0usize; for d in &req.readable { let n = usize::try_from(d.len).map_err(|_| VirtioError::Device("tx length"))?; let end = off.checked_add(n).ok_or(VirtioError::Device("tx length"))?; let dst = pkt .get_mut(off..end) .ok_or(VirtioError::Device("tx chain longer than its total"))?; mem.read(GuestAddress(d.addr), dst) .map_err(|e| VirtioError::Queue(e.into()))?; off = end; } let (hdr, frame) = pkt.split_at(HDR_LEN); if let Err(why) = header_ok(hdr) { return Ok(Err(why)); } match backend.send(frame) { Ok(()) => Ok(Ok(frame.len())), Err(_) => Ok(Err(TxDrop::Send)), }}The bytes are copied out of guest memory once, into pkt, and the header is checked on the copy: chapter 16's copy-then-validate, since the running guest could rewrite the header between a check and a send. The backend gets the frame without its header.
Security
The guest controls every descriptor's address and length and all 12 header bytes. It does not control how much we allocate (at most 1526 bytes), how often we read each byte (once), or whether a bad packet stops the device (never). Without the cap, guest lengths would size a host allocation.
Receive: frames arrive whenever they like
Transmit starts when the guest rings. A received frame arrives at any moment, into a buffer the guest must have posted in advance. So where does it wait if no buffer is posted?
Before the device sees it, a frame waits in the host socket's receive buffer, inside the macOS kernel. Once the device has it, it goes into a posted buffer at once or is dropped. A real NIC with an empty receive ring does the same (Linux counts rx_missed_errors). We call it drop-and-count: discard, bump a counter, let the guest's protocols recover. Waiting instead is this chapter's deliberate break.
/// Deliver one received frame into the next posted RX chain (module docs). Drops are/// counted and returned as an outcome; only a malformed ring is `Err` (the caller reports/// it: NEEDS_RESET).pub fn receive(&mut self, frame: &[u8]) -> Result<RxOutcome, VirtioError> { if !(ETH_MIN_FRAME..=ETH_MAX_FRAME).contains(&frame.len()) { bump(&self.counters.rx_dropped_len, 1); crate::guest_warn!( "virtio-net: RX datagram of {:?} bytes dropped (not 14..=1514)", frame.len() ); return Ok(RxOutcome::BadLength); } // No driver yet, reset, receiveq not ready, or NEEDS_RESET: there is no buffer to use. let usable = self .active .as_mut() .filter(|a| a.rx.ready() && !a.irq.needs_reset()); let Some(a) = usable else { bump(&self.counters.rx_dropped_no_buffer, 1); crate::guest_warn!("virtio-net: RX frame dropped: device or receiveq not ready"); return Ok(RxOutcome::NoBuffer); }; let mem = &*a.mem; let Some(chain) = a.rx.pop(mem)? else { bump(&self.counters.rx_dropped_no_buffer, 1); crate::guest_warn!("virtio-net: RX frame dropped: no receive buffer posted"); return Ok(RxOutcome::NoBuffer); };A datagram outside 14 to 1514 bytes is not a frame (rx_dropped_len). A device not set up, in DEVICE_NEEDS_RESET, or with an empty receive queue has no buffer (rx_dropped_no_buffer). Otherwise there is a posted chain:
let req = chain.into_validated(u64::MAX)?; let need = HDR_LEN .checked_add(frame.len()) .ok_or(VirtioError::Device("rx length"))? as u64; let outcome = if !req.readable.is_empty() || req.writable_len < need { bump(&self.counters.rx_dropped_small, 1); crate::guest_warn!( "virtio-net: RX frame dropped: chain has {:?} readable descriptors and {:?} \ writable bytes, needs 0 and {need:?}", req.readable.len(), req.writable_len ); a.rx.add_used(mem, req.head, 0)?; RxOutcome::ChainUnusable } else { // A fresh buffer per frame: the zeroed header, num_buffers = 1, the frame. let mut pkt = vec![0u8; HDR_LEN]; if let Some(nb) = pkt.get_mut(10..12) { nb.copy_from_slice(&1u16.to_le_bytes()); } pkt.extend_from_slice(frame); let written = req.write_writable(mem, &pkt)?; a.rx.add_used(mem, req.head, written)?; // what was actually written bump(&self.counters.rx_packets, 1); bump(&self.counters.rx_bytes, frame.len() as u64); RxOutcome::Delivered }; if a.rx.should_interrupt(mem)? { a.irq.signal_used(); } Ok(outcome)}A chain that is readable, or too small for 12 + the frame, goes back unused with length 0 (rx_dropped_small). Otherwise the device writes a header of zeros except num_buffers = 1, then the frame, and reports exactly the bytes written. Every counter shows up in --stats:
/// The NIC's counters (`--stats`), shared by the device, its RX thread and the stats line.#[derive(Debug, Default)]pub struct NetCounters { tx_packets: AtomicU64, tx_bytes: AtomicU64, tx_dropped: AtomicU64, rx_packets: AtomicU64, rx_bytes: AtomicU64, rx_dropped_no_buffer: AtomicU64, rx_dropped_small: AtomicU64, rx_dropped_len: AtomicU64,}The seam: NetBackend
The device needs two things from the host, "send this frame" and "give me the next frame": a trait, NetBackend, in learner/crates/vmm/src/net/backend.rs:
/// A host-side frame transport for one NIC (module docs for the contract).pub trait NetBackend: Send + Sync { /// Send one Ethernet frame. An `Err` means the frame was dropped; the caller counts it. fn send(&self, frame: &[u8]) -> io::Result<()>; /// Receive one frame into `buf` and return its length, or an error after at most /// [`RECV_TIMEOUT`] (`WouldBlock`/`TimedOut`: nothing arrived; `PermissionDenied`: a /// datagram arrived and the backend dropped it, already counted). fn recv(&self, buf: &mut [u8]) -> io::Result<usize>; /// Datagrams dropped because they did not come from the configured peer. Cumulative for the /// lifetime of the backend, which spans in-process reboots. fn rx_dropped_foreign(&self) -> u64 { 0 }}The contract is in the timings. send runs on the worker with the device mutex held, so it gives up after 10 ms and the frame is dropped and counted. recv returns within 100 ms even if nothing arrives; is_quiet says whether its error means "nothing for the guest" (a timeout, or a datagram already dropped and counted). The host tests use an in-memory MockBackend.
A thread that never waits for the guest
Who calls receive? Not a vCPU: its thread runs the guest. Not the worker: nobody rings a doorbell for an incoming frame. So each NIC gets one more thread, its RX thread (RX for receive, TX for transmit), running spawn_rx's loop:
let mut buf = vec![0u8; RX_BUFFER];while !job_shared.stop.load(Ordering::SeqCst) { let n = match job_backend.recv(&mut buf) { Ok(n) => n, Err(e) if is_quiet(&e) => continue, Err(e) => { crate::guest_warn!("virtio-net: receive failed: {e}"); std::thread::sleep(std::time::Duration::from_millis(10)); continue; } }; let frame = buf.get(..n).unwrap_or_default(); // A poisoned device (a worker panicked) is never touched again. let Ok(mut dev) = device.lock() else { break }; match dev.receive(frame) { Ok(_) | Err(VirtioError::NotActivated) => {} // Reported with the device mutex held, like the worker (lock order device // → interrupt): a Status = 0 reset waiting on the mutex then clears it. Err(e) => report_error(&interrupt, RX_QUEUE, &e), }}recv gives up after 100 ms, so the thread checks its stop flag ten times a second, and it holds the device mutex for one frame at a time. If the mutex is poisoned (chapter 15), the loop leaves without touching the device. If this thread panics, a guard created at its top stops the whole VM: Rust runs a value's Drop while a panic unwinds, and std::thread::panicking() tells the guard why.
struct RxPanicGuard { shared: Arc<RxShared>, ctl: Arc<VmControl>,}impl Drop for RxPanicGuard { fn drop(&mut self) { if std::thread::panicking() { self.shared.panicked.store(true, Ordering::SeqCst); self.ctl .request_stop(StopReason::Vmm(Error::Internal(RX_PANIC))); } }}The receive buffer, RX_BUFFER, is 2048 bytes. recv truncates a longer datagram, but it is still longer than any frame, so it is dropped as rx_dropped_len:
/// The RX thread's receive buffer, sized like macOS's `net.local.dgram.maxdgram` (2048)./// `maxdgram` is only the *default* send buffer of a datagram socket, not a cap: a sender that/// raises its own `SO_SNDBUF` can send a longer datagram (checked on a real Mac), and `recv` silently truncates it/// to this buffer. That is safe because the buffer is **longer than any frame**: a truncated/// datagram is exactly `RX_BUFFER` bytes, more than [`ETH_MAX_FRAME`], so [`Net::receive`]/// always drops it (`rx_dropped_len`) and a truncation can never pass as a valid frame. The/// assertion below keeps that invariant true if either constant changes.pub const RX_BUFFER: usize = 2048;const _: () = assert!( RX_BUFFER > ETH_MAX_FRAME, "a truncated datagram must not fit a frame");Chapter 17's worker gains one small trait, Companion: another thread of the same device. As the worker's companion, the RX thread is stopped and joined with it before guest memory is freed, and its counters print with the worker's:
/// Another host thread that belongs to the same device (a NIC's RX thread, for example). It is/// attached to the device's worker ([`Worker::attach`]) so the machine needs no second list:/// stopping the worker stops and joins its companions too (before guest RAM is freed),/// and their `--stats` lines come out with the worker's ([`Worker::companion_stats`]).pub trait Companion: Send + Sync { /// Stop the thread and join it. Idempotent. Returns true if it panicked. fn stop(&self) -> bool; /// One `--stats` line (numbers and static names only, never guest text), if it has counters. fn stats(&self) -> Option<String> { None }}/// Start NIC `n`'s RX thread (`virtio::net::spawn_rx`) and attach it to the slot's worker/// as its `Companion`, so stopping the workers (before guest RAM is freed) also stops and/// joins it, and its counters come out in `--stats`.fn attach_net_rx( worker: &Worker, slot: usize, n: usize, dev: Arc<Mutex<crate::virtio::Net>>, interrupt: Arc<VirtioInterrupt>, ctl: &Arc<VmControl>,) -> Result<()> { let rx = crate::virtio::net::spawn_rx( &format!("virtio-net-rx-{slot}"), &format!("net{n} slot {slot}"), dev, interrupt, Arc::clone(ctl), ) .map_err(|_| Error::Internal("cannot spawn a virtio-net RX thread"))?; worker.attach(Arc::new(rx)); Ok(())}The rest is chapter 15's VirtioDevice trait. The configuration space holds the MAC and ignores writes. A doorbell on queue 0 only means "I posted buffers", which receive finds when the next frame arrives, so it does nothing:
/// TX on QueueNotify of queue 1. A notify on queue 0 only says "RX buffers were posted":/// they are consumed when a frame arrives ([`Net::receive`]), so there is nothing to do.fn process_queue(&mut self, index: usize, budget: u16) -> Result<QueueProgress, VirtioError> { match index { RX_QUEUE => { if self.active.is_none() { return Err(VirtioError::NotActivated); } Ok(QueueProgress::Drained) } TX_QUEUE => self.process_tx(budget), _ => Err(VirtioError::NoSuchQueue(index)), }}Check the first sitting's work with the reference's host-only suite and its helper directory:
cp -Rn crates/vmm/tests/virtio_support crates/vmm/tests/virtio_net_hostile.rs learner/crates/vmm/tests/cd learner && cargo test -q -p vmm --test virtio_net_hostileIts 18 tests cover every rule above, with the names in item 1 of "Your turn". Expect test result: ok. 18 passed.
Good place to stop. Your device passes its host tests; sitting B gives it a wire and needs your Mac.
A wire made of two socket files
A Unix datagram socket keeps message boundaries (the unix-sockets primer), so one datagram is one Ethernet frame. Each VM binds its own socket file and sends to the other's:
guest A | macvmm A host: dir $T, mode 0700 macvmm B | guest B | |eth0 -->| virtio-net (A) --send_to--> b.sock --recv--> virtio-net (B) --------|--> eth0eth0 <--| virtio-net (A) <--recv-- a.sock <--send_to-- virtio-net (B) --------|--- eth0 | A binds a.sock B binds b.sock |Each VMM receives on the socket it bound and sends to its peer's. The bars are the trust boundaries between guest and VMM; nothing leaves the Mac.
The unixgram backend's option is --net unixgram:LOCAL,peer=REMOTE[,mac=XX:XX:XX:XX:XX:XX], parsed by parse_net in learner/crates/macvmm/src/cli.rs. Without mac=, the card gets 02:6d:76 plus three random bytes. Name the peer: a NIC that accepted whoever wrote first would be a gift to every program on the Mac. (An opt-in ,learn locks onto the first sender instead; it is weaker, and we do not use it.)
let peer = match (peer, learn) { (Some(p), false) => NetPeer::Path(p), (None, true) => NetPeer::Learn, (Some(_), true) => { return Err("--net unixgram: give peer=PATH or ,learn, not both".into()); } (None, false) => return Err("--net unixgram needs peer=PATH (or ,learn)".into()),};Before binding, the VMM runs the primer's checks in learner/crates/vmm/src/backend/hostio.rs (create it if you have none). The directory must be a real directory you own that nobody else can write to:
/// The directory holding a `--net` socket path must be a real directory (checked with/// `symlink_metadata`, so a symlinked directory is refused), owned by us and not group- or/// world-writable. Otherwise another local user could create, replace or connect to the socket/// file (see `docs/security/threat-model.md`). The socket file itself is `srwx------` (owner/// only) because of the startup `umask(0o077)`.fn check_socket_dir(path: &Path) -> core::result::Result<(), InputError> { let dir = path .parent() .filter(|d| !d.as_os_str().is_empty()) .unwrap_or(Path::new(".")); let md = std::fs::symlink_metadata(dir).map_err(|err| InputError::NetSetup { path: dir.to_path_buf(), err, })?; if !md.file_type().is_dir() || md.uid() != hvf::host::getuid() || md.mode() & 0o022 != 0 { return Err(InputError::NetDir { dir: dir.to_path_buf(), }); } Ok(())}Something already at LOCAL is inspected without following symlinks and replaced only if it is a socket, yours, and stale: left behind by a VM that died, with nobody bound to it.
match std::fs::symlink_metadata(&local) { Err(e) if e.kind() == io::ErrorKind::NotFound => {} Err(err) => return Err(InputError::NetSetup { path: local, err }), Ok(md) => { if !md.file_type().is_socket() { return Err(InputError::NetNotSocket { path: local }); } if md.uid() != hvf::host::getuid() { return Err(InputError::NetNotOwned { path: local }); } match probe(&local) { Probe::Stale => { std::fs::remove_file(&local).map_err(|err| InputError::NetSetup { path: local.clone(), err, })? } Probe::Live => return Err(InputError::NetLiveSocket { path: local }), Probe::Unknown(err) => return Err(InputError::NetSetup { path: local, err }), } }}The stale test is a datagram connect: it succeeds on a live socket and fails with ECONNREFUSED on a stale one.
/// Is the socket at `path` live? A datagram `connect` to a bound socket succeeds; to a socket/// file whose owner is gone it fails with `ECONNREFUSED` (checked on a real Mac). Only `Stale` may be replaced.pub fn probe(path: &Path) -> Probe { let sock = match UnixDatagram::unbound() { Ok(s) => s, Err(e) => return Probe::Unknown(e), }; match sock.connect(path) { Ok(()) => Probe::Live, Err(e) if e.kind() == io::ErrorKind::ConnectionRefused => Probe::Stale, Err(e) => Probe::Unknown(e), }}Binding raises both socket buffers to 1 MiB. The receive buffer is where frames queue while the RX thread is busy; the macOS default, 4096 bytes, holds two frames. When it is full, the peer's send_to fails and the peer counts a tx_dropped. setsockopt is an unsafe raw call, so set_socket_buffers lives in the hvf crate (chapter 01):
/// Bind `local` (already checked and, if stale, removed by `HostIo`), raise/// both buffers to [`SOCKET_BUFFER`], and set the timeouts: reads wait at most/// [`RECV_TIMEOUT`] so the RX thread sees its stop flag. `bind` creates the socket file with/// mode 0777 minus the startup `umask(0o077)`, so it is `srwx------`: only its owner can/// connect. The umask is never changed around `bind`, which would race with every other/// thread creating a file.pub fn bind(local: &Path, peer: PeerSpec) -> Result<UnixgramBackend, SetupError> { let sock = UnixDatagram::bind(local).map_err(SetupError::Bind)?; hvf::host::set_socket_buffers(sock.as_raw_fd(), SOCKET_BUFFER, SOCKET_BUFFER) .map_err(SetupError::Buffers)?; // Blocking mode on purpose: `O_NONBLOCK` is a property of the open file, shared by // the RX thread's `recv` and the worker's `send`, so the timeouts below bound both instead. sock.set_read_timeout(Some(RECV_TIMEOUT)) .map_err(SetupError::Timeouts)?; sock.set_write_timeout(Some(SEND_TIMEOUT)) .map_err(SetupError::Timeouts)?; let peer = match peer { PeerSpec::Fixed { target, accept } => Peer::Fixed { target, accept }, PeerSpec::Learn => Peer::Learn(OnceLock::new()), }; Ok(UnixgramBackend { sock, local: local.to_path_buf(), peer, foreign: AtomicU64::new(0), })}The reference sets a umask (file-creation mask) of 077 at startup, so bind creates the socket srwx------, owner only, as the primer computed. Chapter 25 adds that umask to yours; until then, the 0700 directory from mktemp -d keeps other users out.
A full peer fails with ENOBUFS at once, ignoring the write timeout, so send retries with short sleeps for at most 10 ms, then drops:
fn send(&self, frame: &[u8]) -> io::Result<()> { let Some(target) = self.peer() else { return Err(io::Error::from(io::ErrorKind::NotConnected)); }; let start = Instant::now(); loop { match self.sock.send_to(frame, target) { Ok(n) if n == frame.len() => return Ok(()), Ok(_) => return Err(io::Error::other("short datagram send")), Err(e) if (e.raw_os_error() == Some(hvf::host::ENOBUFS) || e.kind() == io::ErrorKind::WouldBlock) && start.elapsed() < SEND_TIMEOUT => { std::thread::sleep(SEND_RETRY_PAUSE); } Err(e) => return Err(e), } }}One more check, on every datagram. As the primer showed, on macOS even a connected datagram socket receives from any sender that can write to its path, and ours is not connected: every frame is a send_to(peer), because the peer may not exist yet or may restart. So the source check is the only filter; recv counts failures as rx_dropped_foreign:
fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { let (n, from) = self.sock.recv_from(buf)?; match self.accepts(from.as_pathname()) { Ok(()) => Ok(n), Err(why) => { self.foreign.fetch_add(1, Ordering::Relaxed); warn_foreign(&self.local, from.as_pathname(), why); Err(io::Error::from(io::ErrorKind::PermissionDenied)) } }}fn accepts(&self, source: Option<&Path>) -> Result<(), &'static str> { let Some(src) = source else { return Err("unnamed sender"); }; if !src.is_absolute() { return Err("relative source path"); } let ok = match &self.peer { Peer::Fixed { accept, .. } => accept.iter().any(|a| a.as_os_str() == src.as_os_str()),The comparison is byte for byte, against a list, accept. On macOS $TMPDIR lives under /var, a symlink to /private/var, so one socket has two spellings. open_unixgram resolves our peer= path's directory once and accepts either. A received path is never resolved, or a sender could bind a symlink that resolves to the peer.
/// The spellings a datagram from the peer may carry as its source: the absolute path,/// and the same path with its directory resolved (`/tmp/x/b.sock` and `/private/tmp/x/b.sock`/// are the same socket on macOS). Only *our* configuration is resolved, here, once; a received/// source path is never resolved, so a sender cannot pass by binding a symlink.////// A relative `peer=` as typed is **not** a spelling: a datagram's source is the sender's/// `sun_path` exactly as it was bound (checked on a real Mac), so `b.sock` bound from *any* directory arrives as/// `b.sock`. Accepting it would let any process that can write to LOCAL pose as the peer from a/// directory of its own choosing. A macvmm peer never needs it: `open_unixgram` always binds an/// absolute LOCAL.fn peer_spellings(abs: &Path) -> Vec<PathBuf> { debug_assert!(abs.is_absolute()); let mut out = vec![abs.to_path_buf()]; if let (Some(dir), Some(name)) = (abs.parent(), abs.file_name()) && let Ok(real) = std::fs::canonicalize(dir) { let real = real.join(name); if real.as_path() != abs { out.push(real); } } out}Two VMs, one conversation
The test initramfs has two cases for this chapter. net-b brings up eth0 (Linux's name for its first network interface) as 10.0.0.2; "up" means the driver is in use and posting receive buffers. It listens on TCP port 5000 with nc (netcat, which pipes bytes over one TCP connection) and prints the sha256 of what it receives. net-a comes up as 10.0.0.1, pings B, then sends 32 MiB of random bytes:
net_a() { net_up 10.0.0.1 # Up to 10 s for B to answer (it is already listening when A boots, but ARP and its link # may take a moment). i=0 while ! ping -c 1 -W 1 10.0.0.2 >/dev/null 2>&1; do i=$((i + 1)) if [ "$i" -ge 10 ]; then echo "macvmm-net: FAILED no answer from 10.0.0.2" break fi done got="$(ping -c 5 -i 0.2 10.0.0.2 | grep -o '[0-9]* packets received' | cut -d' ' -f1)" if [ "$got" = 5 ]; then echo "macvmm-net: ping 5/5 ok" else echo "macvmm-net: FAILED ping ${got:-0}/5" fi head -c 33554432 /dev/urandom > /tmp/x sum="$(sha256sum /tmp/x | cut -d' ' -f1)" # -w 5: after our stdin ends, wait at most 5 s for the peer to close (busybox nc does not # always half-close on EOF), so the transfer always terminates. if nc -w 5 10.0.0.2 5000 < /tmp/x; then echo "macvmm-net: sent $(wc -c < /tmp/x) bytes sha256=$sum" else echo "macvmm-net: FAILED nc send" fi}From the repository root these run the reference; for yours, run them inside learner/ with ../.cache. In terminal 1, make a private directory and start B:
T=$(mktemp -d); echo "$T"cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --stats --net "unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02" --cmdline "console=ttyAMA0 quiet macvmm.test=net-b"When it prints listening, set T in terminal 2 to the path terminal 1 printed and start A:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --stats --net "unixgram:$T/a.sock,peer=$T/b.sock,mac=02:6d:76:00:00:01" --cmdline "console=ttyAMA0 quiet macvmm.test=net-a"(Ctrl-A x quits B if A never connects.) VM A:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --stats --net unixgram:$T/a.sock,peer=$T/b.sock,mac=02:6d:76:00:00:01 --cmdline "console=ttyAMA0 quiet macvmm.test=net-a"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.1 up mac 02:6d:76:00:00:01macvmm-net: ping 5/5 okmacvmm-net: sent 33554432 bytes sha256=38d8284757d383a07669606ca8238fbfe9d870961c00c8420d20746809ce417a[ 1.566301] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=257 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 4895: hvc 16, sysreg 2, data abort 4877macvmm: stats: vcpu0 time: exec 0.560 s, wfi 0.969 smacvmm: stats: host cpu 0.784 s over 1.592 s wall (50%)macvmm: stats: net0 slot 0: tx_packets=23192 tx_bytes=35085348 tx_dropped=0 rx_packets=5586 rx_bytes=368856 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576VM B:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --stats --net unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02 --cmdline "console=ttyAMA0 quiet macvmm.test=net-b"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.2 up mac 02:6d:76:00:00:02macvmm-net: listeningmacvmm-net: received 33554432 bytes sha256=38d8284757d383a07669606ca8238fbfe9d870961c00c8420d20746809ce417a[ 6.698204] reboot: Power downmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=259 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 30358: hvc 16, sysreg 2, data abort 30340macvmm: stats: vcpu0 time: exec 0.483 s, wfi 6.097 smacvmm: stats: host cpu 0.834 s over 6.793 s wall (13%)macvmm: stats: net0 slot 0: tx_packets=5586 tx_bytes=368856 tx_dropped=6 rx_packets=23192 rx_bytes=35085348 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576Ping 5/5 and equal hashes (yours will differ: the bytes are random). A's tx_packets=23192 equals B's rx_packets, bytes too: no frame lost between the sockets.
Now the opening puzzle: B's tx_dropped=6, and six Send warnings. send_to fails when nothing is bound at the peer path: before A starts and after A powers off. Frames in those windows are dropped and counted (a rerun of ours dropped 3). Not a bug but the contract: a network may lose frames, and the protocols above it are built for that.
Two bytes off
Back to the Predict. We changed split_at(HDR_LEN) to split_at(10) in tx_one in a copy of the tree, ran it as VM A, and ran the unmodified reference as VM B:
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --stats --net unixgram:$T/a.sock,peer=$T/b.sock,mac=02:6d:76:00:00:01 --cmdline "console=ttyAMA0 quiet macvmm.test=net-a"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.1 up mac 02:6d:76:00:00:01macvmm-net: FAILED no answer from 10.0.0.2macvmm-net: FAILED ping 0/5macvmm-net: FAILED nc send[ 24.292776] reboot: Power downmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=228 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 654: hvc 16, sysreg 2, data abort 636macvmm: stats: vcpu0 time: exec 0.346 s, wfi 23.934 smacvmm: stats: host cpu 0.374 s over 24.383 s wall (2%)macvmm: stats: net0 slot 0: tx_packets=20 tx_bytes=1200 tx_dropped=0 rx_packets=2 rx_bytes=140 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --timeout 30 --stats --net unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02 --cmdline "console=ttyAMA0 quiet macvmm.test=net-b"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.2 up mac 02:6d:76:00:00:02macvmm-net: listeningmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: timeout: the guest was still running after --timeout 30smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=115 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 424: canceled 1, hvc 15, sysreg 2, data abort 406macvmm: stats: vcpu0 time: exec 0.110 s, wfi 29.835 smacvmm: stats: host cpu 0.132 s over 30.035 s wall (1%)macvmm: stats: net0 slot 0: tx_packets=2 tx_bytes=140 tx_dropped=7 rx_packets=20 rx_bytes=1200 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576B's VMM delivered all 20 of A's frames into B's buffers; B's guest answered none. Here is A's ARP broadcast as B's guest reads it, after the two leftover header bytes (num_buffers, written as 0):
| Bytes B reads | Sent as | Read as |
|---|---|---|
| 0 to 5 | ff ff ff ff ff ff (broadcast) | 00 00 ff ff ff ff: a destination that is not B |
| 6 to 11 | 02 6d 76 00 00 01 (A's MAC) | ff ff 02 6d 76 00: a "source" that is no NIC |
| 12 to 13 | 08 06 (ARP) | 00 01: below 0x0600, so read as an 802.3 length rather than a type; the frame was already discarded for its destination |
The answer is (c), nothing: a frame addressed to somebody else, which a network stack discards without a word. B's two transmitted frames, 70 bytes each, are the size of the IPv6 (Internet Protocol version 6) router solicitation Linux sends when an interface comes up; its seven Send drops are the before-A and after-A windows again. Framing is a contract between driver and device, even with no network.
Breaking it on purpose
Deliberate breakage 1: wait for a buffer instead of dropping the frame. In Net::receive, replace the let Some(chain) = a.rx.pop(mem)? else { … } block by a loop that pops, sleeps 1 ms if the ring is empty, and tries again. It looks kinder. Predict what happens when frames arrive while the guest has posted no buffers; write your guess under ## Q1.
For "no buffers" on demand, VM B's shell loads the driver but never brings eth0 up, and this driver posts receive buffers only when it comes up. Meanwhile VM A runs net-a, sending ARP requests to B for about 20 seconds. First, the reference:
(sleep 2; echo 'modprobe virtio_mmio; modprobe virtio_net; sleep 8; cat /sys/class/net/eth0/statistics/rx_packets; poweroff -f') | cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --timeout 20 --stats --net unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02 --cmdline "console=ttyAMA0 quiet"macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_net; sleep 8; cat /sys/class/net/eth0/statistics/rx_packets; poweroff -f0[ 9.685516] reboot: Power downmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [virtio-net-rx-0] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=197 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=3macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 988: hvc 16, sysreg 2, data abort 970macvmm: stats: vcpu0 time: exec 0.114 s, wfi 9.552 smacvmm: stats: host cpu 0.133 s over 9.710 s wall (2%)macvmm: stats: net0 slot 0: tx_packets=0 tx_bytes=0 tx_dropped=0 rx_packets=0 rx_bytes=0 rx_dropped_no_buffer=13 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576B's VMM dropped 13 frames (rx_dropped_no_buffer=13), and the guest's own rx_packets says 0. Only ten warnings appear because warnings are rate-limited (chapter 08); the counter is the truth. Now with the break:
(sleep 2; echo 'modprobe virtio_mmio; modprobe virtio_net; sleep 8; cat /sys/class/net/eth0/statistics/rx_packets; poweroff -f') | cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --timeout 20 --stats --net unixgram:"$T/b.sock",peer="$T/a.sock",mac=02:6d:76:00:00:02 --cmdline "console=ttyAMA0 quiet"macvmm-initramfs: ready 6.18.60-0-virt/ # modprobe virtio_mmio; modprobe virtio_net; sleep 8; cat /sys/class/net/eth0/statistics/rx_packets; poweroff -f0macvmm: user quit (second signal: exiting now)The guest printed 0 and began to power off, then nothing: no Power down, no stats. --timeout 20 and a first SIGTERM did nothing; only the second quit signal (chapter 09) ended it. To see why, we hung it again and ran the macOS sample tool, which records where each thread of a process is waiting (man sample), filtered:
sample "$B" 1 2>/dev/null | grep -E 'Thread_|Net7receive|9functions5sleep|10VirtioMmio5reset|5Mutex4lock|ScopedJoinHandleuE4join' 691 Thread_123835475 DispatchQueue_1: com.apple.main-thread (serial) + 691 _RNvMs1_NtNtCs1SSuMAdGM58_3std6thread6scopedINtB5_16ScopedJoinHandleuE4joinCs2rxmOgGCNRe_3vmm (in macvmm) + 40 [0x10029c2fc] 691 Thread_123835623: sink:stdout 691 Thread_123835624: signal 691 Thread_123835626: com.apple.virtualization.thread.virtual-clock 691 Thread_123835661: virtio-net-0 691 Thread_123835662: virtio-net-rx-0 + 671 _RNvMs1_NtNtCs2rxmOgGCNRe_3vmm6virtio3netNtB5_3Net7receive (in macvmm) + 700 [0x10028c514] + ! 670 _RNvNtNtCs1SSuMAdGM58_3std6thread9functions5sleep (in macvmm) + 100 [0x10030a1a0] + ! 1 _RNvNtNtCs1SSuMAdGM58_3std6thread9functions5sleep (in macvmm) + 100 [0x10030a1a0] + 18 _RNvMs1_NtNtCs2rxmOgGCNRe_3vmm6virtio3netNtB5_3Net7receive (in macvmm) + 436 [0x10028c40c] + 1 _RNvMs1_NtNtCs2rxmOgGCNRe_3vmm6virtio3netNtB5_3Net7receive (in macvmm) + 448 [0x10028c418] + 1 _RNvMs1_NtNtCs2rxmOgGCNRe_3vmm6virtio3netNtB5_3Net7receive (in macvmm) + 696 [0x10028c510] 691 Thread_123835663: vcpu0 691 _RNvMs_NtNtCs2rxmOgGCNRe_3vmm6virtio4mmioNtB4_10VirtioMmio5reset (in macvmm) + 36 [0x10021ca24] 691 _RNvMNtNtNtNtNtCs1SSuMAdGM58_3std3sys3pal4unix4sync5mutexNtB2_5Mutex4lock (in macvmm) + 12 [0x1002f718c]Read the words inside the mangled names; the numbers are lengths. virtio-net-rx-0 sleeps inside Net::receive, waiting for a buffer while holding the device mutex. vcpu0 is in VirtioMmio::reset, waiting for that mutex: power-off wrote 0 to Status, and a reset takes the device lock. The main thread waits in join for the vCPU.
The RX thread waits for the guest, whose only vCPU waits for the RX thread. --timeout kicks a vCPU out of the guest, but this one is stuck in our code. With eth0 down the guest touched no register of this device until power-off; any access that takes the device lock, such as a transmit QueueNotify, would stall the same way.
To run it yourself, make the edit in learner/ and build it. In terminal 1, inside learner/, with your main run's T:
(sleep 2; echo 'modprobe virtio_mmio; modprobe virtio_net; sleep 8; cat /sys/class/net/eth0/statistics/rx_packets; poweroff -f') | cargo run -q -p macvmm -- run --kernel ../.cache/macvmm/Image-virt --initrd ../.cache/macvmm/initramfs-test.img --timeout 20 --stats --net "unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02" --cmdline "console=ttyAMA0 quiet"Within three seconds, start A as before (late, and B exits normally with rx_dropped_no_buffer=0). When A has exited, in a third terminal run B=$(pgrep -f "macvmm run .*$T/b.sock"), sample "$B" 1, and kill "$B" twice. Undo the edit.
The misconception this exposes: "waiting is safer than dropping". Here the waiting device froze the guest. The rule: a device never waits for its guest, and every host-side wait has a timeout.
What "no entitlement" buys, and what it does not
macvmm is signed ad hoc with one entitlement, com.apple.security.hypervisor. Apple's library for putting VMs on real networks, vmnet.framework, needs root or com.apple.vm.networking, a restricted entitlement that gets an ad-hoc signed program killed at launch (the codesign-entitlements primer). Unix datagram sockets need neither: to macOS they are files, guarded by owner and mode. That also limits unixgram: to other programs on this Mac: no internet, no DHCP server (Dynamic Host Configuration Protocol; our guests set addresses by hand), no other machine.
Containment means limiting what a program can do after an attacker has taken it over. "No network entitlement" describes what macvmm asked for, not what it can do: any macOS process may open internet connections without one, so a guest that took over our VMM could too. The repository's audit (cargo run -p xtask -- audit) allows networking code in crates/vmm only in the net module and a short allow-list: a rule for reviewers, not a run-time barrier. The barrier is chapter 25's sandbox, rules the kernel enforces.
Try it
Run B as in the main run, plus --timeout 20. Three seconds later, start a third VM, C, with A's command but LOCAL set to $T/c.sock. B never named c.sock, so C's ping should fail; check B's rx_dropped_foreign.
cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --timeout 40 --stats --net "unixgram:$T/c.sock,peer=$T/b.sock,mac=02:6d:76:00:00:01" --cmdline "console=ttyAMA0 quiet macvmm.test=net-a"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.1 up mac 02:6d:76:00:00:01macvmm-net: FAILED no answer from 10.0.0.2macvmm-net: FAILED ping 0/5macvmm-net: FAILED nc send[ 24.294782] reboot: Power downmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=228 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 650: hvc 16, sysreg 2, data abort 632macvmm: stats: vcpu0 time: exec 0.357 s, wfi 23.921 smacvmm: stats: host cpu 0.393 s over 24.377 s wall (2%)macvmm: stats: net0 slot 0: tx_packets=17 tx_bytes=1034 tx_dropped=3 rx_packets=0 rx_bytes=0 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=0macvmm: stats: rlimit core=0 nofile=1048576cargo run -q -p macvmm -- run --kernel .cache/macvmm/Image-virt --initrd .cache/macvmm/initramfs-test.img --timeout 20 --stats --net "unixgram:$T/b.sock,peer=$T/a.sock,mac=02:6d:76:00:00:02" --cmdline "console=ttyAMA0 quiet macvmm.test=net-b"macvmm-initramfs: ready 6.18.60-0-virtmacvmm-net: eth0 10.0.0.2 up mac 02:6d:76:00:00:02macvmm-net: listeningmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [virtio-net-rx-0] net "$T/b.sock": datagram from Some("$T/c.sock") dropped: not the peer (NET-1)macvmm: warn: [virtio-net-0] guest: virtio-net: TX frame dropped: Sendmacvmm: timeout: the guest was still running after --timeout 20smacvmm: stats: serial_input_dropped=0 serial_input_queued=0 serial_written=115 serial_sink_dropped=0 serial_capped=0 serial_lost=0 serial_filtered=0macvmm: stats: vcpu0 exits: vtimer 0, wfx 0, total 383: canceled 1, hvc 15, sysreg 2, data abort 365macvmm: stats: vcpu0 time: exec 0.102 s, wfi 19.841 smacvmm: stats: host cpu 0.124 s over 20.056 s wall (1%)macvmm: stats: net0 slot 0: tx_packets=0 tx_bytes=0 tx_dropped=8 rx_packets=0 rx_bytes=0 rx_dropped_no_buffer=0 rx_dropped_small=0 rx_dropped_len=0 rx_dropped_foreign=17macvmm: stats: rlimit core=0 nofile=1048576C printed FAILED ping 0/5; B dropped all 17 of its frames (rx_dropped_foreign=17). (C's three Send drops came after B exited; B's eight went to a.sock, where nothing is bound.) Any program running as you can write to your socket file; this check keeps it off your guest's wire.
Your turn
In learner/, build what this page showed, with the names the contract tests use:
crates/vmm/src/virtio/net.rs:Net(new(mac, backend),receivereturningRxOutcome:Delivered,NoBuffer,ChainUnusable,BadLength;stats;spawn_rx),HDR_LEN,NET_QUEUE_SIZE(256),NET_CONFIG_LEN,RX_QUEUE,TX_QUEUE,F_MAC,RX_BUFFER;DEVICE_ID_NET = 1invirtio/mod.rs;Companioninvirtio/worker.rs.net/backend.rs(NetBackend) andnet/unixgram.rs:UnixgramBackend(bind,local,peer,rx_dropped_foreign,send,recv),PeerSpec,probe,SOCKET_BUFFER. The tests also coverlearn: lock onto the first absolute sender path, once.set_socket_buffersinhvf::host, with a// SAFETY:comment.- In
backend/hostio.rs:check_socket_dir,open_unixgramwith theacceptspellings, and theInputErrorvariantsNetDir,NetNotSocket,NetLiveSocket. - In
vmm::config:NetSpec(local,peer,mac),NetPeer(PathorLearn), andVmConfig::validate, refusing a NIC that is its own peer or two NICs with oneLOCAL. --netincli.rs, andattach_net_rxin the machine.
Your journal has a Predict entry and four questions: Q1 and Q2 with the break's captures and sample in front of you, Q3 after the last section, Q4 the open question below. Stuck? scripts/learner hint 19.
Checkpoint
Back at the repository root, run:
Checkpoint
Needs a MacRun this from the repository root:
scripts/checkpoint.sh 19You should see, as the last line:
CHECKPOINT 19 PASSIt runs the contract tests (the 18 from sitting A and 12 in crates/vmm/tests/unixgram.rs), the runs on your Mac, and the journal check. For a failing test's full output, copy crates/vmm/tests/unixgram.rs into learner/crates/vmm/tests/ and run cargo test -q -p vmm --test virtio_net_hostile --test unixgram inside learner/. On the reference:
cargo test -q -p vmm --test virtio_net_hostile --test unixgramrunning 12 tests............test result: ok. 12 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.11srunning 18 tests..................test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12smacvmm: warn: [learn_locks_to_the_first_sender] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-learn/a.sock": datagram from None dropped: unnamed sender (NET-1)macvmm: warn: [learn_locks_to_the_first_sender] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-learn/a.sock": learned peer "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-learn/first.sock"; it is locked for the lifetime of the VMmacvmm: warn: [learn_locks_to_the_first_sender] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-learn/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-learn/second.sock") dropped: not the learned peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [net_peer_check] net "/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/a.sock": datagram from Some("/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-peer/evil.sock") dropped: not the peer (NET-1)macvmm: warn: [relative_source_paths_are_never_accepted] net "/private/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-rel/l.sock": learned peer "/private/var/folders/xx/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx/T/mvu13405-rel/first.sock"; it is locked for the lifetime of the VMvirtio_net_hostile property seed 7954892368743920689 (MACVMM_SEED)macvmm: warn: [inactive_device_drops_and_rx_notify_is_a_noop] guest: virtio-net: RX frame dropped: device or receiveq not readymacvmm: warn: [rx_without_a_posted_buffer_is_dropped] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [inactive_device_drops_and_rx_notify_is_a_noop] guest: virtio-net: RX frame dropped: device or receiveq not readymacvmm: warn: [tx_chain_longer_than_a_frame_is_dropped] guest: virtio-net: TX frame dropped: Length(1527)macvmm: warn: [tx_chain_with_a_writable_descriptor_is_dropped_unwritten] guest: virtio-net: TX frame dropped: Writablemacvmm: warn: [rx_chain_smaller_than_header_plus_frame_is_returned_empty] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 111 writable bytes, needs 0 and 112macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: TX frame dropped: Header { flags: 158, gso_type: 77 }macvmm: warn: [a_descriptor_loop_is_an_error_on_both_queues] guest: virtio: queue 0 failed, device needs reset: virtqueue: ChainTooLong { budget: 16 }macvmm: warn: [tx_chain_shorter_than_the_header_is_dropped] guest: virtio-net: TX frame dropped: Length(11)macvmm: warn: [backend_send_error_is_counted_not_propagated] guest: virtio-net: TX frame dropped: Sendmacvmm: warn: [tx_chain_longer_than_a_frame_is_dropped] guest: virtio-net: TX frame dropped: Length(1527)macvmm: warn: [rx_chain_with_a_readable_descriptor_is_returned_empty] guest: virtio-net: RX frame dropped: chain has 1 readable descriptors and 2048 writable bytes, needs 0 and 72macvmm: warn: [mac_config_reads_at_every_width_and_ignores_writes] guest: virtio-mmio: config access of 1 bytes at 0x6 outside the 6-byte config space (RAZ/WI)macvmm: warn: [rx_datagrams_outside_14_to_1514_are_dropped] guest: virtio-net: RX datagram of 0 bytes dropped (not 14..=1514)macvmm: warn: [tx_chain_shorter_than_the_header_is_dropped] guest: virtio-net: TX frame dropped: Length(25)macvmm: warn: [rx_datagrams_outside_14_to_1514_are_dropped] guest: virtio-net: RX datagram of 1 bytes dropped (not 14..=1514)macvmm: warn: [rx_datagrams_outside_14_to_1514_are_dropped] guest: virtio-net: RX datagram of 13 bytes dropped (not 14..=1514)macvmm: warn: [mac_config_reads_at_every_width_and_ignores_writes] guest: virtio-mmio: config access of 4 bytes at 0x4 outside the 6-byte config space (RAZ/WI)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 1 readable descriptors and 0 writable bytes, needs 0 and 331macvmm: warn: [rx_datagrams_outside_14_to_1514_are_dropped] guest: virtio-net: RX datagram of 1515 bytes dropped (not 14..=1514)macvmm: warn: [rx_datagrams_outside_14_to_1514_are_dropped] guest: virtio-net: RX datagram of 2048 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 828 writable bytes, needs 0 and 1518macvmm: warn: [tx_nonzero_flags_are_dropped] guest: virtio-net: TX frame dropped: Header { flags: 1, gso_type: 0 }macvmm: warn: [tx_nonzero_flags_are_dropped] guest: virtio-net: TX frame dropped: Header { flags: 2, gso_type: 0 }macvmm: warn: [tx_nonzero_flags_are_dropped] guest: virtio-net: TX frame dropped: Header { flags: 4, gso_type: 0 }macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 4 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 4 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 2 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 1597 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 61 writable bytes, needs 0 and 1146macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 8 bytes dropped (not 14..=1514)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 719 writable bytes, needs 0 and 1188macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 572 writable bytes, needs 0 and 984macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 887 writable bytes, needs 0 and 1410macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 56 writable bytes, needs 0 and 1393macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 1226 writable bytes, needs 0 and 1460macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer postedmacvmm: warn: [net-rx-test] guest: virtio: queue 0 failed, device needs reset: virtqueue: ChainTooLong { budget: 16 }macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: TX frame dropped: Length(13) (989 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 1599 bytes dropped (not 14..=1514) (989 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer posted (989 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 1171 writable bytes, needs 0 and 1290 (989 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: TX frame dropped: Length(13) (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 1517 bytes dropped (not 14..=1514) (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: TX frame dropped: Writable (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: no receive buffer posted (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX frame dropped: chain has 0 readable descriptors and 899 writable bytes, needs 0 and 1010 (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: TX frame dropped: Length(4) (999 similar messages suppressed)macvmm: warn: [random_chains_and_frames_keep_the_caps] guest: virtio-net: RX datagram of 1531 bytes dropped (not 14..=1514) (999 similar messages suppressed)The whole checkpoint, on the reference:
scripts/checkpoint.sh 19 --ref[PASS] contract tests virtio_net_hostile (18 tests), unixgram (12 tests)[PASS] runs on your Mac two-vms: 12/12 serial markers, exit 0 in 2.56s[PASS] runs on your Mac bind-file: 2/2 serial markers, exit 2 in 0.03s[PASS] runs on your Mac probe-net: 6/6 serial markers, exit 0 in 0.13s[INFO] journal not checked (not a learner tree)CHECKPOINT 19 PASSBesides the two-VM run, it checks that a regular file at LOCAL is refused with exit code 2 and left untouched (the trailing NET-4 is the reference's own label for that rule), and that the bare-metal virtio probe finds device 1 in slot 0 (its warnings are narrow-read tests, as in chapter 15):
printf precious > $T/x; cargo run -q -p macvmm -- run --net unixgram:$T/x,peer=$T/y --kernel target/guests/aarch64-unknown-none/release/hello --timeout 10; echo "exit code $?"; cat $T/xexit code 2preciousmacvmm: refusing to replace non-socket path "$T/x" (--net only replaces a stale socket of yours; NET-4)cargo run -q -p macvmm -- run --mem 64M --net unixgram:$T/p.sock,peer=$T/q.sock --kernel target/guests/aarch64-unknown-none/release/virtio-probe --timeout 10virtio-probe: slot 0 device 1 features okvirtio-probe: slot 0 device id 1 status 0xfvirtio-probe: 32 slots magic ok version 2virtio-probe: 31 empty (device id 0)virtio-probe: narrow read RAZ okvirtio-probe: dt lists 1 virtio_mmio nodes okmacvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 2-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 8-byte read at 0x0 is not an aligned 32-bit access (RAZ)macvmm: warn: [vcpu0] guest: virtio-mmio: 1-byte read at 0x0 is not an aligned 32-bit access (RAZ)What now works:
- a virtio network card that copies, checks and caps every transmitted frame and drops and counts instead of waiting;
- a
unixgrambackend joining two VMs with no entitlement and no root, accepting datagrams only from the peer; - two guests moving 32 MiB with matching hashes,
--statsaccounting for every lost frame.
The next chapter starts from this state: the reference at the end of chapter 19, tag ch-19.
What's next
Every device in Part VII now has its own threads, each taking the device lock for one request at a time, beside one vCPU. Chapter 20 gives the guest many CPUs, and today's deadlock becomes one of several ways their threads can wait for each other.
Open question
Our virtio-net is slow by design: at most 1514 bytes per frame, each copied out of guest memory and through a socket, with no offloads. If you could add one offload first (checksum offload, segmentation offload, or mergeable receive buffers), which would buy the most speed for the 32 MiB transfer, and what new guest-written field would your device then have to parse and distrust?
Spec hunt
- virtio 1.2, section 5.1.6 "Device Operation", and its legacy-interface note on the header: when is
struct virtio_net_hdr10 bytes long, and which feature bit decides it for a legacy device? - virtio 1.2, sections 5.1.6.3.2 "Device Requirements: Setting Up Receive Buffers" and 5.1.6.4.1 "Device Requirements: Processing of Incoming Packets": into how many descriptors may one packet go when
VIRTIO_NET_F_MRG_RXBUFwas not negotiated, and what must the device then write intonum_buffers?