supermachine 0.7.70

Run any OCI/Docker image as a hardware-isolated microVM on macOS HVF (Linux KVM and Windows WHP in progress). Single library API, zero flags for the common case, sub-100 ms cold-restore from snapshot.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Status: compact port. Implements virtio-mmio register layout v2
// (the only layout Linux uses today).
//
// Register map (virtio spec 1.1 §4.2.2):
//   0x000  MagicValue       'virt'
//   0x004  Version          2
//   0x008  DeviceID         (per-device)
//   0x00c  VendorID
//   0x010  DeviceFeatures   (read-only, paged by DeviceFeaturesSel)
//   0x014  DeviceFeaturesSel
//   0x020  DriverFeatures   (RW, paged by DriverFeaturesSel)
//   0x024  DriverFeaturesSel
//   0x030  QueueSel         (selects queue index)
//   0x034  QueueNumMax      (R: max ring entries for selected queue)
//   0x038  QueueNum         (RW: actual ring size)
//   0x044  QueueReady       (RW)
//   0x050  QueueNotify      (W: kick from driver)
//   0x060  InterruptStatus  (R)
//   0x064  InterruptACK     (W: clear bits)
//   0x070  Status           (RW)
//   0x080  QueueDescLow
//   0x084  QueueDescHigh
//   0x090  QueueDriverLow   (avail ring)
//   0x094  QueueDriverHigh
//   0x0a0  QueueDeviceLow   (used ring)
//   0x0a4  QueueDeviceHigh
//   0x100+ device-specific config space

#![allow(dead_code)]

use std::sync::{Arc, Mutex};

use super::queue::{GuestMem, Queue};
use super::VirtioDevice;
use crate::devices::mmio_bus::MmioDevice;

const MAGIC: u32 = 0x74726976; // 'virt'
const VERSION: u32 = 2;

/// Captured per-queue state (subset of `Queue`'s mutable fields).
#[derive(Clone, Debug)]
pub struct QueueSnapshot {
    pub size: u16,
    pub ready: bool,
    pub desc_table: u64,
    pub avail_ring: u64,
    pub used_ring: u64,
    pub last_avail_idx: u16,
    pub next_used_idx: u16,
}

/// Captured per-device MMIO state. Restored by `MmioVirtio::restore_state`.
#[derive(Clone, Debug)]
pub struct MmioSnapshot {
    pub driver_features: [u32; 2],
    pub status: u32,
    /// Pending IRQ status the guest hasn't ACK'd. Important if the
    /// host had bumped `next_used_idx` (so a new used entry is
    /// visible in guest RAM) but the guest hadn't yet processed the
    /// IRQ at capture time — guest needs that bit set on resume to
    /// know there's work.
    pub interrupt_status: u32,
    pub queues: Vec<QueueSnapshot>,
}

impl MmioSnapshot {
    /// The single canonical wire codec for a virtio-mmio transport's snapshot
    /// state — it lives next to the type so EVERY snapshot pipeline serializes
    /// it identically (Phase-3 backend unification: `kvm::run` and the
    /// converging `vmm::snapshot` both route through this instead of
    /// hand-rolling the byte layout, which had already drifted — HVF wrote a
    /// stray alignment pad byte the KVM codec omitted). Layout (little-endian,
    /// the compact KVM form, no padding):
    ///
    /// ```text
    ///   driver_features[0] u32 · driver_features[1] u32
    ///   status u32 · interrupt_status u32 · n_queues u32
    ///   per queue: size u16 · ready u8 · desc_table u64 · avail_ring u64
    ///              used_ring u64 · last_avail_idx u16 · next_used_idx u16
    /// ```
    pub fn write_to<W: std::io::Write>(&self, w: &mut W) -> std::io::Result<()> {
        w.write_all(&self.driver_features[0].to_le_bytes())?;
        w.write_all(&self.driver_features[1].to_le_bytes())?;
        w.write_all(&self.status.to_le_bytes())?;
        w.write_all(&self.interrupt_status.to_le_bytes())?;
        w.write_all(&(self.queues.len() as u32).to_le_bytes())?;
        for q in &self.queues {
            w.write_all(&q.size.to_le_bytes())?;
            w.write_all(&[q.ready as u8])?;
            w.write_all(&q.desc_table.to_le_bytes())?;
            w.write_all(&q.avail_ring.to_le_bytes())?;
            w.write_all(&q.used_ring.to_le_bytes())?;
            w.write_all(&q.last_avail_idx.to_le_bytes())?;
            w.write_all(&q.next_used_idx.to_le_bytes())?;
        }
        Ok(())
    }

    /// Inverse of [`write_to`](Self::write_to). Reads exactly the bytes that
    /// method wrote.
    pub fn read_from<R: std::io::Read>(r: &mut R) -> std::io::Result<MmioSnapshot> {
        fn rd<const N: usize, R: std::io::Read>(r: &mut R) -> std::io::Result<[u8; N]> {
            let mut b = [0u8; N];
            r.read_exact(&mut b)?;
            Ok(b)
        }
        let driver_features = [
            u32::from_le_bytes(rd::<4, _>(r)?),
            u32::from_le_bytes(rd::<4, _>(r)?),
        ];
        let status = u32::from_le_bytes(rd::<4, _>(r)?);
        let interrupt_status = u32::from_le_bytes(rd::<4, _>(r)?);
        let nq = u32::from_le_bytes(rd::<4, _>(r)?);
        let mut queues = Vec::with_capacity(nq.min(64) as usize);
        for _ in 0..nq {
            let size = u16::from_le_bytes(rd::<2, _>(r)?);
            let ready = rd::<1, _>(r)?[0] != 0;
            queues.push(QueueSnapshot {
                size,
                ready,
                desc_table: u64::from_le_bytes(rd::<8, _>(r)?),
                avail_ring: u64::from_le_bytes(rd::<8, _>(r)?),
                used_ring: u64::from_le_bytes(rd::<8, _>(r)?),
                last_avail_idx: u16::from_le_bytes(rd::<2, _>(r)?),
                next_used_idx: u16::from_le_bytes(rd::<2, _>(r)?),
            });
        }
        Ok(MmioSnapshot {
            driver_features,
            status,
            interrupt_status,
            queues,
        })
    }
}

struct State {
    device_features_sel: u32,
    driver_features: [u32; 2],
    driver_features_sel: u32,
    queue_sel: u32,
    status: u32,
    interrupt_status: u32,
    /// Per-queue state arrays.
    queues: Vec<Queue>,
    activated: bool,
    /// Selected shared-memory region (virtio-mmio rev 1.2). Driver
    /// writes a region id to offset 0x0AC; subsequent reads of
    /// SHMLen{Low,High} (0x0B0/0x0B4) and SHMBase{Low,High}
    /// (0x0B8/0x0BC) return the matching region from
    /// `dev.shm_regions()`, or len=0 if no region with that id.
    shm_sel: u32,
    /// Notification: callback when guest writes to QueueNotify or
    /// when status flips DRIVER_OK.
    irq_raise: Arc<dyn Fn() + Send + Sync>,
}

pub struct MmioVirtio {
    dev: Arc<dyn VirtioDevice>,
    state: Mutex<State>,
}

impl MmioVirtio {
    pub fn new(
        dev: Arc<dyn VirtioDevice>,
        mem: GuestMem,
        irq_raise: Arc<dyn Fn() + Send + Sync>,
    ) -> Self {
        let queues = (0..dev.num_queues())
            .map(|_| Queue::new(mem.clone()))
            .collect();
        Self {
            dev,
            state: Mutex::new(State {
                device_features_sel: 0,
                driver_features: [0; 2],
                driver_features_sel: 0,
                queue_sel: 0,
                status: 0,
                interrupt_status: 0,
                queues,
                activated: false,
                shm_sel: 0,
                irq_raise,
            }),
        }
    }

    /// Snapshot of mutable per-device MMIO state. Captures the bits
    /// the guest set during driver init: negotiated features, status
    /// (DRIVER_OK et al.), per-queue addresses + cursors, AND
    /// `interrupt_status` (so a used-buffer/config IRQ published but
    /// not yet ACKed by the guest survives the restore). Only the
    /// write-only selector registers (device/driver feature-select,
    /// queue-select) are dropped — they are scratch the guest re-sets
    /// on every access.
    pub fn capture_state(&self) -> MmioSnapshot {
        let st = self.state.lock().unwrap();
        // Live cursors live in the DEVICE's queues post-activate (the
        // device clones queues out of MmioVirtio in `activate` and
        // bumps last_avail_idx / next_used_idx in its own copy). Read
        // from the device when we can; fall back to the mirror for
        // pre-activate state.
        let live = self.dev.snapshot_queues();
        let queues: Vec<QueueSnapshot> = (0..st.queues.len())
            .map(|i| {
                let q = live.get(i).unwrap_or(&st.queues[i]);
                QueueSnapshot {
                    size: q.size,
                    ready: q.ready,
                    desc_table: q.desc_table,
                    avail_ring: q.avail_ring,
                    used_ring: q.used_ring,
                    last_avail_idx: q.last_avail_idx,
                    next_used_idx: q.next_used_idx,
                }
            })
            .collect();
        MmioSnapshot {
            driver_features: st.driver_features,
            status: st.status,
            interrupt_status: st.interrupt_status,
            queues,
        }
    }

    /// Replay a captured State into a fresh MmioVirtio. If the
    /// snapshot has DRIVER_OK set, also re-activates the device with
    /// the restored queues so the muxer/device starts using the same
    /// ring addresses + cursors the guest expects.
    pub fn restore_state(&self, snap: &MmioSnapshot) {
        let mut st = self.state.lock().unwrap();
        st.driver_features = snap.driver_features;
        st.status = snap.status;
        st.interrupt_status = snap.interrupt_status;
        for (i, qs) in snap.queues.iter().enumerate() {
            if let Some(q) = st.queues.get_mut(i) {
                q.size = qs.size;
                q.ready = qs.ready;
                q.desc_table = qs.desc_table;
                q.avail_ring = qs.avail_ring;
                q.used_ring = qs.used_ring;
                q.last_avail_idx = qs.last_avail_idx;
                q.next_used_idx = qs.next_used_idx;
            }
        }
        if snap.status & super::STATUS_DRIVER_OK != 0 {
            st.activated = true;
            let queues = st.queues.clone();
            drop(st);
            self.dev.activate(queues);
        }
    }

    /// Build a closure that asserts the config-change IRQ
    /// (interrupt_status bit 1). Used by virtio-balloon when num_pages
    /// changes — the guest reads InterruptStatus, sees bit 1, then
    /// reads the device's config register space.
    pub fn make_config_change_irq(self: &Arc<Self>) -> Arc<dyn Fn() + Send + Sync> {
        // WEAK back-reference, not strong: this closure is handed to the DEVICE
        // (`dev.set_config_irq_raise`), and `MmioVirtio` holds the device
        // (`self.dev`). A strong `self.clone()` here would form a device⇄mmio
        // Arc cycle that never frees — and since `state.irq_raise` captures the
        // `Arc<KvmVm>`, that cycle pins the VM fd (and its kernel kthreads) for
        // the life of the process, leaking one per VM across pool churn. Upgrade
        // on each call; once the mmio is dropped at teardown the IRQ is a no-op.
        let me = Arc::downgrade(self);
        Arc::new(move || {
            let Some(me) = me.upgrade() else {
                return;
            };
            let mut st = me.state.lock().unwrap();
            st.interrupt_status |= 0x2;
            let f = st.irq_raise.clone();
            drop(st);
            f();
        })
    }

    /// Build the closure devices use to raise their used-buffer IRQ.
    /// It sets the device's `interrupt_status |= 1` (so the guest's
    /// IRQ handler reads VIRTIO_MMIO_INT_VRING and dispatches), then
    /// pulses the SPI line.
    /// The virtio device-type id of the wrapped device (VIRTIO_ID_BLOCK / VSOCK
    /// / FS …). Lets the snapshot pipeline tag each device's `DeviceRecord` kind.
    pub fn device_id(&self) -> u32 {
        self.dev.device_id()
    }

    pub fn make_used_buffer_irq(self: &Arc<Self>) -> Arc<dyn Fn() + Send + Sync> {
        // WEAK back-reference — see `make_config_change_irq`. The device stores
        // this closure (`dev.set_irq_raise`) and `MmioVirtio` owns the device, so
        // a strong ref here leaks the device + mmio + captured `Arc<KvmVm>` (VM
        // fd) per VM. Upgrade per call; a dropped mmio makes the IRQ a no-op.
        let me = Arc::downgrade(self);
        Arc::new(move || {
            let Some(me) = me.upgrade() else {
                return;
            };
            let mut st = me.state.lock().unwrap();
            st.interrupt_status |= 0x1;
            let f = st.irq_raise.clone();
            drop(st);
            f();
        })
    }
}

impl MmioDevice for MmioVirtio {
    fn read(&self, offset: u64, _size: u8) -> u64 {
        let st = self.state.lock().unwrap();
        let v: u32 = match offset {
            0x000 => MAGIC,
            0x004 => VERSION,
            0x008 => self.dev.device_id(),
            0x00c => self.dev.vendor_id(),
            0x010 => {
                // DeviceFeatures, paged by sel. We expose 64 bits.
                let f = self.dev.features();
                if st.device_features_sel == 0 {
                    f as u32
                } else {
                    (f >> 32) as u32
                }
            }
            0x034 => self.dev.queue_max_size() as u32,
            0x038 => st
                .queues
                .get(st.queue_sel as usize)
                .map(|q| q.size as u32)
                .unwrap_or(0),
            0x044 => st
                .queues
                .get(st.queue_sel as usize)
                .map(|q| if q.ready { 1 } else { 0 })
                .unwrap_or(0),
            0x060 => st.interrupt_status,
            0x070 => st.status,
            // Shared-memory region selectors (virtio-mmio rev 1.2 §4.2.2).
            // SHMSel was written; expose Len/Base for that region.
            0x0b0 | 0x0b4 | 0x0b8 | 0x0bc => {
                let sel = st.shm_sel as u8;
                let region = self.dev.shm_regions().into_iter().find(|r| r.id == sel);
                let (base, len) = match region {
                    Some(r) => (r.gpa, r.len),
                    // virtio-mmio 1.2 §4.2.2: a SHMSel that doesn't correspond to
                    // a region MUST read back length `-1` (all ones), NOT 0. A 0
                    // length reads as "a zero-length region exists", which makes
                    // the guest virtio-fs driver try to reserve addr=0/len=0 for
                    // its DAX window and fail probe (-EBUSY) → "tag not found".
                    // -1 tells the driver the slot is empty so it skips DAX.
                    None => (0u64, u64::MAX),
                };
                match offset {
                    0x0b0 => len as u32,
                    0x0b4 => (len >> 32) as u32,
                    0x0b8 => base as u32,
                    0x0bc => (base >> 32) as u32,
                    _ => unreachable!(),
                }
            }
            0x100.. => {
                let cfg = self.dev.config();
                let off = (offset - 0x100) as usize;
                off.checked_add(4)
                    .and_then(|end| cfg.get(off..end))
                    .map(|bytes| u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
                    .unwrap_or(0)
            }
            _ => 0,
        };
        v as u64
    }

    fn write(&self, offset: u64, value: u64, _size: u8) {
        let mut st = self.state.lock().unwrap();
        let v32 = value as u32;
        match offset {
            0x014 => st.device_features_sel = v32,
            0x020 => {
                let i = (st.driver_features_sel & 1) as usize;
                st.driver_features[i] = v32;
            }
            0x024 => st.driver_features_sel = v32,
            0x030 => st.queue_sel = v32,
            0x038 => {
                let sel = st.queue_sel as usize;
                if let Some(q) = st.queues.get_mut(sel) {
                    q.size = v32 as u16;
                }
            }
            0x044 => {
                let sel = st.queue_sel as usize;
                if let Some(q) = st.queues.get_mut(sel) {
                    q.ready = v32 != 0;
                }
            }
            0x050 => {
                // QueueNotify — guest kicks queue v32. Drop the lock
                // before invoking notify, in case the device wants to
                // call back into us (e.g. raise IRQ).
                drop(st);
                self.dev.notify(v32 as u16);
            }
            0x064 => st.interrupt_status &= !v32,
            // SHMSel: selects which shared-memory region's
            // Len/Base will be exposed at 0x0B0..0x0BC. Write-only;
            // the driver writes id, then reads len + base.
            0x0ac => st.shm_sel = v32,
            0x070 => {
                st.status = v32;
                // On DRIVER_OK transition, hand the queues to the device.
                if v32 & super::STATUS_DRIVER_OK != 0 && !st.activated {
                    st.activated = true;
                    let queues = st.queues.clone();
                    drop(st);
                    self.dev.activate(queues);
                }
            }
            // Per-queue address triples (low/high u32). Combine into u64.
            0x080 => set_low(&mut st, |q| &mut q.desc_table, v32),
            0x084 => set_high(&mut st, |q| &mut q.desc_table, v32),
            0x090 => set_low(&mut st, |q| &mut q.avail_ring, v32),
            0x094 => set_high(&mut st, |q| &mut q.avail_ring, v32),
            0x0a0 => set_low(&mut st, |q| &mut q.used_ring, v32),
            0x0a4 => set_high(&mut st, |q| &mut q.used_ring, v32),
            // Device-specific config writes (e.g. virtio-balloon `actual`
            // at offset 0x104). Forward to the device.
            0x100.. => {
                drop(st);
                self.dev.config_write((offset - 0x100) as usize, v32);
            }
            _ => {}
        }
    }

    fn len(&self) -> u64 {
        0x200
    }
}

fn set_low(st: &mut State, accessor: impl FnOnce(&mut Queue) -> &mut u64, v: u32) {
    let sel = st.queue_sel as usize;
    if let Some(q) = st.queues.get_mut(sel) {
        let r = accessor(q);
        *r = (*r & !0xffff_ffff) | (v as u64);
    }
}
fn set_high(st: &mut State, accessor: impl FnOnce(&mut Queue) -> &mut u64, v: u32) {
    let sel = st.queue_sel as usize;
    if let Some(q) = st.queues.get_mut(sel) {
        let r = accessor(q);
        *r = (*r & 0xffff_ffff) | ((v as u64) << 32);
    }
}

/// Helper for the device's `notify` impl to raise the device IRQ.
/// Called from inside the device after queue processing.
pub fn raise_used_buffer_irq(mmio: &MmioVirtio) {
    let mut st = mmio.state.lock().unwrap();
    st.interrupt_status |= 0x1; // bit 0 = "used buffer notification"
    let f = st.irq_raise.clone();
    drop(st);
    f();
}

#[cfg(test)]
mod tests {
    //! virtio-mmio register-level tests. We don't spin up a guest;
    //! instead we drive the MMIO read/write surface directly and
    //! verify the device advertises what we expect.

    #[test]
    fn mmio_snapshot_codec_round_trips_and_is_stable() {
        use super::{MmioSnapshot, QueueSnapshot};
        let snap = MmioSnapshot {
            driver_features: [0x1234_5678, 0x9abc_def0],
            status: 0xf,
            interrupt_status: 0x1,
            queues: vec![
                QueueSnapshot {
                    size: 256,
                    ready: true,
                    desc_table: 0x1_0000,
                    avail_ring: 0x1_1000,
                    used_ring: 0x1_2000,
                    last_avail_idx: 7,
                    next_used_idx: 7,
                },
                QueueSnapshot {
                    size: 64,
                    ready: false,
                    desc_table: 0x2_0000,
                    avail_ring: 0,
                    used_ring: 0,
                    last_avail_idx: 0,
                    next_used_idx: 0,
                },
            ],
        };
        let mut buf = Vec::new();
        snap.write_to(&mut buf).unwrap();
        // Exact size pins the no-pad layout: 20-byte header + n*u32 count is
        // folded in; per queue = 2+1+8+8+8+2+2 = 31 bytes (NO alignment pad).
        // header = 4+4+4+4+4 = 20; total = 20 + 2*31 = 82.
        assert_eq!(buf.len(), 82, "wire layout drifted (alignment pad?)");
        let got = MmioSnapshot::read_from(&mut &buf[..]).unwrap();
        assert_eq!(got.driver_features, snap.driver_features);
        assert_eq!(got.status, snap.status);
        assert_eq!(got.interrupt_status, snap.interrupt_status);
        assert_eq!(got.queues.len(), 2);
        assert_eq!(got.queues[0].size, 256);
        assert!(got.queues[0].ready);
        assert_eq!(got.queues[0].desc_table, 0x1_0000);
        assert_eq!(got.queues[0].last_avail_idx, 7);
        assert!(!got.queues[1].ready);
        assert_eq!(got.queues[1].size, 64);
    }

    use super::*;
    use crate::devices::mmio_bus::MmioDevice;
    use crate::devices::virtio::fs::{VirtioFs, VirtioFsConfig};
    use crate::devices::virtio::queue::GuestMem;
    use std::sync::Arc;

    fn make_fs_mmio() -> Arc<MmioVirtio> {
        let dev = Arc::new(VirtioFs::new(VirtioFsConfig {
            tag: "shared".into(),
            num_request_queues: 1,
            dax_window_gpa: 0x80_0000_0000,
            dax_window_len: 0x4_0000_0000, // 16 GiB
        }));
        // A throwaway 4 KiB GuestMem; the SHM register test path
        // doesn't touch it.
        let mem = GuestMem::new(std::ptr::null_mut(), 0, 0);
        let irq = Arc::new(|| {}) as Arc<dyn Fn() + Send + Sync>;
        Arc::new(MmioVirtio::new(dev as Arc<dyn VirtioDevice>, mem, irq))
    }

    fn read_u32(d: &MmioVirtio, off: u64) -> u32 {
        d.read(off, 4) as u32
    }

    #[test]
    fn shm_region_0_round_trip() {
        let m = make_fs_mmio();
        // Select SHMID = 0 (the DAX window).
        m.write(0x0ac, 0, 4);
        // Read Len and Base back as low/high pairs.
        let len_lo = read_u32(&m, 0x0b0) as u64;
        let len_hi = read_u32(&m, 0x0b4) as u64;
        let len = (len_hi << 32) | len_lo;
        assert_eq!(len, 0x4_0000_0000, "DAX window len");

        let base_lo = read_u32(&m, 0x0b8) as u64;
        let base_hi = read_u32(&m, 0x0bc) as u64;
        let base = (base_hi << 32) | base_lo;
        assert_eq!(base, 0x80_0000_0000, "DAX window base");
    }

    #[test]
    fn shm_unknown_region_reports_minus_one_len() {
        let m = make_fs_mmio();
        // Select a region id virtio-fs doesn't advertise.
        m.write(0x0ac, 99, 4);
        // virtio-mmio 1.2 §4.2.2: a nonexistent region reads length -1 (all
        // ones), NOT 0 — a 0 length makes the guest treat the slot as a real
        // zero-length region and fail to map it (see the SHMLen read handler).
        let len_lo = read_u32(&m, 0x0b0);
        let len_hi = read_u32(&m, 0x0b4);
        assert_eq!(len_lo, 0xFFFF_FFFF);
        assert_eq!(len_hi, 0xFFFF_FFFF);
    }

    #[test]
    fn device_id_and_vendor_id_visible() {
        let m = make_fs_mmio();
        assert_eq!(read_u32(&m, 0x000), MAGIC);
        assert_eq!(read_u32(&m, 0x004), VERSION);
        assert_eq!(read_u32(&m, 0x008), 26, "VIRTIO_ID_FS");
    }

    // ── write/validation surface: hostile register sequences ──────────
    // Registers: QueueSel 0x030, QueueNum 0x038, QueueReady 0x044,
    // desc lo/hi 0x080/0x084, avail lo 0x090, used lo 0x0a0, Status 0x070.

    #[test]
    fn queue_num_and_ready_round_trip() {
        let m = make_fs_mmio();
        m.write(0x030, 0, 4); // QueueSel = 0
        m.write(0x038, 64, 4); // QueueNum = 64
        m.write(0x044, 1, 4); // QueueReady = 1
        let s = m.capture_state();
        assert_eq!(s.queues[0].size, 64);
        assert!(s.queues[0].ready);
    }

    #[test]
    fn queue_sel_out_of_range_writes_are_ignored_safely() {
        let m = make_fs_mmio();
        // Configure queue 0 legitimately.
        m.write(0x030, 0, 4);
        m.write(0x038, 32, 4);
        // Select a wildly out-of-range queue and write — the `Option::get`
        // guards must make these silent no-ops (no panic, no neighbour
        // corruption), which is what the whole design relies on.
        m.write(0x030, 999, 4);
        m.write(0x038, 4096, 4);
        m.write(0x044, 1, 4);
        m.write(0x080, 0xdead_beef, 4);
        let s = m.capture_state();
        assert_eq!(s.queues[0].size, 32, "real queue untouched by OOR writes");
        assert!(!s.queues[0].ready);
    }

    #[test]
    fn queue_address_triples_round_trip() {
        let m = make_fs_mmio();
        m.write(0x030, 0, 4); // QueueSel = 0
        m.write(0x080, 0x1111_2222, 4); // desc low
        m.write(0x084, 0xaaaa_bbbb, 4); // desc high
        m.write(0x090, 0x3333_4444, 4); // avail low
        m.write(0x0a0, 0x5555_6666, 4); // used low
        let s = m.capture_state();
        assert_eq!(s.queues[0].desc_table, 0xaaaa_bbbb_1111_2222, "lo/hi merge");
        assert_eq!(s.queues[0].avail_ring & 0xffff_ffff, 0x3333_4444);
        assert_eq!(s.queues[0].used_ring & 0xffff_ffff, 0x5555_6666);
    }

    #[test]
    fn hostile_zero_size_queue_activate_does_not_panic() {
        // The exact register sequence a hostile guest would use to wedge a
        // size-0 queue into the device: QueueNum=0, ready, DRIVER_OK →
        // activate. Must not panic at the register layer (the drain-time
        // divide-by-zero is guarded in Queue::pop_chain).
        let m = make_fs_mmio();
        m.write(0x030, 0, 4); // QueueSel = 0
        m.write(0x038, 0, 4); // QueueNum = 0
        m.write(0x044, 1, 4); // QueueReady
        m.write(0x070, crate::devices::virtio::STATUS_DRIVER_OK as u64, 4); // DRIVER_OK
        let s = m.capture_state();
        assert_eq!(s.queues[0].size, 0);
        assert_ne!(s.status & crate::devices::virtio::STATUS_DRIVER_OK, 0);
    }
}