rsemu 0.0.2

A multiplatform emulator in pure Rust, built bottom-up on a generic framework.
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
//! The virtio over MMIO transport.
//!
//! # Source
//!
//! *Virtual I/O Device (VIRTIO) Version 1.2*, OASIS Standard: §4.2 ("Virtio
//! Over MMIO") for the register block below, §2.1 for the device status
//! handshake, §6 for the reserved feature bits. Nothing else — see
//! [`queue`](super::queue) for why no driver source was opened.
//!
//! # The register block
//!
//! ```text
//!   0x000 MagicValue  R    "virt"          0x070 Status          RW
//!   0x004 Version     R    2 (modern)      0x080 QueueDescLow    W
//!   0x008 DeviceID    R                    0x084 QueueDescHigh   W
//!   0x00c VendorID    R                    0x090 QueueDriverLow  W
//!   0x010 DeviceFeatures    R              0x094 QueueDriverHigh W
//!   0x014 DeviceFeaturesSel W              0x0a0 QueueDeviceLow  W
//!   0x020 DriverFeatures    W              0x0a4 QueueDeviceHigh W
//!   0x024 DriverFeaturesSel W              0x0fc ConfigGeneration R
//!   0x030 QueueSel    W                    0x100 device configuration
//!   0x034 QueueNumMax R
//!   0x038 QueueNum    W
//!   0x044 QueueReady  RW
//!   0x050 QueueNotify W
//!   0x060 InterruptStatus R
//!   0x064 InterruptACK    W
//! ```
//!
//! # Version 2 only, and why that is a feature
//!
//! `Version` reads 2, so a legacy driver walks away rather than programming a
//! `GuestPageSize` register this does not have. The legacy layout is a
//! different device with the same magic number, and half-implementing it
//! produces a machine that boots one kernel and corrupts another's disk.
//!
//! # When work happens
//!
//! A write to `QueueNotify` processes every available chain, synchronously,
//! inside the guest's own store instruction. That is the re-entrancy contract
//! of `ROADMAP.md` §4.7 taken at its word: the transport's state lock is
//! released *before* the backend is called, because the backend performs DMA
//! through the same address space the notify arrived on.

use alloc::format;
use alloc::string::{String, ToString};
use alloc::sync::{Arc, Weak};
use alloc::vec::Vec;
use core::fmt;

use crate::core::device::{Device, DeviceClass, RealizeCtx, ResetKind};
use crate::core::error::{BusError, Error, Result};
use crate::core::space::{AccessConstraints, AddressSpace, MemAttrs, MemOps, MemResult};
use crate::core::space::{Region, RegionRef, RequesterId};
use crate::core::state::{ChunkReader, ChunkWriter, Sink, Source};
use crate::core::sync::{LockRank, Mutex};
use crate::core::value::{Endian, Width};
use crate::core::wire::{Level, WireSource};
use crate::machine::realize::{BindCtx, Instance};

use super::super::dt::{DtSource, NodeSpec};
use super::queue::{Descriptor, Layout, QUEUE_SIZE_MAX, Queue};
use super::{Backend, VENDOR_ID};

/// How much address space one virtio-mmio device occupies.
///
/// The registers end at `0x100` and the configuration space follows; 4 KiB is
/// what boards conventionally give each one, which also means one page.
pub const REGISTER_WINDOW_LEN: u64 = 0x1000;

/// Where the device-specific configuration space starts (§4.2.2).
pub const CONFIG_OFFSET: u64 = 0x100;

/// `MagicValue`: the ASCII bytes `virt`, little-endian (§4.2.2).
pub const MAGIC: u32 = 0x7472_6976;

/// The transport version this implements. 2 is the non-legacy interface.
pub const VERSION: u32 = 2;

// -- Status bits (§2.1) -----------------------------------------------------

/// The guest has noticed the device.
const STATUS_ACKNOWLEDGE: u32 = 1;
/// The guest has a driver for it.
const STATUS_DRIVER: u32 = 2;
/// The driver is done setting up and the device may be used.
const STATUS_DRIVER_OK: u32 = 4;
/// The driver has accepted a feature set the device can live with.
const STATUS_FEATURES_OK: u32 = 8;
/// Something went wrong that only a reset will clear.
const STATUS_NEEDS_RESET: u32 = 64;
/// The driver has given up on the device.
const STATUS_FAILED: u32 = 128;

/// `VIRTIO_F_VERSION_1` (§6): bit 32, and a modern device offers nothing
/// without it.
pub const F_VERSION_1: u64 = 1 << 32;

// -- InterruptStatus bits (§4.2.2) ------------------------------------------

/// The device has put something in a used ring.
const INT_USED_BUFFER: u32 = 1;
/// The configuration space changed.
const INT_CONFIG_CHANGE: u32 = 2;

/// Everything the driver can see or change.
#[derive(Debug, Clone, PartialEq, Eq)]
struct State {
    device_features_sel: u32,
    driver_features_sel: u32,
    /// The two halves of the 64-bit acknowledged feature set.
    driver_features: [u32; 2],
    queue_sel: u32,
    queues: Vec<QueueState>,
    status: u32,
    interrupt_status: u32,
    config_generation: u32,
}

/// One queue's configuration and the device's position in it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
struct QueueState {
    layout: Layout,
    /// How far into the available ring the device has consumed.
    last_avail: u16,
    /// The next index the device will write into the used ring.
    used_idx: u16,
}

impl State {
    fn new(queues: usize) -> State {
        State {
            device_features_sel: 0,
            driver_features_sel: 0,
            driver_features: [0; 2],
            queue_sel: 0,
            queues: alloc::vec![QueueState::default(); queues],
            status: 0,
            interrupt_status: 0,
            config_generation: 0,
        }
    }
}

/// The register block, as something an address space can dispatch to.
struct Registers {
    state: Mutex<State>,
    /// The interrupt output and the DMA space, at [`LockRank::LEAF`] so they
    /// can be taken with nothing else held.
    links: Mutex<Links>,
    backend: Arc<dyn Backend>,
}

/// What the machine gave this device.
#[derive(Debug, Default)]
struct Links {
    out: Option<WireSource>,
    space: Option<Arc<AddressSpace>>,
    requester: RequesterId,
    /// The net the interrupt pin drives, so the device tree can look its
    /// number up in the PLIC's pin table. See [`dt`](super::super::dt).
    irq_wire: Option<crate::core::wire::WireId>,
}

impl fmt::Debug for Registers {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("Registers");
        s.field("backend", &self.backend);
        match self.state.try_lock() {
            Some(state) => s.field("status", &state.status).finish(),
            None => s.field("state", &"<in use>").finish(),
        }
    }
}

/// A virtio device on the MMIO transport.
#[derive(Debug)]
pub struct VirtioMmio {
    regs: Arc<Registers>,
    region: RegionRef,
    class: &'static DeviceClass,
}

impl VirtioMmio {
    /// Wrap `backend` in the MMIO transport.
    #[must_use]
    pub fn new(backend: Arc<dyn Backend>, class: &'static DeviceClass) -> VirtioMmio {
        let queues = backend.queue_count();
        let regs = Arc::new(Registers {
            state: Mutex::with_rank(LockRank::DEVICE, State::new(queues)),
            links: Mutex::with_rank(LockRank::LEAF, Links::default()),
            backend,
        });
        let region: RegionRef = Arc::new(Region::io(
            "virtio.mmio",
            REGISTER_WINDOW_LEN,
            Arc::clone(&regs) as Arc<dyn MemOps>,
        ));
        super::super::dt::publish(&region, Arc::downgrade(&regs) as Weak<dyn DtSource>);
        VirtioMmio {
            regs,
            region,
            class,
        }
    }

    /// The backend this transport carries.
    #[must_use]
    pub fn backend(&self) -> &Arc<dyn Backend> {
        &self.regs.backend
    }

    /// The device status register, as the driver last wrote it.
    #[must_use]
    pub fn status(&self) -> u32 {
        self.regs.state.lock().status
    }

    /// Whether the interrupt line is asserted.
    #[must_use]
    pub fn irq_asserted(&self) -> bool {
        self.regs.state.lock().interrupt_status != 0
    }

    /// Give the device the address space its DMA traverses.
    ///
    /// A realized machine does this through [`Instance::bind`]; a test that
    /// wires one by hand calls it directly.
    pub fn attach_space(&self, space: Arc<AddressSpace>, requester: RequesterId) {
        let mut links = self.regs.links.lock();
        links.space = Some(space);
        links.requester = requester;
    }

    /// Process queue `index` as a `QueueNotify` write would.
    pub fn notify(&self, index: u32) {
        self.regs.notify(index);
    }

    /// Tell the driver the configuration space changed (§4.2.2).
    ///
    /// Bumps `ConfigGeneration` so a driver reading a multi-word configuration
    /// can tell that it straddled a change, and raises the configuration-change
    /// interrupt. Nothing in this build's two backends changes its
    /// configuration while running; a resizable disk or a network device whose
    /// link goes down would.
    pub fn signal_config_change(&self) {
        {
            let mut state = self.regs.state.lock();
            state.config_generation = state.config_generation.wrapping_add(1);
            state.interrupt_status |= INT_CONFIG_CHANGE;
        }
        self.regs.drive(true);
    }
}

impl Registers {
    /// Drive the interrupt line. Never called with the state lock held.
    fn drive(&self, asserted: bool) {
        let out = self.links.lock().out.clone();
        if let Some(out) = out {
            out.set(Level::from_bool(asserted));
        }
    }

    /// The feature word the driver is currently selecting.
    fn device_features(&self, sel: u32) -> u32 {
        let all = self.backend.features() | F_VERSION_1;
        match sel {
            0 => all as u32,
            1 => (all >> 32) as u32,
            // §6 reserves everything above bit 63; a selector past it reads
            // zero rather than wrapping around to word 0.
            _ => 0,
        }
    }

    /// Run every chain the driver has made available on `index`.
    ///
    /// The state lock is taken twice and held across nothing: the backend does
    /// DMA through the same space this notify arrived on (§4.7).
    fn notify(&self, index: u32) {
        let (space, requester) = {
            let links = self.links.lock();
            (links.space.clone(), links.requester)
        };
        let Some(space) = space else {
            return;
        };
        let Some(queue) = self.live_queue(index) else {
            return;
        };
        let q = Queue::new(queue.layout, &space, requester);
        let Ok(avail) = q.avail_idx() else {
            return;
        };

        let mut last = queue.last_avail;
        let mut used = queue.used_idx;
        let mut did_work = false;
        // `avail` wraps at 16 bits, so the comparison is a difference and never
        // an ordering — the driver's index passing ours by 32768 is not a
        // reason to stop (§2.7.6).
        while last != avail {
            let Ok(head) = q.avail_head(last) else {
                break;
            };
            let Ok(chain) = q.chain(head) else {
                break;
            };
            let written = self.backend.handle(index as usize, &q, &chain);
            let Ok(next) = q.publish(used, head, written) else {
                break;
            };
            used = next;
            last = last.wrapping_add(1);
            did_work = true;
        }

        let raise = {
            let mut state = self.state.lock();
            let Some(slot) = state.queues.get_mut(index as usize) else {
                return;
            };
            slot.last_avail = last;
            slot.used_idx = used;
            if did_work {
                state.interrupt_status |= INT_USED_BUFFER;
            }
            state.interrupt_status != 0
        };
        if did_work {
            self.drive(raise);
        }
    }

    /// The queue `index`, if the driver has finished setting it up and the
    /// device is running.
    fn live_queue(&self, index: u32) -> Option<QueueState> {
        let state = self.state.lock();
        if state.status & STATUS_DRIVER_OK == 0 {
            return None;
        }
        let slot = state.queues.get(index as usize).copied()?;
        slot.layout.is_live().then_some(slot)
    }

    /// Return every register to its power-on value and tell the backend.
    fn reset(&self) {
        {
            let mut state = self.state.lock();
            *state = State::new(state.queues.len());
        }
        self.backend.reset();
        self.drive(false);
    }

    fn read_register(&self, offset: u64) -> u32 {
        let mut state = self.state.lock();
        match offset {
            0x000 => MAGIC,
            0x004 => VERSION,
            0x008 => self.backend.device_id(),
            0x00c => VENDOR_ID,
            0x010 => self.device_features(state.device_features_sel),
            0x034 => QUEUE_SIZE_MAX,
            0x044 => u32::from(
                state
                    .queues
                    .get(state.queue_sel as usize)
                    .is_some_and(|q| q.layout.ready),
            ),
            0x060 => state.interrupt_status,
            0x070 => state.status,
            0x0fc => state.config_generation,
            // Write-only registers, and every reserved word: read as zero
            // (§4.2.2). Better than a fault — a driver that reads back what it
            // wrote to `QueueNum` gets a wrong answer rather than a crash, and
            // the specification says it may not do that anyway.
            _ => {
                let _ = &mut state;
                0
            }
        }
    }

    fn write_register(&self, offset: u64, value: u32) {
        // The two writes that act outward — a notify and a reset — are done
        // after the state lock is released.
        enum After {
            Nothing,
            Notify(u32),
            Reset,
            Interrupt(bool),
        }
        let after = {
            let mut state = self.state.lock();
            let sel = state.queue_sel as usize;
            match offset {
                0x014 => {
                    state.device_features_sel = value;
                    After::Nothing
                }
                0x020 => {
                    let word = state.driver_features_sel.min(1) as usize;
                    if state.driver_features_sel < 2 {
                        state.driver_features[word] = value;
                    }
                    After::Nothing
                }
                0x024 => {
                    state.driver_features_sel = value;
                    After::Nothing
                }
                0x030 => {
                    state.queue_sel = value;
                    After::Nothing
                }
                0x038 => {
                    if let Some(q) = state.queues.get_mut(sel) {
                        // A driver may not ask for more than QueueNumMax, and
                        // the size must be a power of two (§2.7).
                        let size = value.min(QUEUE_SIZE_MAX);
                        q.layout.size = if size.is_power_of_two() { size } else { 0 };
                    }
                    After::Nothing
                }
                0x044 => {
                    if let Some(q) = state.queues.get_mut(sel) {
                        q.layout.ready = value & 1 != 0;
                        if !q.layout.ready {
                            // §4.2.2: writing zero after a reset of the queue
                            // means the driver is done with it.
                            q.last_avail = 0;
                            q.used_idx = 0;
                        }
                    }
                    After::Nothing
                }
                0x050 => After::Notify(value),
                0x064 => {
                    state.interrupt_status &= !value;
                    After::Interrupt(state.interrupt_status != 0)
                }
                0x070 => {
                    if value == 0 {
                        After::Reset
                    } else {
                        let mut status = value;
                        // §2.1: the device refuses FEATURES_OK if the driver
                        // did not accept a feature set it can work with. A
                        // modern device requires VIRTIO_F_VERSION_1.
                        if status & STATUS_FEATURES_OK != 0 {
                            let accepted = u64::from(state.driver_features[0])
                                | (u64::from(state.driver_features[1]) << 32);
                            if accepted & F_VERSION_1 == 0 {
                                status &= !STATUS_FEATURES_OK;
                            }
                        }
                        state.status = status
                            & (STATUS_ACKNOWLEDGE
                                | STATUS_DRIVER
                                | STATUS_DRIVER_OK
                                | STATUS_FEATURES_OK
                                | STATUS_NEEDS_RESET
                                | STATUS_FAILED);
                        After::Nothing
                    }
                }
                0x080 => {
                    set_low(&mut state, sel, |l| &mut l.desc, value);
                    After::Nothing
                }
                0x084 => {
                    set_high(&mut state, sel, |l| &mut l.desc, value);
                    After::Nothing
                }
                0x090 => {
                    set_low(&mut state, sel, |l| &mut l.avail, value);
                    After::Nothing
                }
                0x094 => {
                    set_high(&mut state, sel, |l| &mut l.avail, value);
                    After::Nothing
                }
                0x0a0 => {
                    set_low(&mut state, sel, |l| &mut l.used, value);
                    After::Nothing
                }
                0x0a4 => {
                    set_high(&mut state, sel, |l| &mut l.used, value);
                    After::Nothing
                }
                _ => After::Nothing,
            }
        };
        match after {
            After::Nothing => {}
            After::Notify(index) => self.notify(index),
            After::Reset => self.reset(),
            After::Interrupt(level) => self.drive(level),
        }
    }
}

/// Set the low half of one of a queue's ring addresses.
fn set_low(state: &mut State, sel: usize, field: fn(&mut Layout) -> &mut u64, value: u32) {
    if let Some(q) = state.queues.get_mut(sel) {
        let slot = field(&mut q.layout);
        *slot = (*slot & 0xffff_ffff_0000_0000) | u64::from(value);
    }
}

/// Set the high half of one of a queue's ring addresses.
fn set_high(state: &mut State, sel: usize, field: fn(&mut Layout) -> &mut u64, value: u32) {
    if let Some(q) = state.queues.get_mut(sel) {
        let slot = field(&mut q.layout);
        *slot = (*slot & 0xffff_ffff) | (u64::from(value) << 32);
    }
}

impl MemOps for Registers {
    fn read(&self, offset: u64, dst: &mut [u8], _attrs: MemAttrs) -> MemResult {
        if offset >= CONFIG_OFFSET {
            // The configuration space is the device's own, and is accessed at
            // whatever width its layout uses (§4.2.2).
            self.backend.config_read(offset - CONFIG_OFFSET, dst);
            return Ok(());
        }
        if dst.len() != 4 || !offset.is_multiple_of(4) {
            // Every transport register is a naturally aligned 32-bit word.
            return Err(BusError::BadAccess);
        }
        dst.copy_from_slice(&self.read_register(offset).to_le_bytes());
        Ok(())
    }

    fn write(&self, offset: u64, src: &[u8], attrs: MemAttrs) -> MemResult {
        if attrs.debug {
            // Writing `QueueNotify` performs I/O and writing `Status` resets
            // the device; neither can be made side-effect free.
            return Err(BusError::BadAccess);
        }
        if offset >= CONFIG_OFFSET {
            self.backend.config_write(offset - CONFIG_OFFSET, src);
            return Ok(());
        }
        if src.len() != 4 || !offset.is_multiple_of(4) {
            return Err(BusError::BadAccess);
        }
        self.write_register(offset, u32::from_le_bytes([src[0], src[1], src[2], src[3]]));
        Ok(())
    }

    fn constraints(&self) -> AccessConstraints {
        // Not `word(U32)`: the configuration space above `0x100` is read a
        // byte at a time by a driver that does not know its layout, so the
        // width check belongs in the handler where the offset is known.
        AccessConstraints {
            min: Width::U8,
            max: Width::U64,
            natural_alignment: true,
            endian: Endian::Little,
            allow_bulk: false,
            secure_only: false,
            privileged_only: false,
            drives_data_bus: true,
        }
    }
}

impl DtSource for Registers {
    fn dt_spec(&self) -> NodeSpec {
        let mut spec = NodeSpec::peripheral("virtio_mmio", &["virtio,mmio"]);
        spec.irq_wire = self.links.lock().irq_wire;
        spec
    }
}

impl Device for VirtioMmio {
    fn class(&self) -> &'static DeviceClass {
        self.class
    }

    fn realize(&self, _ctx: &mut RealizeCtx<'_>) -> Result<()> {
        Ok(())
    }

    fn reset(&self, _kind: ResetKind) {
        self.regs.reset();
    }

    fn region(&self, name: &str) -> Option<RegionRef> {
        matches!(name, "" | "regs").then(|| Arc::clone(&self.region))
    }

    fn connect(&self, port: &str, source: WireSource) -> Result<()> {
        if port != "irq" {
            return Err(Error::Config {
                at: port.to_string(),
                message: String::from("a virtio-mmio device drives one pin, `irq`"),
            });
        }
        let mut links = self.regs.links.lock();
        // Recorded so the device tree can ask the PLIC which source this net
        // lands on, rather than having the number written down twice.
        links.irq_wire = Some(source.id());
        links.out = Some(source);
        Ok(())
    }

    fn announce(&self, port: &str) {
        if port == "irq" {
            let asserted = self.regs.state.lock().interrupt_status != 0;
            self.regs.drive(asserted);
        }
    }

    fn save(&self, w: &mut ChunkWriter<'_>) -> Result<()> {
        let state = self.regs.state.lock();
        w.write_u32(state.device_features_sel)?;
        w.write_u32(state.driver_features_sel)?;
        w.write_u32(state.driver_features[0])?;
        w.write_u32(state.driver_features[1])?;
        w.write_u32(state.queue_sel)?;
        w.write_u32(state.status)?;
        w.write_u32(state.interrupt_status)?;
        w.write_u32(state.config_generation)?;
        w.write_seq_len(state.queues.len() as u64)?;
        for q in &state.queues {
            w.write_u32(q.layout.size)?;
            w.write_u64(q.layout.desc)?;
            w.write_u64(q.layout.avail)?;
            w.write_u64(q.layout.used)?;
            w.write_bool(q.layout.ready)?;
            w.write_u16(q.last_avail)?;
            w.write_u16(q.used_idx)?;
        }
        drop(state);
        self.regs.backend.save(w)
    }

    fn load(&self, r: &mut ChunkReader<'_>) -> Result<()> {
        let queues = self.regs.state.lock().queues.len();
        let mut state = State::new(queues);
        state.device_features_sel = r.read_u32()?;
        state.driver_features_sel = r.read_u32()?;
        state.driver_features[0] = r.read_u32()?;
        state.driver_features[1] = r.read_u32()?;
        state.queue_sel = r.read_u32()?;
        state.status = r.read_u32()?;
        state.interrupt_status = r.read_u32()?;
        state.config_generation = r.read_u32()?;
        let count = r.read_seq_len(29)? as usize;
        if count != queues {
            return Err(Error::State(format!(
                "snapshot has {count} virtqueue(s), this device has {queues}"
            )));
        }
        for q in &mut state.queues {
            q.layout.size = r.read_u32()?;
            q.layout.desc = r.read_u64()?;
            q.layout.avail = r.read_u64()?;
            q.layout.used = r.read_u64()?;
            q.layout.ready = r.read_bool()?;
            q.last_avail = r.read_u16()?;
            q.used_idx = r.read_u16()?;
        }
        let asserted = state.interrupt_status != 0;
        *self.regs.state.lock() = state;
        self.regs.backend.load(r)?;
        self.regs.drive(asserted);
        Ok(())
    }
}

impl Instance for VirtioMmio {
    fn bind(&self, ctx: &BindCtx<'_>) -> Result<()> {
        let space = ctx.space().ok_or_else(|| Error::Config {
            at: ctx.path().to_string(),
            message: String::from(
                "a virtio device is a bus master and needs the address space its \
                 descriptors live in (`space = mem`)",
            ),
        })?;
        self.attach_space(Arc::clone(space), ctx.requester());
        Ok(())
    }
}

/// A chain, split into what the device may read and what it may write.
///
/// A convenience for backends, which all want the same two numbers.
#[must_use]
pub fn chain_lengths(chain: &[Descriptor]) -> (u64, u64) {
    (Queue::readable_len(chain), Queue::writable_len(chain))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::space::{RamStore, Region as CoreRegion};
    use crate::core::value::Width as W;

    /// A transport over a backend that records what it was asked to do.
    #[derive(Debug, Default)]
    struct Echo {
        calls: Mutex<u32>,
    }

    impl Backend for Echo {
        fn device_id(&self) -> u32 {
            0xbeef
        }

        fn queue_count(&self) -> usize {
            1
        }

        fn config_read(&self, _offset: u64, dst: &mut [u8]) {
            dst.fill(0xa5);
        }

        fn handle(&self, _queue: usize, q: &Queue<'_>, chain: &[Descriptor]) -> u32 {
            *self.calls.lock() += 1;
            q.write_chain(chain, 0, b"ok").unwrap_or(0) as u32
        }

        fn reset(&self) {
            *self.calls.lock() = 0;
        }
    }

    struct Fixture {
        device: VirtioMmio,
        space: Arc<AddressSpace>,
        echo: Arc<Echo>,
    }

    static ECHO_CLASS: DeviceClass = DeviceClass {
        name: "virtio.test",
        version: 1,
        summary: "a virtio device for the transport's own tests",
        properties: &[],
        construct: |_| Err(Error::Unimplemented("test only")),
    };

    const DESC: u64 = 0x1000;
    const AVAIL: u64 = 0x2000;
    const USED: u64 = 0x3000;
    const BUF: u64 = 0x4000;

    impl Fixture {
        fn new() -> Fixture {
            let echo = Arc::new(Echo::default());
            let device = VirtioMmio::new(Arc::clone(&echo) as Arc<dyn Backend>, &ECHO_CLASS);
            let space = AddressSpace::new("mem", 64);
            space
                .topology()
                .map(CoreRegion::ram("ram", Arc::new(RamStore::new(0x1_0000))), 0)
                .unwrap();
            let space = Arc::new(space);
            device.attach_space(Arc::clone(&space), RequesterId(2));
            Fixture {
                device,
                space,
                echo,
            }
        }

        fn read(&self, offset: u64) -> u32 {
            let mut bytes = [0u8; 4];
            self.device
                .regs
                .read(offset, &mut bytes, MemAttrs::DEFAULT)
                .expect("a word read is legal");
            u32::from_le_bytes(bytes)
        }

        fn write(&self, offset: u64, value: u32) {
            self.device
                .regs
                .write(offset, &value.to_le_bytes(), MemAttrs::DEFAULT)
                .expect("a word write is legal");
        }

        fn poke(&self, at: u64, width: W, value: u64) {
            self.space
                .write(at, width, value, MemAttrs::DEFAULT)
                .unwrap();
        }

        /// Take the device through the whole §2.1 handshake and set up queue 0.
        fn bring_up(&self) {
            self.write(0x070, STATUS_ACKNOWLEDGE);
            self.write(0x070, STATUS_ACKNOWLEDGE | STATUS_DRIVER);
            self.write(0x024, 1);
            self.write(0x020, 1); // VIRTIO_F_VERSION_1 is bit 32
            self.write(
                0x070,
                STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK,
            );
            self.write(0x030, 0);
            self.write(0x038, 8);
            self.write(0x080, DESC as u32);
            self.write(0x084, 0);
            self.write(0x090, AVAIL as u32);
            self.write(0x094, 0);
            self.write(0x0a0, USED as u32);
            self.write(0x0a4, 0);
            self.write(0x044, 1);
            self.write(
                0x070,
                STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK | STATUS_DRIVER_OK,
            );
        }

        /// Offer one writable descriptor at `BUF`.
        fn offer(&self, idx: u16) {
            self.poke(DESC, W::U64, BUF);
            self.poke(DESC + 8, W::U32, 8);
            self.poke(
                DESC + 12,
                W::U16,
                u64::from(super::super::queue::DESC_F_WRITE),
            );
            self.poke(DESC + 14, W::U16, 0);
            self.poke(AVAIL + 4, W::U16, 0);
            self.poke(AVAIL + 2, W::U16, u64::from(idx));
        }
    }

    #[test]
    fn the_identity_registers_are_what_a_driver_probes_for() {
        let f = Fixture::new();
        assert_eq!(f.read(0x000), MAGIC);
        assert_eq!(f.read(0x004), VERSION, "modern, not legacy");
        assert_eq!(f.read(0x008), 0xbeef);
        assert_eq!(f.read(0x00c), VENDOR_ID);
        assert_eq!(f.read(0x034), QUEUE_SIZE_MAX);
    }

    #[test]
    fn the_feature_words_are_selected_one_at_a_time() {
        let f = Fixture::new();
        f.write(0x014, 0);
        assert_eq!(f.read(0x010), 0, "nothing in the low word");
        f.write(0x014, 1);
        assert_eq!(f.read(0x010), 1, "VIRTIO_F_VERSION_1 is bit 32");
        f.write(0x014, 2);
        assert_eq!(f.read(0x010), 0, "and nothing above 63");
    }

    #[test]
    fn features_ok_is_refused_unless_the_driver_accepted_version_1() {
        // §2.1: the device gets to say no, and a driver that ignores this is
        // one that would otherwise be handed a legacy layout it did not ask
        // for.
        let f = Fixture::new();
        f.write(0x070, STATUS_ACKNOWLEDGE | STATUS_DRIVER);
        f.write(
            0x070,
            STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK,
        );
        assert_eq!(f.read(0x070) & STATUS_FEATURES_OK, 0, "refused");

        f.write(0x024, 1);
        f.write(0x020, 1);
        f.write(
            0x070,
            STATUS_ACKNOWLEDGE | STATUS_DRIVER | STATUS_FEATURES_OK,
        );
        assert_eq!(f.read(0x070) & STATUS_FEATURES_OK, STATUS_FEATURES_OK);
    }

    #[test]
    fn a_notify_before_driver_ok_does_nothing() {
        let f = Fixture::new();
        f.offer(1);
        f.write(0x050, 0);
        assert_eq!(*f.echo.calls.lock(), 0);
    }

    #[test]
    fn a_notify_runs_every_available_chain_and_raises_the_interrupt() {
        let f = Fixture::new();
        f.bring_up();
        f.offer(1);
        f.write(0x050, 0);
        assert_eq!(*f.echo.calls.lock(), 1);
        assert_eq!(f.read(0x060), INT_USED_BUFFER);
        assert!(f.device.irq_asserted());

        // The used ring got the head and the length.
        let head = f.space.read(USED + 4, W::U32, MemAttrs::DEBUG).unwrap();
        let len = f.space.read(USED + 8, W::U32, MemAttrs::DEBUG).unwrap();
        assert_eq!((head, len), (0, 2));
        assert_eq!(f.space.read(USED + 2, W::U16, MemAttrs::DEBUG).unwrap(), 1);

        // Acknowledging drops the line.
        f.write(0x064, INT_USED_BUFFER);
        assert_eq!(f.read(0x060), 0);
        assert!(!f.device.irq_asserted());
    }

    #[test]
    fn a_second_notify_with_nothing_new_does_no_work() {
        let f = Fixture::new();
        f.bring_up();
        f.offer(1);
        f.write(0x050, 0);
        f.write(0x064, INT_USED_BUFFER);
        f.write(0x050, 0);
        assert_eq!(*f.echo.calls.lock(), 1, "the ring has not moved");
        assert!(!f.device.irq_asserted());
    }

    #[test]
    fn a_queue_size_that_is_not_a_power_of_two_is_refused() {
        let f = Fixture::new();
        f.write(0x030, 0);
        f.write(0x038, 7);
        f.write(0x044, 1);
        assert_eq!(f.read(0x044), 1, "ready is what the driver wrote");
        // But the queue is not live, so a notify does nothing.
        f.write(0x070, STATUS_DRIVER_OK);
        f.write(0x050, 0);
        assert_eq!(*f.echo.calls.lock(), 0);
    }

    #[test]
    fn writing_zero_to_status_resets_everything() {
        let f = Fixture::new();
        f.bring_up();
        f.offer(1);
        f.write(0x050, 0);
        assert!(f.device.irq_asserted());
        f.write(0x070, 0);
        assert_eq!(f.read(0x070), 0);
        assert_eq!(f.read(0x060), 0);
        assert!(!f.device.irq_asserted());
        assert_eq!(*f.echo.calls.lock(), 0, "and the backend was told");
    }

    #[test]
    fn the_configuration_space_is_the_backends_and_is_byte_addressable() {
        let f = Fixture::new();
        let mut byte = [0u8; 1];
        f.device
            .regs
            .read(CONFIG_OFFSET + 3, &mut byte, MemAttrs::DEFAULT)
            .unwrap();
        assert_eq!(byte[0], 0xa5);
    }

    #[test]
    fn a_register_access_that_is_not_an_aligned_word_is_refused() {
        let f = Fixture::new();
        assert!(
            f.device
                .regs
                .read(0x002, &mut [0u8; 4], MemAttrs::DEFAULT)
                .is_err()
        );
        assert!(
            f.device
                .regs
                .read(0x000, &mut [0u8; 2], MemAttrs::DEFAULT)
                .is_err()
        );
        assert!(
            f.device
                .regs
                .write(0x070, &[0u8; 4], MemAttrs::DEBUG)
                .is_err(),
            "and a debug write is refused outright"
        );
    }

    #[test]
    fn a_snapshot_round_trips_the_transport() {
        use crate::core::state::{MachineShape, Migrations, StateReader, StateWriter};

        let saved = Fixture::new();
        saved.bring_up();
        saved.offer(1);
        saved.write(0x050, 0);

        let mut shape = MachineShape::new();
        shape.add_device("vio", ECHO_CLASS.name).unwrap();
        let mut w = StateWriter::new(shape);
        {
            let mut chunk = w.chunk("vio", ECHO_CLASS.name, ECHO_CLASS.version).unwrap();
            saved.device.save(&mut chunk).unwrap();
        }
        let bytes = w.to_vec().unwrap();

        let restored = Fixture::new();
        let reader = StateReader::new(&bytes).unwrap();
        let chunk = reader
            .load(
                "vio",
                ECHO_CLASS.name,
                ECHO_CLASS.version,
                &Migrations::new(),
            )
            .unwrap();
        restored.device.load(&mut chunk.reader()).unwrap();

        assert_eq!(restored.read(0x070), saved.read(0x070));
        assert_eq!(restored.read(0x060), INT_USED_BUFFER);
        assert!(restored.device.irq_asserted());
        // And the device's position in the ring came back: re-notifying with
        // the same available index must not run the chain twice.
        restored.offer(1);
        restored.write(0x050, 0);
        assert_eq!(*restored.echo.calls.lock(), 0);
    }
}