ktstr 0.4.19

Test harness for Linux process schedulers
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
#![cfg(test)]
#![allow(unused_imports)]

use super::testing::*;
use super::*;
use std::io::Write;
use std::sync::atomic::Ordering;
use tempfile::tempfile;
use virtio_bindings::bindings::virtio_ring::VRING_DESC_F_WRITE;
use virtio_queue::desc::{RawDescriptor, split::Descriptor as SplitDescriptor};
use virtio_queue::mock::MockSplitQueue;
use vm_memory::Address;

#[test]
fn magic_version_device_id() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_MAGIC_VALUE), 0x7472_6976);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_VERSION), 2);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_DEVICE_ID), VIRTIO_ID_BLOCK);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_VENDOR_ID), 0);
}

#[test]
fn advertised_features_include_size_max_seg_max_blk_size_flush() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_DEVICE_FEATURES_SEL, 0);
    let lo = read_reg(&dev, VIRTIO_MMIO_DEVICE_FEATURES);
    write_reg(&mut dev, VIRTIO_MMIO_DEVICE_FEATURES_SEL, 1);
    let hi = read_reg(&dev, VIRTIO_MMIO_DEVICE_FEATURES);
    let features = (hi as u64) << 32 | lo as u64;
    assert_ne!(features & (1u64 << VIRTIO_F_VERSION_1), 0);
    assert_ne!(features & (1u64 << VIRTIO_BLK_F_BLK_SIZE), 0);
    assert_ne!(features & (1u64 << VIRTIO_BLK_F_SEG_MAX), 0);
    assert_ne!(features & (1u64 << VIRTIO_BLK_F_SIZE_MAX), 0);
    // F_FLUSH advertised so guest blk-mq can issue REQ_OP_FLUSH
    // at metadata-commit boundaries — btrfs depends on this for
    // tree-consistency ordering.
    assert_ne!(features & (1u64 << VIRTIO_BLK_F_FLUSH), 0);
}

#[test]
fn advertised_features_include_event_idx() {
    // VIRTIO_RING_F_EVENT_IDX is bit 29, in the low 32-bit half.
    // The guest needs the bit set during feature negotiation so
    // it populates `used_event` in the avail ring; without
    // advertisement the device cannot suppress IRQs even when
    // the corresponding wire-up lands.
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_DEVICE_FEATURES_SEL, 0);
    let lo = read_reg(&dev, VIRTIO_MMIO_DEVICE_FEATURES);
    write_reg(&mut dev, VIRTIO_MMIO_DEVICE_FEATURES_SEL, 1);
    let hi = read_reg(&dev, VIRTIO_MMIO_DEVICE_FEATURES);
    let features = (hi as u64) << 32 | lo as u64;
    assert_ne!(features & (1u64 << VIRTIO_RING_F_EVENT_IDX), 0);
}

#[test]
fn capacity_in_config_space() {
    // 256 MB / 512 = 524_288 sectors. The default capacity is
    // 256 MB (mkfs.btrfs minimum).
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    assert_eq!(dev.capacity_sectors(), 524_288);
    let mut buf = [0u8; 8];
    dev.mmio_read(0x100, &mut buf);
    assert_eq!(u64::from_le_bytes(buf), 524_288);
}

#[test]
fn blk_size_in_config_space() {
    // VIRTIO_BLK_F_BLK_SIZE puts the logical block size at
    // offset 0x14 in config space.
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mut buf = [0u8; 4];
    dev.mmio_read(0x100 + 0x14, &mut buf);
    assert_eq!(u32::from_le_bytes(buf), VIRTIO_BLK_SECTOR_SIZE);
}

#[test]
fn reset_bumps_config_generation() {
    // virtio-v1.2 §4.2.2.1: config_generation must change when
    // any config-space field changes. Reset always bumps (rather
    // than tracking specific field mutations) so a re-binding
    // driver re-reads config space cleanly. v0 capacity is
    // fixed for the device's lifetime, so today the bump is
    // pure defense-in-depth — but if a future patch resizes
    // between resets the guest must observe the new generation
    // to invalidate its cached read.
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let gen0 = read_reg(&dev, VIRTIO_MMIO_CONFIG_GENERATION);
    // Drive through a full status handshake then write 0 to
    // trigger reset.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);
    let gen1 = read_reg(&dev, VIRTIO_MMIO_CONFIG_GENERATION);
    assert_eq!(gen1, gen0.wrapping_add(1));
    // Second cycle bumps again.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);
    let gen2 = read_reg(&dev, VIRTIO_MMIO_CONFIG_GENERATION);
    assert_eq!(gen2, gen1.wrapping_add(1));
}

/// Reset rebuilds the throttle buckets from the captured
/// `DiskThrottle`. virtio-v1.2 §2.1: a reset returns the
/// device to its initial state — bucket fill is part of that
/// state. An adversarial guest must not be able to drain the
/// bucket and then issue a reset to bypass the rate limit;
/// the bucket must be re-armed to its starting capacity.
#[test]
fn reset_rebuilds_throttle_buckets() {
    let throttle = DiskThrottle {
        iops: std::num::NonZeroU64::new(4),
        bytes_per_sec: std::num::NonZeroU64::new(8192),
        iops_burst_capacity: None,
        bytes_burst_capacity: None,
    };
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, throttle);
    // Pin last_refill so consume() doesn't passively refill in
    // the test, then drain both buckets.
    let now = std::time::Instant::now();
    dev.worker
        .state_mut()
        .ops_bucket
        .set_last_refill_for_test(now);
    dev.worker
        .state_mut()
        .bytes_bucket
        .set_last_refill_for_test(now);
    assert!(dev.worker.state_mut().ops_bucket.consume(4));
    assert!(dev.worker.state_mut().bytes_bucket.consume(8192));
    // Re-pin so the post-consume can_consume reflects the
    // drained state, not a passive refill.
    dev.worker
        .state_mut()
        .ops_bucket
        .set_last_refill_for_test(now);
    dev.worker
        .state_mut()
        .bytes_bucket
        .set_last_refill_for_test(now);
    assert!(
        !dev.worker.state_mut().ops_bucket.can_consume(1),
        "ops bucket must be drained before reset",
    );
    assert!(
        !dev.worker.state_mut().bytes_bucket.can_consume(1),
        "bytes bucket must be drained before reset",
    );

    // STATUS=0 triggers reset() which (in test mode) calls
    // reset_engine_inline → buckets_from_throttle(self.throttle).
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    // Post-reset: buckets are back to capacity. iops=4 →
    // capacity=4 ops; bytes=8192 → capacity=8192 bytes.
    assert!(
        dev.worker.state_mut().ops_bucket.can_consume(4),
        "ops bucket must be refilled to capacity by reset",
    );
    assert!(
        dev.worker.state_mut().bytes_bucket.can_consume(8192),
        "bytes bucket must be refilled to capacity by reset",
    );
}

/// Reset clears the request queue's next_avail / used.idx
/// state. Direct verification: walk through a status
/// handshake, then call reset and observe the queue back at
/// its initial avail-cursor. (The QueueT API doesn't expose
/// `next_avail()` directly except via `set_next_avail` round
/// trip; we use the test-mode `Queue` alias which does have
/// `next_avail()` accessible via methods.)
#[test]
fn reset_clears_queue_next_avail() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Move next_avail forward from 0 to a non-zero value via
    // the set_next_avail API (test mode: Queue exposes it on
    // the QueueT alias).
    dev.worker.queues[REQ_QUEUE].set_next_avail(7);
    assert_eq!(dev.worker.queues[REQ_QUEUE].next_avail(), 7);

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    assert_eq!(
        dev.worker.queues[REQ_QUEUE].next_avail(),
        0,
        "reset must zero next_avail (Queue::reset behaviour)",
    );
}

/// Reset drains pending irq_evt counter. Race window: a
/// worker that race-fired the IRQ between its last add_used
/// and the stop signal would otherwise leave a non-zero
/// eventfd counter. KVM's irqfd would deliver the GSI to the
/// guest after reset (with the used ring now empty post
/// q.reset()), causing virtblk_done to spin chasing a
/// non-existent completion. The reset path drains the
/// eventfd in Phase 3 to close that window.
#[test]
fn reset_drains_irq_evt_pending_count() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Simulate a worker IRQ write that landed before the
    // reset (in test mode no worker exists; we write directly
    // to the eventfd to model the race).
    dev.irq_evt().write(1).expect("seed irq eventfd counter");

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    // Post-reset: a non-blocking read returns WouldBlock
    // (counter cleared by the reset's drain). If the drain
    // had not run, the read would have returned the count
    // (1) instead.
    match dev.irq_evt().read() {
        Ok(n) => panic!("expected post-reset irq_evt counter drained, but read returned {n}",),
        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
        Err(e) => panic!("unexpected irq_evt read error after reset: {e}"),
    }
}

/// Reset clears `interrupt_status`. The MMIO read of
/// INTERRUPT_STATUS post-reset must see 0 — a stale
/// INT_VRING bit would mislead the guest into believing a
/// completion is pending when the queue is empty.
#[test]
fn reset_clears_interrupt_status() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Set INT_VRING to model a pending interrupt before reset.
    dev.interrupt_status
        .store(VIRTIO_MMIO_INT_VRING, Ordering::Release);
    assert_eq!(
        read_reg(&dev, VIRTIO_MMIO_INTERRUPT_STATUS),
        VIRTIO_MMIO_INT_VRING,
        "pre-reset: bit set as a precondition",
    );

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    assert_eq!(
        read_reg(&dev, VIRTIO_MMIO_INTERRUPT_STATUS),
        0,
        "reset must clear interrupt_status (Phase 3)",
    );
}

/// Reset re-arms the `mem_unset_warned` latch so a wiring
/// bug after reset (kick before set_mem completes the
/// post-reset rebind) surfaces a fresh warning instead of
/// being suppressed by a latch held from the previous
/// device lifetime.
#[test]
fn reset_clears_mem_unset_warned_latch() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Pre-condition: latch the warning.
    dev.mem_unset_warned.store(true, Ordering::Relaxed);
    assert!(dev.mem_unset_warned.load(Ordering::Relaxed));

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    assert!(
        !dev.mem_unset_warned.load(Ordering::Relaxed),
        "reset must re-arm the queue-notify-before-set_mem latch",
    );
}

/// End-to-end re-bind contract: after a reset, a guest that
/// re-runs the FSM (ACK→DRV→FEAT_OK→queue config→READY→
/// DRIVER_OK) and posts a new chain must observe the device
/// service it just like a freshly-constructed device.
/// Counters are cumulative across reset — the pre-reset
/// `reads_completed=1` carries over and the post-reset chain
/// makes it 2 — but the queue's used.idx (device-published)
/// resets and advances to 1 on the post-reset completion.
/// Pins the e2e re-bind contract: queue cursor resets to 0,
/// counters carry across.
///
/// Modeling note: a real guest, after reset, allocates a
/// fresh queue (avail.idx=0, used.idx=0). MockSplitQueue is
/// the test-side surrogate for the "guest" — it tracks the
/// guest-side avail.idx in guest memory. To model the guest's
/// re-bind, we explicitly zero avail.idx and used.idx in
/// guest memory after the device's reset. Without this, the
/// avail ring still carries the pre-reset chain at
/// avail.ring[0]=0, and the second build_desc_chain bumps
/// avail.idx to 2 → device drains BOTH entries (which both
/// reference the same overwritten descriptor table slot,
/// counting reads_completed twice for a single chain build).
#[test]
fn reset_then_reactivate_processes_new_chain() {
    let cap = 4096u64;
    let f = make_backed_file_with_pattern(cap, 0xAB);
    let mut dev = VirtioBlk::new(f, cap, DiskThrottle::default());
    let mem = make_chain_test_mem();
    let mock = MockSplitQueue::create(&mem, GuestAddress(0), 16);
    let header_addr = GuestAddress(0x4000);
    let data_addr = GuestAddress(0x5000);
    let status_addr = GuestAddress(0x6000);

    // Phase A — first chain through the full pipeline.
    write_blk_header(&mem, header_addr, VIRTIO_BLK_T_IN, 0);
    let descs = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            0,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    mock.build_desc_chain(&descs).expect("build chain 1");
    dev.set_mem(mem.clone());
    wire_device_to_mock(&mut dev, &mock);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);

    let mut s = [0u8; 1];
    mem.read_slice(&mut s, status_addr).unwrap();
    assert_eq!(
        s[0], VIRTIO_BLK_S_OK as u8,
        "first chain must complete S_OK"
    );
    assert_eq!(
        dev.counters().reads_completed.load(Ordering::Relaxed),
        1,
        "first chain bumps reads_completed to 1",
    );

    // Phase B — reset.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        0,
        "device_status must zero on reset"
    );

    // Phase C — model the guest's re-bind: zero the guest's
    // avail.idx and used.idx in guest memory. avail.idx lives
    // at avail_addr+2 (after the 2-byte flags field); used.idx
    // lives at used_addr+2 (same offset on the used ring).
    // Layout per virtio-v1.2 §2.7.6 (avail ring) and §2.7.8
    // (used ring): both rings start with a 2-byte flags
    // field, then a 2-byte idx, then the per-entry slots.
    let avail_idx_addr = mock.avail_addr().checked_add(2).unwrap();
    let used_idx_addr = mock.used_addr().checked_add(2).unwrap();
    mem.write_obj(0u16, avail_idx_addr).unwrap();
    mem.write_obj(0u16, used_idx_addr).unwrap();
    // Plant a fresh status sentinel so we can detect the
    // post-reset write distinctly from the pre-reset one.
    mem.write_slice(&[0xEEu8], status_addr).unwrap();
    // Re-build the chain. With avail.idx zeroed,
    // build_desc_chain stores the chain at avail.ring[0] and
    // bumps avail.idx to 1 — exactly what a freshly
    // re-bound guest does.
    mock.build_desc_chain(&descs).expect("build chain 2");
    wire_device_to_mock(&mut dev, &mock);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);

    let mut s = [0u8; 1];
    mem.read_slice(&mut s, status_addr).unwrap();
    assert_eq!(
        s[0], VIRTIO_BLK_S_OK as u8,
        "post-reset chain must complete S_OK"
    );

    let c = dev.counters();
    // Counters are cumulative across the reset.
    assert_eq!(
        c.reads_completed.load(Ordering::Relaxed),
        2,
        "reads_completed is cumulative across reset (1 pre + 1 post)",
    );
    assert_eq!(c.io_errors.load(Ordering::Relaxed), 0);

    // The guest's used ring was zeroed at re-bind; the
    // device's q.reset() also zeroed its internal used cursor.
    // After the post-reset chain completes, used.idx advances
    // to 1.
    let used_idx: u16 = mem.read_obj(used_idx_addr).expect("read used.idx");
    assert_eq!(
        used_idx, 1,
        "used.idx must be 1 — only the post-reset chain is on \
             the freshly-rebound used ring",
    );
}

/// Counter persistence pin. Reset must NOT zero
/// `VirtioBlkCounters` — they are cumulative for the
/// device's lifetime. Operators monitoring failure-dump
/// counters depend on observing a monotonically
/// non-decreasing series across re-binds.
#[test]
fn reset_preserves_counters() {
    let cap = 4096u64;
    let f = make_backed_file_with_pattern(cap, 0xAB);
    let mut dev = VirtioBlk::new(f, cap, DiskThrottle::default());
    let mem = make_chain_test_mem();
    let mock = MockSplitQueue::create(&mem, GuestAddress(0), 16);
    let header_addr = GuestAddress(0x4000);
    let data_addr = GuestAddress(0x5000);
    let status_addr = GuestAddress(0x6000);
    write_blk_header(&mem, header_addr, VIRTIO_BLK_T_IN, 0);
    let descs = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            0,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    mock.build_desc_chain(&descs).expect("build chain");
    dev.set_mem(mem.clone());
    wire_device_to_mock(&mut dev, &mock);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);

    // Pre-reset snapshot.
    let c = dev.counters();
    let pre_reads = c.reads_completed.load(Ordering::Relaxed);
    let pre_bytes_read = c.bytes_read.load(Ordering::Relaxed);
    let pre_io_errors = c.io_errors.load(Ordering::Relaxed);
    let pre_throttled = c.throttled_count.load(Ordering::Relaxed);
    assert_eq!(pre_reads, 1, "precondition: one read completed");

    // Reset.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    // Post-reset: every counter retains its pre-reset value.
    assert_eq!(
        c.reads_completed.load(Ordering::Relaxed),
        pre_reads,
        "reads_completed must persist across reset",
    );
    assert_eq!(
        c.bytes_read.load(Ordering::Relaxed),
        pre_bytes_read,
        "bytes_read must persist across reset",
    );
    assert_eq!(
        c.io_errors.load(Ordering::Relaxed),
        pre_io_errors,
        "io_errors must persist across reset",
    );
    assert_eq!(
        c.throttled_count.load(Ordering::Relaxed),
        pre_throttled,
        "throttled_count must persist across reset",
    );
}

/// Reset rebuilds the throttle bucket AND the rebuild is
/// real (not a no-op). Sequence: iops=1 → first chain
/// consumes the only token → reset → second chain runs
/// (bucket refilled to capacity) → THIRD chain on the same
/// post-reset notify must stall (capacity was 1, second
/// chain consumed it). Pins both halves of the
/// rebuild-then-still-throttling contract: a guest that
/// resets to bypass throttling sees the bucket back to 1, but
/// the rate limit immediately re-engages.
///
/// Modeling note: same as `reset_then_reactivate_processes_new_chain`
/// — after the device's reset, we zero the guest-side avail.idx /
/// used.idx in guest memory and use distinct descriptor table
/// offsets via `add_desc_chains` so the device pops chains B
/// and C as DISTINCT chains (not as duplicates of an
/// overwritten slot).
#[test]
fn reset_rebuilds_throttle_then_stalls_on_second_chain() {
    let cap = 4096u64;
    let throttle = DiskThrottle {
        iops: std::num::NonZeroU64::new(1),
        bytes_per_sec: None,
        iops_burst_capacity: None,
        bytes_burst_capacity: None,
    };
    let f = make_backed_file_with_pattern(cap, 0xAB);
    let mut dev = VirtioBlk::new(f, cap, throttle);
    let mem = make_chain_test_mem();
    // Queue size 16 with 3 descs per chain → table indices
    // 0..2 (A), 3..5 (B), 6..8 (C). 9 < 16 fits.
    let mock = MockSplitQueue::create(&mem, GuestAddress(0), 16);
    let header_addr = GuestAddress(0x4000);
    let data_addr = GuestAddress(0x5000);
    let status_addr_a = GuestAddress(0x6000);
    let status_addr_b = GuestAddress(0x6100);
    let status_addr_c = GuestAddress(0x6200);
    write_blk_header(&mem, header_addr, VIRTIO_BLK_T_IN, 0);
    let descs_chain_a = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            0,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr_a.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    // Chain A — fires the only iops token.
    mock.build_desc_chain(&descs_chain_a)
        .expect("build chain A");
    dev.set_mem(mem.clone());
    wire_device_to_mock(&mut dev, &mock);
    // Pin the bucket's last_refill so a microsecond between
    // chains can't passively grant a token.
    let now = std::time::Instant::now();
    dev.worker
        .state_mut()
        .ops_bucket
        .set_last_refill_for_test(now);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);
    assert_eq!(
        dev.counters().reads_completed.load(Ordering::Relaxed),
        1,
        "chain A must complete (the only iops token granted)",
    );

    // Reset — buckets rebuilt to capacity=1.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    // Model the guest re-bind: zero avail.idx and used.idx
    // (same modeling as reset_then_reactivate_processes_new_chain).
    // Per virtio-v1.2 §2.7.6/§2.7.8 both rings start with a
    // 2-byte flags field followed by a 2-byte idx field.
    let avail_idx_addr = mock.avail_addr().checked_add(2).unwrap();
    let used_idx_addr = mock.used_addr().checked_add(2).unwrap();
    mem.write_obj(0u16, avail_idx_addr).unwrap();
    mem.write_obj(0u16, used_idx_addr).unwrap();

    // Re-negotiate the FSM and queue config so chains B+C
    // dispatch end-to-end.
    wire_device_to_mock(&mut dev, &mock);

    // Re-pin so the post-reset notify doesn't passively
    // refill before chain B runs. wire_device_to_mock walks
    // the FSM which takes microseconds; even at iops=1 (1
    // token/sec ≈ 1 token / 1_000_000 μs) refill is
    // negligible, but pin for determinism.
    let now2 = std::time::Instant::now();
    dev.worker
        .state_mut()
        .ops_bucket
        .set_last_refill_for_test(now2);

    // Plant fresh status sentinels so we can verify what
    // landed.
    mem.write_slice(&[0xEEu8], status_addr_b).unwrap();
    mem.write_slice(&[0xEEu8], status_addr_c).unwrap();

    // Build chain B at descriptor table indices 3..5. The
    // guest-side avail.idx was just zeroed; add_desc_chains
    // with offset=3 places the chain at table[3..5] and
    // appends head_idx=3 to avail.ring[avail.idx], then
    // increments avail.idx → 1.
    let descs_chain_b = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            virtio_bindings::bindings::virtio_ring::VRING_DESC_F_NEXT as u16,
            4,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16
                | virtio_bindings::bindings::virtio_ring::VRING_DESC_F_NEXT as u16,
            5,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr_b.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    mock.add_desc_chains(&descs_chain_b, 3)
        .expect("add chain B at offset 3");

    // Build chain C at descriptor table indices 6..8.
    let descs_chain_c = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            virtio_bindings::bindings::virtio_ring::VRING_DESC_F_NEXT as u16,
            7,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16
                | virtio_bindings::bindings::virtio_ring::VRING_DESC_F_NEXT as u16,
            8,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr_c.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    mock.add_desc_chains(&descs_chain_c, 6)
        .expect("add chain C at offset 6");

    // Re-pin once more right before the final notify so the
    // test is deterministic regardless of how long the chain
    // building took.
    let now3 = std::time::Instant::now();
    dev.worker
        .state_mut()
        .ops_bucket
        .set_last_refill_for_test(now3);

    let pre_throttled = dev.counters().throttled_count.load(Ordering::Relaxed);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);

    // Chain B must succeed (iops=1 token granted by reset
    // refill). Chain C must stall — the post-reset bucket
    // had only 1 token and B consumed it.
    let c = dev.counters();
    assert_eq!(
        c.reads_completed.load(Ordering::Relaxed),
        2,
        "reads_completed: chain A pre-reset (1) + chain B post-reset (1)",
    );
    assert_eq!(
        c.throttled_count.load(Ordering::Relaxed),
        pre_throttled + 1,
        "chain C must stall: rebuilt bucket has capacity=1 (iops=1) \
             and chain B consumed it",
    );
    // Chain B's status: S_OK (bucket grants).
    let mut sb = [0u8; 1];
    mem.read_slice(&mut sb, status_addr_b).unwrap();
    assert_eq!(sb[0], VIRTIO_BLK_S_OK as u8, "chain B must complete S_OK");
    // Chain C's status: untouched sentinel (stalled, not
    // published).
    let mut sc = [0u8; 1];
    mem.read_slice(&mut sc, status_addr_c).unwrap();
    assert_eq!(
        sc[0], 0xEE,
        "chain C status must remain at sentinel (stall does not write status)",
    );
}

/// After reset, queue config writes are blocked until the
/// FSM walks back to FEATURES_OK. virtio-v1.2 §4.2.2: queue
/// address writes are valid only when FEATURES_OK is set
/// AND DRIVER_OK is NOT — i.e. the rebind window. A reset
/// drops device_status to 0, so any queue config write
/// before the FSM walks back to FEAT_OK must be a silent
/// drop. Pins the gate that prevents a post-reset guest from
/// stomping on queue addresses without a fresh handshake.
#[test]
fn reset_blocks_post_reset_queue_config() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Walk the FSM, plant a known QUEUE_DESC_LOW value, then reset.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << (VIRTIO_F_VERSION_1 - 32),
    );
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_DESC_LOW, 0xDEAD_BEEF);
    // Reset.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);
    // device_status is now 0; queue_config_allowed returns
    // false (requires S_FEAT set + DRIVER_OK clear).
    assert_eq!(dev.device_status.load(Ordering::Acquire), 0);
    // Attempt a queue config write without re-running the
    // FSM. Must be silently dropped.
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_DESC_LOW, 0xCAFE_BABE);

    // The queue's desc table address remains zero (set by
    // q.reset()). To verify, snapshot the queue's current
    // address: in test mode the BlkQueue alias is bare
    // `Queue`, which doesn't expose desc_table_address as a
    // public getter, so we infer the gate via the no-effect
    // check. A regression that lifted the gate would let
    // 0xCAFE_BABE land; with the gate, the write is dropped
    // and the device's internal queue cursor is unchanged.
    // Process_requests on an unset queue → no-op (no chains).
    // The behavioural test: build a chain via MockSplitQueue
    // (which would have set its OWN desc table addr), but
    // because the device's queue config is at 0 due to reset,
    // process_requests cannot pop anything. Verified
    // indirectly here by the device_status == 0 invariant +
    // queue_config_allowed gate logic; a direct address-readback
    // would require a private accessor we don't expose.
}

/// Reset drains a multi-write irq_evt counter. The eventfd
/// counter accumulates additively across writes; a single
/// `read()` returns the entire accumulated count and resets
/// to 0 (eventfd(2) counter mode). A regression that read
/// the counter only once when it could have been multi-writes
/// would leave residual counter — unlikely given counter
/// semantics, but pinned here.
#[test]
fn reset_drains_multi_write_irq_evt() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Three writes accumulate to counter=3.
    dev.irq_evt().write(1).expect("seed irq eventfd #1");
    dev.irq_evt().write(1).expect("seed irq eventfd #2");
    dev.irq_evt().write(1).expect("seed irq eventfd #3");

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);

    // Post-reset: counter must be drained — a single
    // counter-mode read returns the entire accumulated
    // value (3) and resets to 0, so the post-reset
    // non-blocking read is WouldBlock.
    match dev.irq_evt().read() {
        Ok(n) => panic!("expected post-reset irq_evt counter drained, but read returned {n}",),
        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
        Err(e) => panic!("unexpected irq_evt read error after reset: {e}"),
    }
}

/// Pre-rebind / post-reset gate: when `queues[REQ_QUEUE].ready()`
/// returns false, `drain_bracket_impl` early-returns
/// `DrainOutcome::Done` BEFORE the disable_notification /
/// pop_descriptor_chain / add_used pipeline. This pins the gate
/// at the top of `drain_bracket_impl` (`if !queues[REQ_QUEUE].ready()
/// { return DrainOutcome::Done; }`): a kick that lands while
/// the queue is not-ready must produce no observable side
/// effects — no used-ring update, no counter movement, no
/// irqfd write, no status-byte modification.
///
/// Setup: full FSM through DRIVER_OK so the queue is fully
/// wired, build a chain in the avail ring, then explicitly
/// call `set_ready(false)` to model the post-reset /
/// pre-rebind window. The kick that follows must be a no-op.
/// Without the gate, `disable_notification` would write to a
/// used-ring GPA the guest hasn't yet re-published, and
/// `pop_descriptor_chain` would walk the avail ring with
/// stale device-side state — both observable as guest-memory
/// clobber + used.idx advance + counter changes.
#[test]
fn drain_skipped_when_queue_not_ready() {
    let cap = 4096u64;
    let f = make_backed_file_with_pattern(cap, 0xAB);
    let mut dev = VirtioBlk::new(f, cap, DiskThrottle::default());
    let mem = make_chain_test_mem();
    let mock = MockSplitQueue::create(&mem, GuestAddress(0), 16);
    let header_addr = GuestAddress(0x4000);
    let data_addr = GuestAddress(0x5000);
    let status_addr = GuestAddress(0x6000);
    // Plant a fresh sentinel at the status byte — survival of
    // this byte is the post-test invariant.
    mem.write_slice(&[0xEEu8], status_addr).unwrap();
    write_blk_header(&mem, header_addr, VIRTIO_BLK_T_IN, 0);
    let descs = [
        RawDescriptor::from(SplitDescriptor::new(
            header_addr.0,
            VIRTIO_BLK_OUTHDR_SIZE as u32,
            0,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            data_addr.0,
            512,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
        RawDescriptor::from(SplitDescriptor::new(
            status_addr.0,
            1,
            VRING_DESC_F_WRITE as u16,
            0,
        )),
    ];
    mock.build_desc_chain(&descs).expect("build chain");
    dev.set_mem(mem.clone());
    // Walk FSM all the way to DRIVER_OK so the queue is fully
    // wired, then explicitly mark it not-ready.
    // wire_device_to_mock ends with set_ready(true); we revert
    // just that bit to model the pre-rebind state where
    // q.reset() has cleared ready but the guest hasn't yet
    // republished the queue addresses.
    wire_device_to_mock(&mut dev, &mock);
    dev.worker.queues[REQ_QUEUE].set_ready(false);
    assert!(
        !dev.worker.queues[REQ_QUEUE].ready(),
        "precondition: queue must be not-ready before notify",
    );

    // Snapshot every counter we want to assert "did not move".
    let c = dev.counters();
    let pre_reads = c.reads_completed.load(Ordering::Relaxed);
    let pre_writes = c.writes_completed.load(Ordering::Relaxed);
    let pre_flushes = c.flushes_completed.load(Ordering::Relaxed);
    let pre_io_errors = c.io_errors.load(Ordering::Relaxed);
    let pre_throttled = c.throttled_count.load(Ordering::Relaxed);
    let pre_bytes_read = c.bytes_read.load(Ordering::Relaxed);
    let pre_bytes_written = c.bytes_written.load(Ordering::Relaxed);

    // Fire QUEUE_NOTIFY. With the queue not-ready, the gate at
    // the top of drain_bracket_impl must early-return Done
    // before any side effects.
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NOTIFY, REQ_QUEUE as u32);

    // Status byte must remain at sentinel — drain didn't run.
    let mut s = [0u8; 1];
    mem.read_slice(&mut s, status_addr).unwrap();
    assert_eq!(
        s[0], 0xEE,
        "status byte must remain at sentinel — drain must be a \
             no-op when queue not ready",
    );

    // used.idx must remain 0 — no add_used.
    let used_idx: u16 = mem
        .read_obj(mock.used_addr().checked_add(2).unwrap())
        .expect("read used.idx");
    assert_eq!(used_idx, 0, "used.idx must be 0 — gate must skip add_used",);

    // Every counter must remain at its pre-notify snapshot.
    assert_eq!(c.reads_completed.load(Ordering::Relaxed), pre_reads);
    assert_eq!(c.writes_completed.load(Ordering::Relaxed), pre_writes);
    assert_eq!(c.flushes_completed.load(Ordering::Relaxed), pre_flushes);
    assert_eq!(c.io_errors.load(Ordering::Relaxed), pre_io_errors);
    assert_eq!(c.throttled_count.load(Ordering::Relaxed), pre_throttled);
    assert_eq!(c.bytes_read.load(Ordering::Relaxed), pre_bytes_read);
    assert_eq!(c.bytes_written.load(Ordering::Relaxed), pre_bytes_written);

    // irq_evt counter must remain 0 — no signal fired.
    // EFD_NONBLOCK means a non-readable eventfd returns
    // WouldBlock on read.
    match dev.irq_evt().read() {
        Ok(n) => panic!(
            "expected irq_evt not fired (counter=0/WouldBlock), but \
                 read returned {n} — the gate must not call \
                 irq_evt.write",
        ),
        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
        Err(e) => panic!("unexpected irq_evt read error: {e}"),
    }
}

#[test]
fn seg_max_in_config_space() {
    // VIRTIO_BLK_F_SEG_MAX puts the per-request max scatter-gather
    // segment count at offset 0x0C in config space (virtio-v1.2
    // §5.2.4). Without this the guest defaults max_segments to 1
    // and serialises every multi-page bio.
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mut buf = [0u8; 4];
    dev.mmio_read(0x100 + 0x0C, &mut buf);
    assert_eq!(u32::from_le_bytes(buf), VIRTIO_BLK_SEG_MAX);
}

#[test]
fn config_space_struct_layout_byte_for_byte() {
    // Read the entire 24-byte populated config-space layout via
    // a single mmio read and verify that every field lands at
    // the kernel-uapi-mandated offset:
    //   capacity (u64 LE) @ 0x00 — VIRTIO_BLK_DEFAULT_CAPACITY_BYTES / 512
    //   size_max (u32 LE) @ 0x08 — VIRTIO_BLK_SIZE_MAX
    //   seg_max  (u32 LE) @ 0x0C — VIRTIO_BLK_SEG_MAX
    //   geometry (4B zeroed) @ 0x10 — F_GEOMETRY not advertised
    //   blk_size (u32 LE) @ 0x14 — VIRTIO_BLK_SECTOR_SIZE
    // A regression in `repr(C, packed)` field ordering or padding
    // would shift any field by a byte and break this assertion
    // before the wrong bytes ever reach the guest.
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mut bytes = [0u8; VIRTIO_BLK_CONFIG_SIZE];
    dev.mmio_read(0x100, &mut bytes);

    let capacity = u64::from_le_bytes(bytes[0x00..0x08].try_into().unwrap());
    let size_max = u32::from_le_bytes(bytes[0x08..0x0C].try_into().unwrap());
    let seg_max = u32::from_le_bytes(bytes[0x0C..0x10].try_into().unwrap());
    let geometry = &bytes[0x10..0x14];
    let blk_size = u32::from_le_bytes(bytes[0x14..0x18].try_into().unwrap());

    assert_eq!(
        capacity,
        VIRTIO_BLK_DEFAULT_CAPACITY_BYTES / VIRTIO_BLK_SECTOR_SIZE as u64,
        "capacity mismatch — repr(C, packed) layout drift?",
    );
    assert_eq!(size_max, VIRTIO_BLK_SIZE_MAX, "size_max layout drift");
    assert_eq!(seg_max, VIRTIO_BLK_SEG_MAX, "seg_max layout drift");
    assert_eq!(
        geometry, &[0u8; 4],
        "F_GEOMETRY not advertised; geometry must be zero",
    );
    assert_eq!(blk_size, VIRTIO_BLK_SECTOR_SIZE, "blk_size layout drift");
}

#[test]
fn config_space_zero_past_struct_size() {
    // virtio-v1.2 §4.2.2.2: reads past the populated config layout
    // return zero. Our `repr(C, packed)` struct is 24 bytes; the
    // device must zero-fill any read at offset >= 24 within
    // config space. A buggy guest or future feature negotiation
    // must see deterministic zero rather than uninitialized memory.
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mut buf = [0xffu8; 16];
    dev.mmio_read(0x100 + VIRTIO_BLK_CONFIG_SIZE as u64, &mut buf);
    assert!(
        buf.iter().all(|&b| b == 0),
        "config-space read past struct size must be zero-filled, got {:02x?}",
        buf,
    );

    // Read straddling the struct boundary: half within, half
    // past. The within portion carries blk_size at offset 0x14;
    // the past portion (offset 0x18..0x1C) must zero-fill.
    let mut buf = [0xffu8; 8];
    dev.mmio_read(0x100 + 0x14, &mut buf);
    assert_eq!(
        u32::from_le_bytes(buf[0..4].try_into().unwrap()),
        VIRTIO_BLK_SECTOR_SIZE,
        "first 4 bytes must be blk_size",
    );
    assert_eq!(
        &buf[4..],
        &[0u8; 4],
        "trailing 4 bytes (offset 0x18..0x1C) must zero-fill past struct end",
    );
}

#[test]
fn config_space_struct_size_matches_kernel_uapi() {
    // Mirror the compile-time size assertion at runtime so a
    // broken assertion surfaces under nextest output rather than
    // hidden in a const-eval failure. Also pin the alignment to
    // 1: ByteValued::as_slice() returns the struct's bytes
    // directly, and `repr(C, packed)` collapses alignment to 1
    // — which both matches the kernel's
    // `__attribute__((packed))` layout and avoids any
    // unaligned-access UB on architectures we don't currently
    // target.
    assert_eq!(
        VIRTIO_BLK_CONFIG_SIZE, 24,
        "VirtioBlkConfig must be 24 bytes (capacity 8 + size_max 4 + \
             seg_max 4 + geometry 4 + blk_size 4) per the kernel uapi \
             layout. Mismatch implies repr(C, packed) drift.",
    );
    assert_eq!(
        std::mem::align_of::<VirtioBlkConfig>(),
        1,
        "repr(C, packed) must produce alignment 1",
    );
    assert_eq!(
        std::mem::align_of::<VirtioBlkGeometry>(),
        1,
        "geometry sub-struct must also be packed to align 1",
    );
}

#[test]
fn config_space_writes_silently_dropped() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let before = dev.capacity_sectors();
    dev.mmio_write(0x100, &[0xff, 0xff, 0xff, 0xff]);
    assert_eq!(dev.capacity_sectors(), before);
}

#[test]
fn queue_num_max() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 0);
    assert_eq!(
        read_reg(&dev, VIRTIO_MMIO_QUEUE_NUM_MAX),
        QUEUE_MAX_SIZE as u32
    );
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 1);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_QUEUE_NUM_MAX), 0);
}

#[test]
fn status_state_machine() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    // Skipping FEATURES_OK is rejected.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_OK);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_DRV);
}

/// FEATURES_OK transition rejected when VIRTIO_F_VERSION_1 is
/// not in the driver-acknowledged set (virtio-v1.2 §6.1: "A
/// driver MUST accept VIRTIO_F_VERSION_1"). Modern devices
/// require this bit; the kernel's `virtio_features_ok`
/// (drivers/virtio/virtio.c) writes FEATURES_OK then re-reads
/// STATUS to confirm the device accepted, surfacing -ENODEV
/// otherwise. The device's role is to leave FEATURES_OK clear
/// when the bit is missing so the kernel's read-back fails.
///
/// The legacy path here exercises a guest that walks the FSM
/// to the FEATURES_OK write WITHOUT having acknowledged
/// VIRTIO_F_VERSION_1. The device must not commit the
/// transition; `device_status` stays at S_DRV and a subsequent
/// driver re-read of STATUS sees FEATURES_OK is unset.
#[test]
fn features_ok_rejected_without_version_1() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    // Driver acks an unrelated feature (BLK_SIZE in the low
    // half) but skips VIRTIO_F_VERSION_1 (bit 32, page 1).
    // device_features() advertises BLK_SIZE so this is a
    // legitimate ack from the device's perspective — only
    // VIRTIO_F_VERSION_1 is missing.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 0);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << VIRTIO_BLK_F_BLK_SIZE,
    );
    // Attempt FEATURES_OK without VIRTIO_F_VERSION_1: rejected.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_DRV,
        "FEATURES_OK must be rejected when VIRTIO_F_VERSION_1 is not negotiated",
    );

    // After the driver acks VIRTIO_F_VERSION_1, the same
    // FEATURES_OK write succeeds — confirms the gate is
    // version-1-specific, not blanket-rejecting.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << (VIRTIO_F_VERSION_1 - 32),
    );
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_FEAT,
        "FEATURES_OK must be accepted once VIRTIO_F_VERSION_1 is in driver_features",
    );
}

#[test]
fn status_reset_via_zero() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, 0);
    assert_eq!(dev.device_status.load(Ordering::Acquire), 0);
}

#[test]
fn capacity_custom_size() {
    let dev = make_device(256 * 1024 * 1024, DiskThrottle::default());
    assert_eq!(dev.capacity_sectors(), 256 * 1024 * 1024 / 512);
}

#[test]
fn counters_initially_zero() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let c = dev.counters();
    assert_eq!(c.reads_completed.load(Ordering::Relaxed), 0);
    assert_eq!(c.writes_completed.load(Ordering::Relaxed), 0);
    assert_eq!(c.flushes_completed.load(Ordering::Relaxed), 0);
    assert_eq!(c.bytes_read.load(Ordering::Relaxed), 0);
    assert_eq!(c.bytes_written.load(Ordering::Relaxed), 0);
    assert_eq!(c.throttled_count.load(Ordering::Relaxed), 0);
    assert_eq!(c.io_errors.load(Ordering::Relaxed), 0);
}

#[test]
fn counters_arc_shared_with_caller() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let c1 = dev.counters();
    let c2 = dev.counters();
    c1.reads_completed.store(42, Ordering::Relaxed);
    assert_eq!(c2.reads_completed.load(Ordering::Relaxed), 42);
}

/// Each `VirtioBlkCounters` accessor returns the value stored in
/// the matching atomic field — no swapped-accessor wiring. Pin
/// distinct sentinel values per field (1..=8) so a regression
/// that, for example, has `reads_completed()` return
/// `writes_completed`'s atomic surfaces here as a wrong-value
/// assertion failure that names the field.
///
/// Counters are crate-internal; the test reaches into the public
/// `pub(crate)` atomic fields to seed sentinels, then exercises
/// each `pub fn` accessor. Without this test the eight accessors
/// have zero call sites in the test suite and a swap regression
/// would only surface at runtime via wrong failure-dump numbers.
#[test]
fn counters_accessors_match_atomic_state() {
    let counters = VirtioBlkCounters::default();
    // Distinct sentinels so any swapped-accessor returns a value
    // that mismatches the field name in the assertion message.
    counters.reads_completed.store(1, Ordering::Relaxed);
    counters.writes_completed.store(2, Ordering::Relaxed);
    counters.flushes_completed.store(3, Ordering::Relaxed);
    counters.bytes_read.store(4, Ordering::Relaxed);
    counters.bytes_written.store(5, Ordering::Relaxed);
    counters.throttled_count.store(6, Ordering::Relaxed);
    counters.io_errors.store(7, Ordering::Relaxed);
    counters
        .currently_throttled_gauge
        .store(8, Ordering::Relaxed);
    assert_eq!(counters.reads_completed(), 1, "reads_completed accessor");
    assert_eq!(counters.writes_completed(), 2, "writes_completed accessor");
    assert_eq!(
        counters.flushes_completed(),
        3,
        "flushes_completed accessor"
    );
    assert_eq!(counters.bytes_read(), 4, "bytes_read accessor");
    assert_eq!(counters.bytes_written(), 5, "bytes_written accessor");
    assert_eq!(counters.throttled_count(), 6, "throttled_count accessor");
    assert_eq!(counters.io_errors(), 7, "io_errors accessor");
    assert_eq!(
        counters.currently_throttled_gauge(),
        8,
        "currently_throttled_gauge accessor",
    );
}

/// FEATURES_OK without VIRTIO_F_VERSION_1 must be observable as a
/// rejection via the MMIO read-back path, not just via the
/// internal `device_status` field. The kernel's
/// `virtio_features_ok` writes FEATURES_OK and re-reads STATUS;
/// the production rejection signal is "the bit didn't stick" as
/// observed through MMIO reads. A regression that updated
/// `device_status` but broke the STATUS read register would pass
/// `features_ok_rejected_without_version_1` (which checks the
/// field directly) while presenting as accept-then-reject to a
/// real driver.
///
/// Construction parallels `features_ok_rejected_without_version_1`:
/// walk to S_DRV, ack a non-VERSION_1 feature, attempt FEATURES_OK,
/// then read STATUS via `read_reg` and assert the response equals
/// S_DRV (S_FEAT bit absent).
#[test]
fn features_ok_rejection_visible_via_mmio_read() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    // Ack BLK_SIZE in the low half but skip VIRTIO_F_VERSION_1
    // (bit 32 in the high half). A legitimate non-VERSION_1
    // feature ack — the rejection is specifically about the
    // missing transport bit, not the device's feature set.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 0);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << VIRTIO_BLK_F_BLK_SIZE,
    );
    // Attempt FEATURES_OK without VIRTIO_F_VERSION_1.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);
    // MMIO read-back: STATUS must report S_DRV (not S_FEAT) so
    // the kernel's read-after-write check surfaces the
    // rejection.
    let status = read_reg(&dev, VIRTIO_MMIO_STATUS);
    assert_eq!(
        status, S_DRV,
        "MMIO STATUS read-back must show FEATURES_OK is unset \
             when VIRTIO_F_VERSION_1 was not negotiated",
    );
    assert_ne!(
        status & VIRTIO_CONFIG_S_FEATURES_OK,
        VIRTIO_CONFIG_S_FEATURES_OK,
        "FEATURES_OK bit must NOT be set in MMIO read-back",
    );

    // Sanity check: same MMIO walk after acking VIRTIO_F_VERSION_1
    // succeeds — proves the rejection was version-1-specific,
    // not a blanket MMIO-read-broken regression.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << (VIRTIO_F_VERSION_1 - 32),
    );
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);
    let status = read_reg(&dev, VIRTIO_MMIO_STATUS);
    assert_eq!(
        status, S_FEAT,
        "MMIO STATUS read-back must show FEATURES_OK is set \
             once VIRTIO_F_VERSION_1 was negotiated",
    );
}

/// `set_mem` is one-shot: the second call must NOT replace the
/// stored guest memory. The field is `Arc<OnceLock<GuestMemoryMmap>>`,
/// and `OnceLock::set` returns Err on already-initialised; the
/// device's `set_mem` logs a warn and returns without overwriting.
/// Pin the warn+ignore behaviour: after two `set_mem` calls with
/// distinct memory maps, the stored map must point at the FIRST
/// instance.
///
/// Pointer equality via `OnceLock::get() as *const GuestMemoryMmap`
/// is the load-bearing assertion — `GuestMemoryMmap` has no
/// `PartialEq` and copying via `clone()` would defeat the point
/// (clones would be address-distinct even if content-equal).
#[test]
fn set_mem_twice_keeps_first_instance() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mem_a = make_guest_mem(4096);
    let mem_b = make_guest_mem(8192);
    dev.set_mem(mem_a);
    // Snapshot the address `OnceLock::get()` returns AFTER the
    // first set. The second set call must not alter what
    // `get()` returns.
    let first_ptr = dev.mem.get().expect("set_mem populated OnceLock") as *const GuestMemoryMmap;
    // Second set with a distinct map. set_mem swallows the
    // already-initialised Err with a warn (per its doc); the
    // function returns Ok regardless.
    dev.set_mem(mem_b);
    let after_ptr = dev.mem.get().expect("OnceLock still populated") as *const GuestMemoryMmap;
    assert_eq!(
        first_ptr, after_ptr,
        "OnceLock must retain the first GuestMemoryMmap; set_mem \
             must not overwrite on the second call",
    );
}

#[test]
fn handle_flush_no_mem_no_panic() {
    // Flush calls fdatasync on the backing file. Ensure it
    // succeeds on a fresh tempfile (which is always
    // fdatasync-able on Linux).
    let mut f = tempfile().unwrap();
    f.write_all(&[0u8; 1024]).unwrap();
    // Direct call bypassing MMIO — sync_data must succeed.
    f.sync_data().expect("tempfile sync_data must succeed");
}

#[test]
fn ok_status_constant_distinct_from_ioerr() {
    // Pin the canonical virtio-blk status byte values. A
    // regression that maps every request to OK silently corrupts
    // guest filesystems by serving uninitialized data.
    assert_eq!(VIRTIO_BLK_S_OK, 0);
    assert_eq!(VIRTIO_BLK_S_IOERR, 1);
    assert_eq!(VIRTIO_BLK_S_UNSUPP, 2);
}

// ----------------------------------------------------------------
// MMIO/FSM/IRQ surface tests ported from virtio_console.
//
// These exercise the device's MMIO/FSM/IRQ surface independent
// of the backend descriptor-I/O path — they pin behaviour the
// device shares with every virtio-mmio device per virtio-v1.2
// (status FSM, queue config gating, IRQ delivery). Mechanical
// ports of virtio_console's analogous coverage; behavioral
// parity with that device is the goal because the two share
// the same MMIO contract.
// ----------------------------------------------------------------

/// `INTERRUPT_STATUS` reflects the device's internal
/// `interrupt_status` register; reads do NOT clear it (only
/// `INTERRUPT_ACK` writes do, per virtio-v1.2 §4.2.2). Mirrors
/// `virtio_console::interrupt_status_and_ack`.
#[test]
fn interrupt_status_and_ack() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_INTERRUPT_STATUS), 0);
    dev.interrupt_status
        .store(VIRTIO_MMIO_INT_VRING, Ordering::Release);
    assert_eq!(
        read_reg(&dev, VIRTIO_MMIO_INTERRUPT_STATUS),
        VIRTIO_MMIO_INT_VRING
    );
}

/// `INTERRUPT_ACK` clears only the bits the driver writes,
/// leaving other bits set. virtio-v1.2 §4.2.2.2 specifies that
/// each write to `InterruptACK` clears the bits in `InterruptStatus`
/// matching the bits set in the value written. Mirrors
/// `virtio_console::interrupt_ack_clears_bits`.
///
/// virtio-blk fires `VIRTIO_MMIO_INT_CONFIG` on the
/// queue-poison path: when `drain_bracket_impl` observes
/// `Error::InvalidAvailRingIndex` (a hostile-guest avail.idx
/// distance violation per virtio-v1.2 §2.7.13.3), it sets
/// NEEDS_RESET in `device_status` and signals the guest via
/// the INT_CONFIG bit + irqfd. ACK semantics are exercised
/// here with both INT_VRING and INT_CONFIG bits set so the
/// mask-clear path covers the production poison-path
/// signalling AND the ordinary publish-path INT_VRING bit.
#[test]
fn interrupt_ack_clears_bits() {
    use virtio_bindings::virtio_mmio::VIRTIO_MMIO_INT_CONFIG;
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    dev.interrupt_status.store(
        VIRTIO_MMIO_INT_VRING | VIRTIO_MMIO_INT_CONFIG,
        Ordering::Release,
    );
    write_reg(&mut dev, VIRTIO_MMIO_INTERRUPT_ACK, VIRTIO_MMIO_INT_VRING);
    assert_eq!(
        read_reg(&dev, VIRTIO_MMIO_INTERRUPT_STATUS),
        VIRTIO_MMIO_INT_CONFIG,
    );
}

/// Non-4-byte reads must return 0xff for every byte. The
/// virtio-MMIO spec mandates 4-byte register access; a partial
/// access is a guest bug. Returning 0xff is more debuggable than
/// silently zeroing because it produces an obviously wrong value
/// the kernel driver flags. Mirrors
/// `virtio_console::non_4byte_read_returns_ff`.
#[test]
fn non_4byte_read_returns_ff() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    let mut buf = [0u8; 2];
    dev.mmio_read(0, &mut buf);
    assert_eq!(buf, [0xff, 0xff]);
}

/// Non-4-byte writes are silently dropped. The device MUST
/// not act on a partial register write; pinning that the device
/// state remains untouched after a bogus 2-byte write to STATUS.
/// Mirrors `virtio_console::non_4byte_write_ignored`.
#[test]
fn non_4byte_write_ignored() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    dev.mmio_write(VIRTIO_MMIO_STATUS as u64, &[0x01, 0x00]);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_STATUS), 0);
}

/// `DRIVER_FEATURES` writes are gated by status: BEFORE
/// DRIVER bit, writes are dropped. AFTER ACKNOWLEDGE+DRIVER
/// (`S_DRV`), writes are accepted into the page selected by
/// `DRIVER_FEATURES_SEL`. Pins the page-select dispatch (page 0
/// → low 32 bits, page 1 → high 32 bits). Mirrors
/// `virtio_console::driver_features_gated_by_status`.
#[test]
fn driver_features_gated_by_status() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Before DRIVER status, features writes are rejected.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES, 0xDEAD);
    assert_eq!(dev.driver_features, 0);

    // After ACKNOWLEDGE + DRIVER, features writes are accepted.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES, 0xDEAD_BEEF);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES, 0xCAFE_BABE);
    assert_eq!(dev.driver_features, 0xCAFE_BABE_DEAD_BEEF);
}

/// Feature negotiation closes once `FEATURES_OK` is set:
/// subsequent `DRIVER_FEATURES` writes must be dropped. Pinning
/// this prevents a regression that would let the guest mutate
/// negotiated features post-handshake — a spec violation that
/// can corrupt device behavior. Mirrors
/// `virtio_console::features_rejected_after_features_ok`.
#[test]
fn features_rejected_after_features_ok() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << (VIRTIO_F_VERSION_1 - 32),
    );
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);

    // After FEATURES_OK, features writes are rejected.
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES, 0xFFFF);
    assert_eq!(dev.driver_features & 0xFFFF_FFFF, 0);
}

/// `QUEUE_DESC_LOW`/`QUEUE_DESC_HIGH` writes are gated by
/// `queue_config_allowed`: BEFORE `FEATURES_OK`, writes drop;
/// AFTER `FEATURES_OK` (and before `DRIVER_OK`), they're applied.
/// virtio-v1.2 §4.2.2.2 mandates queue config is only legal in
/// the `FEATURES_OK..DRIVER_OK` window. Mirrors
/// `virtio_console::queue_desc_addr_requires_features_ok`.
#[test]
fn queue_desc_addr_requires_features_ok() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_DESC_LOW, 0x1000);
    // Not accepted before FEATURES_OK.
    assert_ne!(dev.worker.queues[0].desc_table(), 0x1000);

    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_DRIVER_FEATURES_SEL, 1);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_DRIVER_FEATURES,
        1 << (VIRTIO_F_VERSION_1 - 32),
    );
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_FEAT);

    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_DESC_LOW, 0x1000);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_DESC_HIGH, 0);
    assert_eq!(dev.worker.queues[0].desc_table(), 0x1000);
}

/// Reads of unknown register offsets return 0 (the catchall
/// `_ => 0` arm in `mmio_read`). 0x300 sits beyond every defined
/// MMIO offset and below the 0x100 config-space split, so it's a
/// pure unknown-register probe. Mirrors
/// `virtio_console::unknown_register_returns_zero`.
#[test]
fn unknown_register_returns_zero() {
    let dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    assert_eq!(read_reg(&dev, 0x300), 0);
}

/// Writes to unknown register offsets are silently dropped.
/// Confirms that an attempted write to 0x300 has no observable
/// side effect on the device's STATUS register. Mirrors
/// `virtio_console::unknown_register_write_ignored`.
#[test]
fn unknown_register_write_ignored() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, 0x300, 0xDEAD);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_STATUS), 0);
}

/// `QUEUE_SEL` accepting any 32-bit value is fine, but
/// reading `QUEUE_NUM_MAX`/`QUEUE_READY` for a select that's
/// out of range returns 0 because `selected_queue()` returns
/// `None`. virtio-blk has only one queue (REQ_QUEUE=0), so any
/// select >= 1 must read 0. Mirrors
/// `virtio_console::invalid_queue_select_returns_zero`.
#[test]
fn invalid_queue_select_returns_zero() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 99);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_QUEUE_NUM_MAX), 0);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_QUEUE_READY), 0);
}

/// `DEVICE_FEATURES_SEL` page 2 returns 0. Only pages 0
/// and 1 are defined (low / high 32 bits of the 64-bit feature
/// set); higher pages must read 0 per virtio-v1.2's
/// reserved-for-future-extensions semantics. Mirrors
/// `virtio_console::features_page_2_returns_zero`.
#[test]
fn features_page_2_returns_zero() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_DEVICE_FEATURES_SEL, 2);
    assert_eq!(read_reg(&dev, VIRTIO_MMIO_DEVICE_FEATURES), 0);
}

/// Skipping `ACKNOWLEDGE` (writing `DRIVER` directly) is
/// rejected by the FSM. `set_status` requires the new-bit set
/// to match exactly the next legal transition; jumping straight
/// to `DRIVER` from 0 violates the §3.1.1 ordering.
/// Mirrors `virtio_console::status_skip_acknowledge_rejected`.
#[test]
fn status_skip_acknowledge_rejected() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Skipping ACKNOWLEDGE, going straight to DRIVER.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, VIRTIO_CONFIG_S_DRIVER);
    assert_eq!(dev.device_status.load(Ordering::Acquire), 0);
}

/// Idempotent re-write of the current `device_status` is a
/// no-op — the value is unchanged AND no rejection diagnostic
/// fires. Standard drivers (the kernel virtio_mmio /
/// virtio_pci `vp_finalize_features` path) write
/// `STATUS = old | NEW_BIT` and re-read; an MMIO probe path
/// may also issue a duplicate write of the current status.
/// Pinning this contract prevents a spurious "illegal FSM
/// transition" warn from polluting operator logs on a
/// well-formed driver. Distinct from
/// `status_skip_acknowledge_rejected` which exercises a true
/// ordering violation.
#[tracing_test::traced_test]
#[test]
fn status_idempotent_rewrite_is_noop() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Reach S_ACK first via a legal transition.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_ACK);
    // Idempotent re-write of the same value: state unchanged,
    // no warn emitted.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK,
        "idempotent re-write must NOT alter device_status",
    );
    assert!(
        !logs_contain("illegal FSM transition"),
        "idempotent re-write must NOT emit the illegal-transition warn",
    );
    assert!(
        !logs_contain("attempted to clear"),
        "idempotent re-write must NOT emit the clear-bit warn",
    );
    // Same idempotence at later FSM states. Walk to S_DRV and
    // re-write S_DRV.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_DRV);
    assert!(
        !logs_contain("illegal FSM transition"),
        "S_DRV re-write must NOT emit the illegal-transition warn",
    );
}

/// Writing a multi-bit transition (two new bits at once, e.g.
/// `S_DRV | S_FEAT` from `S_ACK` instead of one step at a
/// time) is rejected by the FSM and emits a warn. Per virtio-v1.2
/// §3.1.1 the driver must walk the FSM one bit at a time so
/// the device can validate each step's preconditions.
#[tracing_test::traced_test]
#[test]
fn status_multi_bit_transition_rejected_and_logged() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    // From S_ACK, a single legal transition is to S_DRV. Two
    // bits at once (S_DRV | VIRTIO_CONFIG_S_FEATURES_OK) is a
    // multi-bit transition the FSM must reject.
    write_reg(
        &mut dev,
        VIRTIO_MMIO_STATUS,
        S_ACK | VIRTIO_CONFIG_S_DRIVER | VIRTIO_CONFIG_S_FEATURES_OK,
    );
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK,
        "multi-bit transition must NOT advance device_status",
    );
    assert!(
        logs_contain("illegal FSM transition"),
        "multi-bit transition must emit the illegal-transition warn so \
             a buggy driver surfaces in the operator log",
    );
}

/// Attempting to clear a previously-set status bit (without a
/// full STATUS=0 reset) is rejected by the monotone-bit gate
/// at the head of `set_status` and emits the dedicated
/// "attempted to clear" warn. Per virtio-v1.2 §3.1.1 status
/// bits are monotone within a driver session — the only path
/// from a higher state back to lower is STATUS=0.
#[tracing_test::traced_test]
#[test]
fn status_clear_bit_rejected_and_logged() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Walk to S_DRV (S_ACK | S_DRIVER set).
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_DRV);
    // Attempt to drop S_DRIVER while keeping S_ACKNOWLEDGE.
    // val = S_ACK; val & device_status = S_ACK != device_status
    // (S_DRV) → fails the monotone-bit gate.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_DRV,
        "clear-bit attempt must NOT alter device_status",
    );
    assert!(
        logs_contain("attempted to clear"),
        "clear-bit attempt must emit the dedicated clear-bit warn",
    );
    assert!(
        !logs_contain("illegal FSM transition"),
        "clear-bit path must NOT emit the generic illegal-transition warn — \
             the dedicated clear-bit warn is the right diagnostic",
    );
}

/// Once `DRIVER_OK` is set, queue config writes (here
/// `QUEUE_NUM`) MUST be rejected by `queue_config_allowed`. The
/// FSM gate is `S_FEAT && !DRIVER_OK`, so a `QUEUE_NUM` write
/// after the device is fully driver-up is a spec violation that
/// the device drops. Pin that the queue size stays at the
/// initialised default. Mirrors
/// `virtio_console::queue_config_rejected_after_driver_ok`.
///
/// Uses [`init_device`] to fully sequence the FSM up to
/// `S_OK`, so this test also exercises the happy-path init
/// pipeline (any FSM regression that breaks negotiate-up surfaces
/// here as a setup-time assertion failure rather than a missed
/// post-OK write).
#[test]
fn queue_config_rejected_after_driver_ok() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    init_device(&mut dev);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_OK);

    // After DRIVER_OK, queue config is rejected.
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_SEL, 0);
    write_reg(&mut dev, VIRTIO_MMIO_QUEUE_NUM, 64);
    // Queue size should still be the post-init default
    // (QUEUE_MAX_SIZE), not 64.
    assert_eq!(dev.worker.queues[0].size(), QUEUE_MAX_SIZE);
}

/// FAILED (bit 0x80) must be accepted on top of any FSM state.
/// virtio-v1.2 §2.1.1 — `virtio_add_status(dev,
/// VIRTIO_CONFIG_S_FAILED)` is the kernel's exit path on probe
/// failure (drivers/virtio/virtio.c:363, 570, 606, 643). The
/// kernel reads `get_status`, ORs in FAILED, and writes the
/// result, so `val == current_status | FAILED` regardless of the
/// FSM rung the driver had reached. Pins the FAILED early-accept
/// branch in `set_status` at every legal predecessor state so a
/// regression that re-routes the FAILED bit through the
/// FSM-ladder match (and rejects it as an "illegal FSM
/// transition") surfaces here. Mirrors
/// `virtio_console::set_status_failed_accepted_at_every_fsm_state`.
#[test]
fn set_status_failed_accepted_at_every_fsm_state() {
    // From device_status = 0.
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        VIRTIO_CONFIG_S_FAILED,
        "FAILED from status=0 must be accepted",
    );

    // From device_status = S_ACK.
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK | VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK | VIRTIO_CONFIG_S_FAILED,
        "FAILED from status=S_ACK must be accepted (S_ACK preserved)",
    );

    // From device_status = S_DRV.
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_DRV | VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_DRV | VIRTIO_CONFIG_S_FAILED,
        "FAILED from status=S_DRV must be accepted (S_DRV preserved)",
    );

    // From device_status = S_OK (full FSM walk via init_device).
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    init_device(&mut dev);
    assert_eq!(dev.device_status.load(Ordering::Acquire), S_OK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_OK | VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_OK | VIRTIO_CONFIG_S_FAILED,
        "FAILED from status=S_OK must be accepted (S_OK preserved)",
    );
}

/// FAILED combined with a non-FAILED unrecognised new bit must
/// be rejected — the FAILED early-accept only triggers when
/// `new_bits == VIRTIO_CONFIG_S_FAILED` (FAILED alone, no other
/// new bits). A guest mixing FAILED with garbage extra bits is
/// misbehaving in a way unrelated to the legitimate FAILED
/// signal. Mirrors
/// `virtio_console::set_status_failed_plus_unknown_bit_rejected`.
#[tracing_test::traced_test]
#[test]
fn set_status_failed_plus_unknown_bit_rejected() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    // val = ACK | FAILED | 0x10. new_bits = FAILED | 0x10 ≠
    // FAILED alone, so the early-accept branch does NOT trigger;
    // the FSM-ladder match has no arm for the union → reject.
    write_reg(
        &mut dev,
        VIRTIO_MMIO_STATUS,
        S_ACK | VIRTIO_CONFIG_S_FAILED | 0x10,
    );
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK,
        "FAILED combined with a non-FAILED unknown bit must be \
         rejected — the early-accept is gated on FAILED alone",
    );
    assert!(
        logs_contain("illegal FSM transition"),
        "FAILED+unknown-bit must emit the FSM-ladder rejection warn",
    );
}

/// FAILED accepted on top of NEEDS_RESET when the kernel
/// follows the documented `get_status` → OR-in-FAILED → write
/// sequence. The poisoned device exposes NEEDS_RESET via
/// `get_status`, the kernel's `virtio_add_status(FAILED)` reads
/// that and writes back `NEEDS_RESET | FAILED`. The monotone-bit
/// gate accepts (val ⊇ current); the FAILED branch stores both
/// bits. Pins that NEEDS_RESET does NOT swallow a legitimate
/// FAILED signal arriving with NEEDS_RESET present — the failure
/// dump must show both states so an operator can distinguish
/// "device declared itself broken" (NEEDS_RESET) from "driver
/// gave up" (FAILED).
#[test]
fn set_status_failed_accepted_on_top_of_needs_reset() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    // Plant NEEDS_RESET via the same fetch_or the worker would
    // use on queue poison.
    dev.device_status
        .fetch_or(VIRTIO_CONFIG_S_NEEDS_RESET, Ordering::SeqCst);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        VIRTIO_CONFIG_S_NEEDS_RESET,
    );
    // Kernel-style sequence: read get_status, OR in FAILED, write.
    let current = dev.device_status.load(Ordering::Acquire);
    write_reg(
        &mut dev,
        VIRTIO_MMIO_STATUS,
        current | VIRTIO_CONFIG_S_FAILED,
    );
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        VIRTIO_CONFIG_S_NEEDS_RESET | VIRTIO_CONFIG_S_FAILED,
        "FAILED must land alongside NEEDS_RESET when the kernel \
         follows the get_status | FAILED write sequence",
    );
}

/// FAILED on an idempotent re-write (FAILED already set) is a
/// no-op via the `new_bits == 0` short-circuit — the FAILED
/// early-accept only fires when FAILED is the SOLE new bit.
/// Pins the interaction between the idempotent-rewrite gate and
/// the FAILED branch so a future refactor that reorders them
/// surfaces here. The kernel's `virtio_features_ok` post-write
/// `get_status` re-read does not retrigger an MMIO write, but
/// any path that issues a duplicate FAILED store must remain a
/// silent no-op rather than logging a warn each time.
#[tracing_test::traced_test]
#[test]
fn set_status_failed_idempotent_rewrite_is_noop() {
    let mut dev = make_device(VIRTIO_BLK_DEFAULT_CAPACITY_BYTES, DiskThrottle::default());
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK);
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK | VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK | VIRTIO_CONFIG_S_FAILED,
        "FAILED accepted on first write",
    );
    // Duplicate FAILED store: same value, same bits — must
    // short-circuit at `new_bits == 0` without re-emitting the
    // warn or rejecting.
    write_reg(&mut dev, VIRTIO_MMIO_STATUS, S_ACK | VIRTIO_CONFIG_S_FAILED);
    assert_eq!(
        dev.device_status.load(Ordering::Acquire),
        S_ACK | VIRTIO_CONFIG_S_FAILED,
        "idempotent FAILED re-write must NOT alter device_status",
    );
    assert!(
        !logs_contain("illegal FSM transition"),
        "idempotent FAILED re-write must NOT emit the illegal-transition warn",
    );
    assert!(
        !logs_contain("attempted to clear"),
        "idempotent FAILED re-write must NOT emit the clear-bit warn",
    );
}