aboutsummaryrefslogtreecommitdiff
path: root/src/x86_64.rs
blob: ff23b340c24ba96422af85dd2666bda89c8b487d (plain)
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
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
use core::fmt;
use core::mem::size_of;
use core::num::NonZero;
use core::ptr::NonNull;
use nix::sys::mman::{MapFlags, ProtFlags};

use kvm_ioctls::{Kvm, VcpuFd, VmFd};
use kvm_bindings::{
    kvm_cpuid_entry2, kvm_guest_debug, kvm_msr_entry,
    kvm_userspace_memory_region, kvm_segment, CpuId, Msrs,
    KVM_GUESTDBG_ENABLE, KVM_GUESTDBG_SINGLESTEP, KVM_MAX_CPUID_ENTRIES,
};

pub use kvm_bindings::{kvm_regs, kvm_sregs, kvm_xcrs, kvm_debug_exit_arch};

const _TARGET_IS_64BIT: () = {
    assert!(size_of::<u64>() == size_of::<usize>(), "asmlinator only supports 64-bit targets");
};

// the wanton casting between usize and u64 is justifiable here because TARGET_IS_64BIT above:
fn usize_to_u64(x: usize) -> u64 {
    let _ = _TARGET_IS_64BIT;

    x as u64
}

fn u64_to_usize(x: u64) -> usize {
    let _ = _TARGET_IS_64BIT;

    x as usize
}

/// a test VM for running arbitrary instructions.
///
/// there is one CPU which is configured for long-mode execution. all memory is
/// identity-mapped with 1GiB pages. page tables are configured to cover 512 GiB of memory, but
/// much much less than that is actually allocated and usable through `memory.`
///
/// it is configured with `mem_size` bytes of memory at guest address 0, accessible through
/// host pointer `memory`. this region is used for "control structures"; page tables, GDT, IDT,
/// and stack. it is also the region where code to be executed is placed.
pub struct Vm {
    settings: VmSettings,
    vm: VmFd,
    vcpu: VcpuFd,
    supported_cpuid: CpuId,
    current_cpuid: CpuId,
    idt_configured: bool,
    syscall_configured: bool,
    mem_ceiling: u64,
    memory: Mapping,
    aux_memories: Vec<Mapping>,
}

/// broad categories of cpuid/cpu features that should be detectable or configurable as part of
/// setting up a VM. this is split out for legibility, but also because in theory these (especially
/// ISA extensions) features probably should be configurable by library users somehow..
///
/// not yet sure, so this is not pub.
#[derive(Copy, Clone, Debug)]
enum Feature {
    /// support for long mode and miscellaneous baseline instructions.
    ///
    /// `asmlinator` assumes these features are always supported.
    Base,
    /// support for syscall/sysret instructions.
    Syscall,
    /// support for the xsave/xrstor instructions and at least xcr0.
    ///
    /// cpuid leaf eax=0x0000_0001 bit ecx[26], see APM
    /// chapter "Obtaining Processor Information Via the CPUID Instruction",
    /// section "Standard Feature Function Numbers".
    XSave,
    /// support for 1GB page mappings. cpuid leaf eax=0x8000_0001 bit edx[26].
    Pdpe1Gb,
    /// support for the XSAVE SSE region. this correponds to the bit in CPUID leaf D and
    /// corresponding bit in xcr0. if this bit is unset, attempts to use instructions with xmm
    /// state will #UD.
    StateSSE,
    /// support for the XSAVE AVX region. this correponds to the bit in CPUID leaf D and
    /// corresponding bit in xcr0. if this bit is unset, attempts to use instructions with ymm
    /// state will #UD.
    StateAVX,
    /// support for the XSAVE AVX512 regions. this correponds to the bits for K, ZMM_Hi256, and
    /// Hi16_ZMM in CPUID leaf D and corresponding bits in xcr0. if these bits are not set,
    /// attempts to use instructions with zmm state may #UD.
    StateAVX512,
    /// support for Page Size Extensions. is relevant only for protected mode; among other things,
    /// this bit indicates support for page directory entries mapping 4MiB of memory directly,
    /// rather than mapping a 1024-entry block of PTEs.
    Pse,
}

const CPUID_00000001_ECX_XSAVE: u32 = 1 << 26;

const CPUID_00000001_EDX_PSE: u32 = 1 << 3;

const CPUID_0000000D_EAX_SSE: u32 = 1 << 1;
const CPUID_0000000D_EAX_AVX: u32 = 1 << 2;
const CPUID_0000000D_EAX_AVX512: u32 = (1 << 5) | (1 << 6) | (1 << 7);

const CPUID_80000001_EDX_PDPE1GB: u32 = 1 << 26;

// AMD APM `System Instruction Support Indicated by CPUID Feature Bits`
const CPUID_00000001_EDX_MSR: u32 = 1 << 5;
const CPUID_00000007_EBX_CLSTAC: u32 = 1 << 20;
const CPUID_80000001_EDX_SYSCALL: u32 = 1 << 11;
const CPUID_80000001_EDX_LM: u32 = 1 << 29;

#[derive(PartialEq)]
#[non_exhaustive]
pub enum VcpuExit<'buf> {
    MmioRead { addr: u64, buf: &'buf mut [u8] },
    MmioWrite { addr: u64, buf: &'buf [u8] },
    IoIn { port: u16, buf: &'buf mut [u8] },
    IoOut { port: u16, buf: &'buf [u8] },
    Debug { pc: u64, info: kvm_debug_exit_arch },
    Exception { nr: u8 },
    Shutdown,
    Hlt,
    Syscall,
}

impl<'buf> fmt::Debug for VcpuExit<'buf> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        use VcpuExit::*;
        match self {
            MmioRead { addr, buf } => {
                let size = buf.len();
                write!(f, "VcpuExit::MmioRead {{ addr: {addr:#08x}, size: {size} }}")
            },
            MmioWrite { addr, buf } => {
                let size = buf.len();
                write!(f, "VcpuExit::MmioWrite {{ addr: {addr:#08x}, size: {size} }}")
            },
            IoIn { port, buf } => {
                let size = buf.len();
                write!(f, "VcpuExit::IoIn {{ port: {port:#04x}, size: {size} }}")
            },
            IoOut { port, buf } => {
                let size = buf.len();
                write!(f, "VcpuExit::IoOut {{ port: {port:#04x}, size: {size} }}")
            },
            Debug { pc, info: _ } => {
                write!(f, "VcpuExit::Debug {{ pc: {pc:#016x}, _ }}")
            },
            Exception { nr } => {
                write!(f, "VcpuExit::Exception {{ nr: {nr} }}")
            },
            Shutdown => {
                write!(f, "VcpuExit::Shutdown")
            },
            Hlt => {
                write!(f, "VcpuExit::Hlt")
            },
            Syscall => {
                write!(f, "VcpuExit::Syscall")
            }
        }
    }
}


const GB: u64 = 1 << 30;

// TODO: cite APM/SDM
const IDT_ENTRIES: u16 = 256;

#[derive(Copy, Clone)]
pub struct GuestAddress(pub u64);

pub struct VmPageTables<'vm> {
    vm: &'vm Vm,
    base: GuestAddress,
}

impl<'vm> VmPageTables<'vm> {
    pub fn pml4_addr(&self) -> GuestAddress {
        self.base
    }

    pub fn pdpt_addr(&self) -> GuestAddress {
        GuestAddress(self.base.0 + 0x1000)
    }

    pub fn pml4_mut(&self) -> *mut u64 {
        // SAFETY: creating VmPageTables implies we've asserted that we can form host pointers
        // for all addresses in the page tables.
        unsafe {
            self.vm.host_ptr(self.pml4_addr()) as *mut u64
        }
    }

    pub fn pdpt_mut(&self) -> *mut u64 {
        // SAFETY: creating VmPageTables implies we've asserted that we can form host pointers
        // for all addresses in the page tables.
        unsafe {
            self.vm.host_ptr(self.pdpt_addr()) as *mut u64
        }
    }
}

fn encode_segment(seg: &kvm_segment) -> u64 {
    let base = seg.base as u64;
    let limit = seg.limit as u64;

    let lim_low = limit & 0xffff;
    let lim_high = (limit >> 16) & 0xf;
    let addr_low = base & 0xffff;
    let desc_low = lim_low | (addr_low << 16);

    let base_mid = (base >> 16) & 0xff;
    let base_high = (base >> 24) & 0xff;
    let access_byte = (seg.type_ as u64)
        | (seg.s as u64) << 4
        | (seg.dpl as u64) << 5
        | (seg.present as u64) << 7;
    let flaglim_byte = lim_high
        | (seg.avl as u64) << 4
        | (seg.l as u64) << 5
        | (seg.db as u64) << 6
        | (seg.g as u64) << 7;
    let desc_high = base_mid
        | access_byte << 8
        | flaglim_byte << 16
        | base_high << 24;

    desc_low | (desc_high << 32)
}

pub enum VmCreateError {
    /// the requested VM was smaller than `asmlinator`'s minimum allowable size.
    TooSmall { requested: usize, required: usize },
    /// the requested VM's memory size was not an even number of pages.
    BadSize { requested: usize, unit: usize },
    /// one of the several syscalls in setting up a new VM failed.
    ///
    /// this is most likely a permissions error, or `/dev/kvm` doesn't exist. otherwise, something
    /// interesting happened!
    ///
    /// this deserves better documentation, but i'm not aware of documentation for KVM ioctl
    /// failure modes.
    SyscallError { op: &'static str, err: nix::errno::Errno },
    /// `base` and `size` are not valid for mapping; either because of over/underflow, or overlaps
    /// with an existing mapping.
    InvalidMapping { base: GuestAddress, size: u64 }
}

impl fmt::Debug for VmCreateError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VmCreateError::TooSmall { requested, required } => {
                write!(f, "requested memory size ({requested}) is too small, must be at least {required}")
            }
            VmCreateError::BadSize { requested, unit } => {
                write!(f, "requested memory size ({requested}) is not a multiple of ({unit})")
            }
            VmCreateError::SyscallError { op, err } => {
                write!(f, "error at {op}: {err}")
            }
            VmCreateError::InvalidMapping { base, size } => {
                write!(f, "invalid mapping (gpa={:#08x}/size={:08x})", base.0, size)
            }
        }
    }
}

impl fmt::Debug for VmError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            VmError::BadSize { requested, unit } => {
                write!(f, "requested memory size ({requested}) is not a multiple of ({unit})")
            }
            VmError::SyscallError { op, err } => {
                write!(f, "error at {op}: {err}")
            }
            VmError::InvalidMapping { base, size } => {
                write!(f, "invalid mapping (gpa={:#08x}/size={:08x})", base.0, size)
            }
        }
    }
}


pub enum VmError {
    /// the requested VM's memory size was not an even number of pages.
    BadSize { requested: usize, unit: usize },
    /// one of the several syscalls in operating a VM failed.
    ///
    /// this deserves better documentation, but i'm not aware of documentation for KVM ioctl
    /// failure modes.
    SyscallError { op: &'static str, err: nix::errno::Errno },
    /// `base` and `size` are not valid for mapping; either because of over/underflow, or overlaps
    /// with an existing mapping.
    InvalidMapping { base: GuestAddress, size: u64 }
}

impl VmError {
    fn from_kvm(op: &'static str, err: kvm_ioctls::Error) -> Self {
        Self::SyscallError { op, err: nix::errno::Errno::from_raw(err.errno()) }
    }
}

impl From<VmError> for VmCreateError {
    fn from(other: VmError) -> Self {
        match other {
            VmError::BadSize { requested, unit } => VmCreateError::BadSize { requested, unit },
            VmError::SyscallError { op, err } => VmCreateError::SyscallError { op, err },
            VmError::InvalidMapping { base, size } => VmCreateError::InvalidMapping { base, size },
        }
    }
}

/// a `mmap`'d region, `munmap`'d on drop.
struct Mapping {
    guest_addr: usize,
    addr: NonNull<core::ffi::c_void>,
    size: NonZero<usize>,
}

impl Drop for Mapping {
    fn drop(&mut self) {
        let res = unsafe {
            nix::sys::mman::munmap(self.addr, self.size.get())
        };
        res.expect("can unmap a region we mapped");
    }
}

impl Mapping {
    fn create_shared(guest_addr: usize, size: usize, prot: ProtFlags) -> Result<Self, VmError> {
        if size % 4096 != 0 {
            return Err(VmError::BadSize {
                requested: size,
                unit: 4096,
            });
        }

        let size = NonZero::new(size)
            .ok_or(VmError::BadSize {
                requested: 0,
                unit: 0,
            })?;

        let map_res = unsafe {
            nix::sys::mman::mmap_anonymous(
                None,
                size,
                prot,
                MapFlags::MAP_ANONYMOUS | MapFlags::MAP_SHARED,
            )
        };

        let map_addr = map_res
            .map_err(|e| VmError::SyscallError { op: "mmap", err: e })?;

        // look, mmap should only be in the business of returning page-aligned addresses but i
        // just wanna see it, you know...
        assert!(map_addr.as_ptr() as usize % 4096 == 0);

        Ok(Self {
            guest_addr,
            addr: map_addr,
            size,
        })
    }

    /// SAFETY: the caller must not use the returned pointer to violate reference safety of the VM.
    /// the pointer must not be turned into a reference while running the VM, etc.
    ///
    /// panics if `address` is not contained in this mapping.
    unsafe fn host_ptr(&self, address: GuestAddress) -> *mut u8 {
        let guest_addr: u64 = usize_to_u64(self.guest_addr);
        let offset = address.0.checked_sub(guest_addr)
            .expect("guest address is above mapping base");

        let base = self.addr.as_ptr() as *mut u8;

        unsafe {
            base.offset(offset as isize)
        }
    }

    /// SAFETY: the caller must ensure that this mapping covers `base` and that there are at least
    /// `size` bytes at `base` before the end of this mapping.
    unsafe fn slice_mut(&mut self, base: GuestAddress, size: u64) -> &mut [u8] {
        let ptr = unsafe { self.host_ptr(base) };

        unsafe {
            core::slice::from_raw_parts_mut(ptr, u64_to_usize(size))
        }
    }

    /// SAFETY: the caller must ensure that this mapping covers `base` and that there are at least
    /// `size` bytes at `base` before the end of this mapping.
    unsafe fn slice(&self, base: GuestAddress, size: u64) -> &[u8] {
        let ptr = unsafe { self.host_ptr(base) };

        unsafe {
            core::slice::from_raw_parts(ptr, u64_to_usize(size))
        }
    }

    fn overlaps(&self, base: GuestAddress, index_end: GuestAddress) -> bool {
        let map_base: u64 = usize_to_u64(self.guest_addr);
        let map_end = map_base.checked_add(usize_to_u64(self.size.get())).unwrap();

        let enclosed_by = base.0 <= map_base && index_end.0 >= map_end;
        let contains_base = base.0 >= map_base && base.0 < map_end;
        let contains_end = index_end.0 >= map_base && index_end.0 <= map_end;

        enclosed_by || contains_base || contains_end
    }

    fn contains(&self, base: GuestAddress) -> bool {
        let end = self.guest_addr.checked_add(self.size.get()).unwrap();

        base.0 >= self.guest_addr as u64 && base.0 < end as u64
    }

    fn check_range(&self, base: GuestAddress, size: u64) -> bool {
        let map_base: u64 = self.guest_addr.try_into().unwrap();
        let Some(offset) = base.0.checked_sub(map_base) else {
            return false;
        };
        let Some(end) = offset.checked_add(size) else {
            return false;
        };

        end <= self.size.get().try_into().unwrap()
    }
}

#[test]
fn test_check_range_exact() {
    let mapping = Mapping::create_shared(0x4000, 0x1000, ProtFlags::PROT_READ).expect("can create mapping");
    assert!(mapping.check_range(GuestAddress(0x4000), 0x1000));
}

#[test]
fn test_xor_runs() {
    let mut vm = Vm::create(128 * 1024).expect("can create vm");
    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x33, 0xc0], &mut regs);

    regs.rax = 0x1234;
    let rip_before = regs.rip;

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");

    let expected_rip = rip_before + 2;
    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };

    let regs_after = vm.get_regs().expect("can get regs");
    assert_eq!(regs_after.rax, 0);
}

#[test]
fn test_protected_mode_runs() {
    let settings = VmSettings::new(128 * 1024, IsaMode::Protected);
    let mut vm = Vm::create_by_settings(settings).expect("can create vm");
    let mut regs = vm.get_regs().expect("can get regs");

    let buf = &[
        0xc5, 0xe0, 0x54, 0xc3, // vandps xmm0, xmm3, xmm3
        0x33, 0xc0,             // xor eax, eax
        0x8b, 0x09,             // mov ecx, [ecx]
        0xf4                    // hlt
    ];
    vm.program(buf, &mut regs);

    regs.rax = 0x1234;
    regs.rcx = 0x4;

    vm.set_regs(&regs).expect("can set regs");

    let res = vm.run().expect("can run vm");

    match res {
        VcpuExit::Hlt => {
            // expected exit from the `0xf4` above.
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };

    let regs_after = vm.get_regs().expect("can get regs");
    assert_eq!(regs_after.rax, 0);
    assert_eq!(regs_after.rcx, 0);
}

#[test]
fn test_pusha_runs() {
    let settings = VmSettings::new(128 * 1024, IsaMode::Real);
    let mut vm = Vm::create_by_settings(settings).expect("can create vm");
    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x60], &mut regs);

    regs.rip = 0;
    regs.rax = 0x1234;
    eprintln!("{:?}", regs);

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");
    let expected_rip = vm.code_addr().0 + 1;

    let res = vm.run().expect("can run vm");

    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            eprintln!("rip after: {:08x}", rip_after);
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };

    let regs_after = vm.get_regs().expect("can get regs");
    assert_eq!(regs_after.rax, 0x1234);
    assert_eq!(regs_after.rsp, 0x1000 - 0x80 - (8 * 2));

    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x66, 0x60], &mut regs);

    regs.rip = 0;
    regs.rax = 0x1234;
    regs.rsp = 0x1000 - 0x80;
    eprintln!("{:?}", regs);

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");
    let expected_rip = vm.code_addr().0 + 2;

    let res = vm.run().expect("can run vm");

    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            eprintln!("rip after: {:08x}", rip_after);
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };

    let regs_after = vm.get_regs().expect("can get regs");
    assert_eq!(regs_after.rax, 0x1234);
    assert_eq!(regs_after.rsp, 0x1000 - 0x80 - (8 * 4));
}

#[test]
fn test_syscall() {
    let mut vm = Vm::create(128 * 1024).expect("can create vm");
    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x0f, 0x05], &mut regs);
    eprintln!("rip before: {:08x}", regs.rip);

    vm.set_regs(&regs).expect("can set regs");

//    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");
    match res {
        VcpuExit::Syscall => { /* expected */ }
        VcpuExit::Debug { pc, .. } => {
            if pc == vm.syscall_addr().0 {
                panic!(
                    "VM exited at syscall target. \
                     syscall hlt stub not executed. \
                     is the VM being single-stepped?"
                );
            }
            panic!("unexpected debug exit at rip={:08x}", pc);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };

    let regs_after = vm.get_regs().expect("can get regs");

    let expected_rip = vm.syscall_addr().0 + 1;
    assert_eq!(expected_rip, regs_after.rip);
}

#[test]
fn test_xorps_runs() {
    let mut vm = Vm::create(128 * 1024).expect("can create vm");
    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x0f, 0x57, 0xc0], &mut regs);

    let rip_before = regs.rip;

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");

    let expected_rip = rip_before + 3;
    eprintln!("exit: {:?}", res);
    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };
}

#[test]
fn test_vex_vandps_runs() {
    let mut vm = Vm::create(128 * 1024).expect("can create vm");

    if !vm.cpuid_supports(Feature::StateAVX) {
        panic!("host CPU does not support AVX");
    }

    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0xc5, 0xe0, 0x54, 0x03], &mut regs);

    regs.rbx = regs.rip;
    let rip_before = regs.rip;

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");

    let expected_rip = rip_before + 4;
    eprintln!("exit: {:?}", res);
    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };
}

#[test]
fn test_vex_vandps_runs_32b() {
    let settings = VmSettings::new(128 * 1024, IsaMode::Protected);
    let mut vm = Vm::create_by_settings(settings).expect("can create vm");

    if !vm.cpuid_supports(Feature::StateAVX) {
        panic!("host CPU does not support AVX");
    }

    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0xc5, 0xe0, 0x54, 0x03], &mut regs);

    regs.rbx = regs.rip;
    let rip_before = regs.rip;

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");

    let expected_rip = rip_before + 4;
    eprintln!("exit: {:?}", res);
    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };
}

#[test]
fn test_evex_vandps_runs() {
    let mut vm = Vm::create(128 * 1024).expect("can create vm");

    if !vm.cpuid_supports(Feature::StateAVX512) {
        panic!("host CPU does not support AVX512");
    }

    let mut regs = vm.get_regs().expect("can get regs");

    vm.program(&[0x62, 0xf1, 0x7c, 0xbd, 0x54, 0x0a], &mut regs);

    regs.rbx = regs.rip;
    let rip_before = regs.rip;

    vm.set_regs(&regs).expect("can set regs");

    vm.set_single_step(true).expect("can set single-step");

    let res = vm.run().expect("can run vm");

    let expected_rip = rip_before + 6;
    eprintln!("exit: {:?}", res);
    match res {
        VcpuExit::Debug { pc: rip_after, .. } => {
            assert_eq!(expected_rip, rip_after);
        }
        other => {
            panic!("unexpected exit: {:?}", other);
        }
    };
}


// this function will sit and loop in the kernel after trying to fulfill the MMIO exit.
//
// not great! don't do that! it's responsive to EINTR at least.
// #[test]
#[allow(dead_code)]
fn kvm_hugepage_bug() {
    let mut vm = Vm::create(1024 * 1024).expect("can create vm");
    vm.add_memory(GuestAddress(0x1_0000_0000), 128 * 1024).expect("can add test mem region");
    unsafe {
        vm.configure_identity_paging(None);
    }

    // `add [rsp], al; add [rcx], al; pop [rcx]; hlt`
    // the first instruction runs fine. the second instruction runs fine.
    // the third instruction gets a page fault at 0xf800? which worked fine for the add.
    // this turns out to be an issue in linux' paging64_gva_to_gpa() when the va is mapped with
    // huge pages.
    let inst: &'static [u8] = &[0x00, 0x04, 0x24, 0x00, 0x01, 0x8f, 0x01, 0xf4];
    let mut regs = vm.get_regs().unwrap();
    regs.rax = 0x00000002_00100000;
    regs.rcx = 0x00000002_00100000;
    vm.program(inst, &mut regs);
    vm.set_regs(&regs).unwrap();
    vm.set_single_step(true).expect("can enable single-step");
    vm.run().expect("can run vm");

    let vm_regs = vm.get_regs().unwrap();
    let vm_sregs = vm.get_sregs().unwrap();
    let mut prev_rip = [0u8; 8];
    vm.read_mem(GuestAddress(vm_regs.rsp + 8), &mut prev_rip[..]);
    let mut buf = [0u8; 8];
    vm.read_mem(GuestAddress(vm_regs.rsp), &mut buf[..]);
    eprintln!(
        "error code: {:#08x} accessing {:016x} @ rip={:#016x} (cr3={:016x})",
        u64::from_le_bytes(buf), vm_sregs.cr2,
        u64::from_le_bytes(prev_rip), vm_sregs.cr3
    );
    if vm_regs.rip == 0x300f {
        let mut pdpt = [0u8; 4096];
        vm.read_mem(vm.page_tables().pdpt_addr(), &mut pdpt[..]);
        eprintln!("pdpt: {:x?}", &pdpt[..8]);
    }
    panic!("no");
}

/// a selector for the execution mode the VM should be initialized to.
///
/// different `IsaMode` will configure the VM wildly differently; generally any VM/vCPU state not
/// directly required for the requested mode will be left untouched.
///
/// in all modes, CPUID leaves and xcr0 are set up to support any ISA extensions supported by the
/// host CPU.
///
/// in all modes, an IDT is installed with interrupt handlers pointed to the 256 bytes from
/// `interrupt_handlers_start()`.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum IsaMode {
    /// request that the VM be configured to run x86-64 instructions, aka "AMD64", or "IA-32e" (and
    /// specifically "IA-32e 64-bit mode") in some Intel nomenclature.
    ///
    /// this configures identity paging, selectors sufficient for long mode (with all vCPU
    /// execution at CPL=0), prepares some MSRs for syscalls, and of course configures `cr0`
    /// for long mode.
    Long,
    /// request that the VM be configured to run 32-bit instructions, with long mode neither
    /// enabled nor active.
    ///
    /// this configures identity paging and selectors covering all 32-bit address space and with
    /// CPL=0.
    Protected,
    /// request that the VM be configured to run 16-bit instructions.
    ///
    /// this configures code/data selectors covering all 24 bits of address space and an interrupt
    /// descriptor table, and CPUID for any host-supported ISA extensions, but that's about it.
    Real,
}

/// the settings to configure a [`Vm::create_by_settings`]. see `VmSettings::new` for top-level
/// configuration.
pub struct VmSettings {
    mem_size: usize,
    isa_mode: IsaMode,
}

impl VmSettings {
    /// provide the bare-minimum configuration for a VM: the size of its memory and what execution
    /// mode the resulting VM should be set for.
    ///
    /// VM control settings (IDT, `cs`, `ds`, other selectors, syscalls, page tables, etc) vary
    /// substantially across different `IsaMode`. in all cases code can be written into the VM with
    /// [`Vm::program()`], then run with [`Vm::run()`].
    pub fn new(mem_size: usize, isa_mode: IsaMode) -> Self {
        Self { mem_size, isa_mode }
    }
}

impl Vm {
    pub fn create(mem_size: usize) -> Result<Vm, VmCreateError> {
        Self::create_by_settings(VmSettings::new(mem_size, IsaMode::Long))
    }

    pub fn create_by_settings(settings: VmSettings) -> Result<Vm, VmCreateError> {
        let kvm = Kvm::new()
            .map_err(|e| VmError::from_kvm("Kvm::new()", e))?;

        let vm = kvm.create_vm()
            .map_err(|e| VmError::from_kvm("craete_vm", e))?;

        let supported_cpuid = kvm.get_supported_cpuid(KVM_MAX_CPUID_ENTRIES).unwrap();

        // actual minimum is somewhere around 0x1a000 bytes, but 0x20_000 aka 128k will do
        if settings.mem_size < 128 * 1024 {
            return Err(VmCreateError::TooSmall {
                requested: settings.mem_size,
                required: 128 * 1024,
            });
        }

        let mapping = Mapping::create_shared(0, settings.mem_size, ProtFlags::PROT_READ | ProtFlags::PROT_WRITE)?;

        let region = kvm_userspace_memory_region {
            slot: 0,
            guest_phys_addr: 0x0000,
            memory_size: mapping.size.get() as u64,
            userspace_addr: mapping.addr.as_ptr() as u64,
            flags: 0,
        };

        let set_res = unsafe { vm.set_user_memory_region(region) };
        set_res.map_err(|e| VmError::from_kvm("set_user_memory_region", e))?;

        let vcpu_res = vm.create_vcpu(0);
        let vcpu = vcpu_res.map_err(|e| VmError::from_kvm("create_vcpu(0)", e))?;

        let current_cpuid = vcpu.get_cpuid2(KVM_MAX_CPUID_ENTRIES).unwrap();

        let mem_ceiling = mapping.size.get().try_into().unwrap();

        let mut this = Vm {
            settings,
            vm,
            vcpu,
            supported_cpuid,
            current_cpuid,
            idt_configured: false,
            syscall_configured: false,
            memory: mapping,
            aux_memories: Vec::new(),
            mem_ceiling,
        };

        let mut vcpu_regs = this.get_regs()?;
        let mut vcpu_sregs = this.get_sregs()?;

        assert!(this.cpuid_supports(Feature::Base));
        this.cpuid_set(Feature::Base, true);

        match this.settings.isa_mode {
            IsaMode::Long => {
                unsafe {
                    this.configure_identity_paging(Some(&mut vcpu_sregs));
                    this.configure_selectors(&mut vcpu_sregs);
                    this.configure_idt(&mut vcpu_regs, &mut vcpu_sregs);
                    let mut xcrs = this.get_xcrs()?;
                    this.configure_extensions(&mut vcpu_sregs, &mut xcrs);
                    this.set_xcrs(&xcrs)?;
                    this.configure_syscalls(&mut vcpu_sregs);
                }

                vcpu_sregs.efer |= 0x0000_0500; // LME | LMA
            }
            IsaMode::Protected => {
                unsafe {
                    this.configure_identity_paging_32b(Some(&mut vcpu_sregs));
                    this.configure_selectors_32b(&mut vcpu_sregs);
                    this.configure_idt_32b(&mut vcpu_regs, &mut vcpu_sregs);
                    let mut xcrs = this.get_xcrs()?;
                    this.configure_extensions(&mut vcpu_sregs, &mut xcrs);
                    this.set_xcrs(&xcrs)?;

                }
            }
            IsaMode::Real => {
                unsafe {
                    this.configure_selectors_16b(&mut vcpu_sregs);
                    this.configure_idt_16b(&mut vcpu_regs, &mut vcpu_sregs);
                    let mut xcrs = this.get_xcrs()?;
                    this.configure_extensions(&mut vcpu_sregs, &mut xcrs);
                    this.set_xcrs(&xcrs)?;

                    // in 16-bit mode we've set cs and ds to cover the last 4kb of memory, starting
                    // at the same place we've written code to execute. there's not much memory to
                    // go around, and not a ton of flexibility in the asmlinator API, so uh ... the
                    // least annoying thing to do might be to just put the stack 0x80 bytes from
                    // the end?
                    vcpu_regs.rsp = 0x1000 - 0x80;
                }
            }
        }

        this.set_regs(&vcpu_regs)?;
        this.set_sregs(&vcpu_sregs)?;

        Ok(this)
    }

    /// map and add a region of size `size` at guest-physical address `gpa`.
    ///
    /// this will not update page tables, so if the newly-added memory is not already mapped due to
    /// a previous `configure_identity_paging` call and it is not mapped due to explicit page table
    /// management, it will not yet be accessible by guest code.
    pub fn add_memory(&mut self, gpa: GuestAddress, size: u64) -> Result<(), VmError> {
        let new_mapping_end = gpa.0.checked_add(size)
            .map(|addr| GuestAddress(addr))
            .ok_or_else(|| VmError::InvalidMapping { base: gpa, size })?;
        if self.memory.overlaps(gpa, new_mapping_end) {
            return Err(VmError::InvalidMapping { base: gpa, size });
        } else {
            for mapping in self.aux_memories.iter() {
                if mapping.overlaps(gpa, new_mapping_end) {
                    return Err(VmError::InvalidMapping { base: gpa, size });
                }
            }
        }

        let mapping = Mapping::create_shared(
            u64_to_usize(gpa.0),
            u64_to_usize(size),
            ProtFlags::PROT_READ | ProtFlags::PROT_WRITE
        )?;

        let used_slots: u32 = self.aux_memories.len().try_into()
            .map_err(|_| VmError::InvalidMapping { base: gpa, size })?;
        let next_slot = used_slots.checked_add(1)
            .ok_or_else(|| VmError::InvalidMapping { base: gpa, size })?;

        let region = kvm_userspace_memory_region {
            slot: next_slot,
            guest_phys_addr: gpa.0,
            memory_size: mapping.size.get() as u64,
            userspace_addr: mapping.addr.as_ptr() as u64,
            flags: 0,
        };

        let set_res = unsafe { self.vm.set_user_memory_region(region) };
        set_res.map_err(|e| VmError::from_kvm("set_user_memory_region", e))?;

        self.aux_memories.push(mapping);

        if new_mapping_end.0 > self.mem_ceiling {
            self.mem_ceiling = new_mapping_end.0;
        }

        Ok(())
    }

    pub fn get_regs(&self) -> Result<kvm_regs, VmError> {
        self.vcpu.get_regs()
            .map_err(|e| VmError::from_kvm("get_regs", e))
    }

    pub fn get_sregs(&self) -> Result<kvm_sregs, VmError> {
        self.vcpu.get_sregs()
            .map_err(|e| VmError::from_kvm("get_sregs", e))
    }

    pub fn get_xcrs(&self) -> Result<kvm_xcrs, VmError> {
        self.vcpu.get_xcrs()
            .map_err(|e| VmError::from_kvm("get_xcrs", e))
    }

    pub fn set_regs(&self, regs: &kvm_regs) -> Result<(), VmError> {
        self.vcpu.set_regs(regs)
            .map_err(|e| VmError::from_kvm("set_regs", e))
    }

    pub fn set_sregs(&self, sregs: &kvm_sregs) -> Result<(), VmError> {
        self.vcpu.set_sregs(sregs)
            .map_err(|e| VmError::from_kvm("set_sregs", e))
    }

    pub fn set_xcrs(&self, xcrs: &kvm_xcrs) -> Result<(), VmError> {
        self.vcpu.set_xcrs(xcrs)
            .map_err(|e| VmError::from_kvm("set_xcrs", e))
    }

    pub fn set_msrs(&self, msrs: &Msrs) -> Result<(), VmError> {
        let n_set = self.vcpu.set_msrs(msrs)
            .map_err(|e| VmError::from_kvm("set_msrs", e))?;
        assert_eq!(msrs.as_slice().len(), n_set);
        Ok(())
    }

    pub fn idt_configured(&self) -> bool {
        self.idt_configured
    }

    pub fn syscall_configured(&self) -> bool {
        self.syscall_configured
    }

    // TODO: seems like there's a KVM bug where if the VM is configured for single-step and the
    // single-stepped instruction is a rmw to MMIO memory (or MMIO hugepages?), the single-step
    // doesn't actually take effect. compare `0x33 0x00` and `0x31 0x00`. what the hell!
    pub fn set_single_step(&mut self, active: bool) -> Result<(), VmError> {
        let mut guest_debug = kvm_guest_debug::default();

        if active {
            guest_debug.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP
        };

        self.vcpu.set_guest_debug(&guest_debug)
            .map_err(|e| VmError::from_kvm("set_guest_debug", e))
    }

    pub fn run<'vm>(&'vm mut self) -> Result<VcpuExit<'vm>, VmError> {
        let exit = self.vcpu.run()
            .map_err(|e| VmError::from_kvm("vcpu run", e))?;

        match exit {
            kvm_ioctls::VcpuExit::MmioRead(addr, buf) => {
                // `buf` is typed with a lifetime from the reborrow of self.vcpu for run() above.
                // this means it's a shorter lifetime than `'vm`, but since the resulting lifetime
                // is also `'vm` it *really* has the effect of disallowing any subsequent use of
                // `self`. these transmutes decouple the lifetime of `exit` from the lifetime of
                // `self` and returned `VcpuExit`, so other arms that don't involve lifetimes can
                // drop `exit()` and query the vcpu.
                //
                // SAFETY: this actually extends the lifetime of `buf` from the shorter transient
                // lifetime to `'vm` for the return type.
                let buf: &'vm mut [u8] = unsafe { core::mem::transmute(buf) };
                return Ok(VcpuExit::MmioRead { buf, addr });
            }
            kvm_ioctls::VcpuExit::MmioWrite(addr, buf) => {
                // see the same transmute in `MmioRead` for why this is load-bearing.
                //
                // SAFETY: this actually extends the lifetime of `buf` from the shorter transient
                // lifetime to `'vm` for the return type.
                let buf: &'vm [u8] = unsafe { core::mem::transmute(buf) };
                return Ok(VcpuExit::MmioWrite { buf, addr });
            }
            kvm_ioctls::VcpuExit::IoIn(port, buf) => {
                // see the same transmute in `MmioRead` for why this is load-bearing.
                //
                // SAFETY: this actually extends the lifetime of `buf` from the shorter transient
                // lifetime to `'vm` for the return type.
                let buf: &'vm mut [u8] = unsafe { core::mem::transmute(buf) };
                return Ok(VcpuExit::IoIn { port, buf });
            }
            kvm_ioctls::VcpuExit::IoOut(port, buf) => {
                // see the same transmute in `MmioRead` for why this is load-bearing.
                //
                // SAFETY: this actually extends the lifetime of `buf` from the shorter transient
                // lifetime to `'vm` for the return type.
                let buf: &'vm [u8] = unsafe { core::mem::transmute(buf) };
                return Ok(VcpuExit::IoOut { port, buf });
            }
            kvm_ioctls::VcpuExit::Debug(info) => {
                let pc = info.pc;
                return Ok(VcpuExit::Debug { pc, info });
            }
            kvm_ioctls::VcpuExit::Hlt => {
                let regs = self.get_regs()?;

                if self.idt_configured {
                    let intrs_start = self.interrupt_handlers_start().0;
                    let intrs_end = intrs_start + IDT_ENTRIES as u64;
                    // by the time we've exited the `hlt` of the interrupt handler has completed,
                    // so rip is advanced by one. subtract back out to convert to an exception
                    // vector number.
                    let intr_addr = regs.rip - 1;

                    if intr_addr >= intrs_start && intr_addr < intrs_end {
                        let nr = intr_addr - intrs_start;
                        // because IDT_ENTRIES is 256, this should always be true..
                        assert!(nr < 256);
                        let nr = nr as u8;

                        return Ok(VcpuExit::Exception { nr });
                    }
                }

                if self.syscall_configured {
                    // the behavior of `syscall`, `hlt`, and `rip` is a little funky. similar to
                    // interrupt handlers, we typically exit with rip pointed immediately after
                    // `syscall_addr()` because we would syscall to `hlt`, execute the first `hlt`,
                    // advance `rip` by one byte, and exit to userland for the HLT.
                    if regs.rip == self.syscall_addr().0 + 1{
                        return Ok(VcpuExit::Syscall);
                    }
                }

                Ok(VcpuExit::Hlt)
            }
            kvm_ioctls::VcpuExit::Shutdown => {
                return Ok(VcpuExit::Shutdown);
            }
            other => {
                panic!("unhandled VcpuExit kind: {other:?}");
            }
        }
    }

    /// get a pointer to host memory mapped to guest address `address`.
    ///
    /// panics if `address` is not a guest-physical address backed by host memory.
    pub unsafe fn host_ptr(&self, address: GuestAddress) -> *mut u8 {
        let mapping = self.map_containing(address, 0)
            .expect("mapping for address exists");

        unsafe {
            mapping.host_ptr(address)
        }
    }

    pub fn gdt_addr(&self) -> GuestAddress {
        GuestAddress(0x1000)
    }

    pub fn idt_addr(&self) -> GuestAddress {
        GuestAddress(0x2000)
    }

    pub fn interrupt_handlers_start(&self) -> GuestAddress {
        GuestAddress(0x3000)
    }

    pub fn syscall_addr(&self) -> GuestAddress {
        GuestAddress(0x4000)
    }

    pub fn page_table_addr(&self) -> GuestAddress {
        GuestAddress(0x10000)
    }

    pub fn code_addr(&self) -> GuestAddress {
        GuestAddress(self.memory.size.get() as u64 - 4096)
    }

    pub fn mem_ceiling(&self) -> u64 {
        self.mem_ceiling
    }

    /// configuring the IDT implies the IDT might be used which means we want a stack pointer
    /// that can have at least 0x18 bytes pushed to it if an interrupt happens.
    pub fn stack_addr(&self) -> GuestAddress {
        // it would be nice to point the stack somewhere that we could get MMIO exits and see the
        // processor push words for the interrupt in real time, but that doesn't ... work.
        // instead, you end up in a loop somewhere around svm_vcpu_run (which you can ^C out of,
        // thankfully).
        //
        // so this picks some guest memory lower down.

        // stack grows *down* but if someone pops a lot of bytes from rsp we'd go up and
        // clobber the page tables. so leave a bit of space.
        GuestAddress(0x19800)
    }

    /// selector 0x10 is chosen arbitrarily for code.
    pub fn selector_cs(&self) -> u16 {
        0x10
    }

    /// selector 0x18 is chosen arbitrarily for data (all segments; ss, ds, es, etc).
    pub fn selector_ds(&self) -> u16 {
        0x18
    }

    /// selector 0x20 is chosen arbitrarily for 16-bit interrupts, which are placed well away from
    /// where selector 0x10 is pointed in real mode.
    pub fn selector_cs_idt_16b(&self) -> u16 {
        0x20
    }

    fn map_containing_mut(&mut self, base: GuestAddress, size: u64) -> Option<&mut Mapping> {
        let mapping = if self.memory.contains(base) {
            &mut self.memory
        } else {
            self.aux_memories.iter_mut()
                .find(|map| map.contains(base))?
        };

        if !mapping.check_range(base, size) {
            return None;
        }

        Some(mapping)
    }

    fn map_containing(&self, base: GuestAddress, size: u64) -> Option<&Mapping> {
        let mapping = if self.memory.contains(base) {
            &self.memory
        } else {
            self.aux_memories.iter()
                .find(|map| map.contains(base))?
        };

        if !mapping.check_range(base, size) {
            return None;
        }

        Some(mapping)
    }

    /// write all of `data` into guest memory at guest-physical address `addr`.
    ///
    /// panics if `data` extends beyond the end of guest memory.
    pub fn write_mem(&mut self, addr: GuestAddress, data: &[u8]) {
        let mapping = self.map_containing(addr, data.len() as u64).expect("mapping is valid");

        // SAFETY: `check_range` above validates the range to copy, and... please do not
        // provide a slice of guest memory as what the guest should be programmed for...
        unsafe {
            std::ptr::copy_nonoverlapping(
                data.as_ptr(),
                mapping.host_ptr(addr),
                data.len()
            );
        }
    }

    /// read guest-physical memory at `addr` to `addr + buf.len()` into `buf`.
    ///
    /// panics if `addr + buf.len()` extends beyond the end of guest memory.
    pub fn read_mem(&mut self, addr: GuestAddress, buf: &mut [u8]) {
        let mapping = self.map_containing(addr, buf.len() as u64).expect("mapping is valid");

        // SAFETY: `check_range` above validates the range to copy, and... please do not
        // provide a slice of guest memory as what should be read into...
        unsafe {
            std::ptr::copy_nonoverlapping(
                mapping.host_ptr(addr) as *const _,
                buf.as_mut_ptr(),
                buf.len()
            );
        }
    }

    /// returns a slice of guest memory pointed to by guest-physical address `addr`, of size
    /// `size`.
    ///
    /// panics if `addr + size` is not enclosed in a single guest mapping. this crate doesn't
    /// support returning a single slice of adjacent guest memory regions (yet?), sorry.
    pub fn mem_slice_mut<'vm>(&'vm mut self, addr: GuestAddress, size: u64) -> &'vm mut [u8] {
        let mapping = self.map_containing_mut(addr, size).expect("mapping is valid");

        // SAFETY: we have an exclusive borrow of the VM, so it is not currently running, and there
        // is no other outstanding slice of guest memory. `map_containing` has already ensured that
        // this mapping contains the whole range `[addr, addr + size)`.
        unsafe {
            mapping.slice_mut(addr, size)
        }
    }

    /// returns a slice of guest memory pointed to by guest-physical address `addr`, of size
    /// `size`.
    ///
    /// panics if `addr + size` is not enclosed in a single guest mapping. this crate doesn't
    /// support returning a single slice of adjacent guest memory regions (yet?), sorry.
    pub fn mem_slice<'vm>(&'vm self, addr: GuestAddress, size: u64) -> &'vm [u8] {
        let mapping = self.map_containing(addr, size).expect("mapping is valid");

        // SAFETY: we have an exclusive borrow of the VM, so it is not currently running, and there
        // is no other outstanding slice of guest memory. `map_containing` has already ensured that
        // this mapping contains the whole range `[addr, addr + size)`.
        unsafe {
            mapping.slice(addr, size)
        }
    }

    /// write `code` into guest memory and set `regs.rip` to the address of that code.
    ///
    /// the chosen code address is [`Self::code_addr`]; this is the guest linear address the
    /// provided code buffer is written to.
    ///
    /// if the VM is configured for `IsaMode::Long` or `IsaMode::Protected`, `rip` or `eip` is set
    /// to this address as well. otherwise, the VM is configured for `IsaMode::Real` and `ip` is
    /// set to `code_addr() & 0x0f` - in typical cases `ip` will be 0.
    ///
    pub fn program(&mut self, code: &[u8], regs: &mut kvm_regs) {
        let addr = self.code_addr();
        self.write_mem(addr, code);

        if self.settings.isa_mode != IsaMode::Real {
            regs.rip = addr.0;
        } else {
            regs.rip = addr.0 & 0x000f;
        }
    }

    fn gdt_entry_mut(&mut self, idx: u16) -> *mut u64 {
        // the GDT is set up at addresses 0..64k:
        //
        // > 3.5.1 Segment Descriptor Tables
        // > A segment descriptor table is an array of segment descriptors (see Figure 3-10). A
        // > descriptor table is variable in length and can contain up to 8192 (2^13) 8-byte
        // > descriptors.

        assert!(idx < 4096 / 8);
        let addr = GuestAddress(self.gdt_addr().0 + (idx as u64 * 8));
        let mapping = self.map_containing(addr, std::mem::size_of::<u64>() as u64).unwrap();

        // SAFETY: idx * 8 can't overflow isize, and we've asserted the end of the pointer is
        // still inside the allocation (`self.memory`).
        unsafe {
            mapping.host_ptr(addr) as *mut u64
        }
    }

    // note this returns a u32, but a long-mode IDT is four u32. the u32 this points at is the
    // first of the four for the entry.
    fn idt_entry_mut(&mut self, idx: u8) -> *mut u32 {
        let addr = GuestAddress(self.idt_addr().0 + (idx as u64 * 16));
        let mapping = self.map_containing(addr, std::mem::size_of::<[u64; 2]>() as u64).unwrap();

        unsafe {
            mapping.host_ptr(addr) as *mut u32
        }
    }

    // note this returns a u32, but a legacy IDT is two u32. the u32 this points at is the
    // first of the four for the entry.
    fn idt_entry_legacy_mut(&mut self, idx: u8) -> *mut u32 {
        let addr = GuestAddress(self.idt_addr().0 + (idx as u64 * 8));
        let mapping = self.map_containing(addr, std::mem::size_of::<[u64; 2]>() as u64).unwrap();

        unsafe {
            mapping.host_ptr(addr) as *mut u32
        }
    }

    pub fn page_tables(&self) -> VmPageTables<'_> {
        let base = self.page_table_addr();

        // the page tables are really just two pages: a PML4 and a PDPT for its first 512G of
        // address space.
        assert!(self.map_containing(base, 0x2000).is_some());

        VmPageTables {
            vm: self,
            base,
        }
    }

    // TODO: there should be a version of this that can be used to query "does this VM support
    // these extensions" probably, and that should take a subset of `Feature` for the ones that are
    // actually related to ISA support (e.g. Pdpe1Gb isn't really useful as a public queryable
    // feature..)
    fn cpuid_supports(&self, feature: Feature) -> bool {
        fn find_leaf(cpuid: &CpuId, leaf: u32, index: u32, f: impl Fn(&kvm_cpuid_entry2) -> bool) -> bool {
            for mut entry in cpuid.as_slice() {
                if entry.function == leaf && entry.index == index {
                    return f(&mut entry);
                }
            }

            false
        }

        match feature {
            Feature::Base => {
                let lm = find_leaf(&self.supported_cpuid, 0x8000_0001, 0, |leaf| {
                    leaf.edx & CPUID_80000001_EDX_LM != 0
                });
                let msr = find_leaf(&self.supported_cpuid, 0x0000_0001, 0, |leaf| {
                    leaf.edx & CPUID_00000001_EDX_MSR != 0
                });
                let clstac = find_leaf(&self.supported_cpuid, 0x0000_0007, 0, |leaf| {
                    leaf.ebx & CPUID_00000007_EBX_CLSTAC != 0
                });
                lm && msr && clstac
            }
            Feature::Syscall => {
                find_leaf(&self.supported_cpuid, 0x8000_0001, 0, |leaf| {
                    leaf.edx & CPUID_80000001_EDX_SYSCALL != 0
                })
            }
            Feature::XSave => {
                find_leaf(&self.supported_cpuid, 0x0000_0001, 0, |leaf| {
                    leaf.edx & CPUID_00000001_ECX_XSAVE != 0
                })
            }
            Feature::Pdpe1Gb => {
                find_leaf(&self.supported_cpuid, 0x8000_0001, 0, |leaf| {
                    leaf.edx & CPUID_80000001_EDX_PDPE1GB != 0
                })
            }
            Feature::StateSSE => {
                find_leaf(&self.supported_cpuid, 0x0000_000d, 0, |leaf| {
                    leaf.eax & CPUID_0000000D_EAX_SSE == CPUID_0000000D_EAX_SSE
                })
            }
            Feature::StateAVX => {
                find_leaf(&self.supported_cpuid, 0x0000_000d, 0, |leaf| {
                    leaf.eax & CPUID_0000000D_EAX_AVX == CPUID_0000000D_EAX_AVX
                })
            }
            Feature::StateAVX512 => {
                find_leaf(&self.supported_cpuid, 0x0000_000d, 0, |leaf| {
                    leaf.eax & CPUID_0000000D_EAX_AVX512 == CPUID_0000000D_EAX_AVX512
                })
            }
            Feature::Pse => {
                find_leaf(&self.supported_cpuid, 0x0000_0001, 0, |leaf| {
                    leaf.edx & CPUID_00000001_EDX_PSE == CPUID_00000001_EDX_PSE
                })
            }
        }
    }

    /// set `feature` to `wanted` in the VM's CPUID configuration.
    ///
    /// panics if the feature cannot be configured (such as if the corresponding CPUID leaf is not
    /// available at all). use [`cpuid_supports`] to test if the feature can be configured.
    fn cpuid_set(&mut self, feature: Feature, wanted: bool) {
        fn edit_leaf(cpuid: &mut CpuId, leaf: u32, index: u32, mut f: impl FnMut(&mut kvm_cpuid_entry2)) {
            for mut entry in cpuid.as_mut_slice() {
                if entry.function == leaf && entry.index == index {
                    f(&mut entry);
                    return;
                }
            }

            // if we're here, the entry simply is not present (yet..?)
            //
            // so, create it.
            let mut entry = kvm_cpuid_entry2 {
                function: leaf,
                index: index,
                eax: 0,
                ecx: 0,
                edx: 0,
                ebx: 0,
                flags: 0,
                padding: [0; 3],
            };
            f(&mut entry);
            cpuid.push(entry).expect("can push");
        }

        fn bit_set(word: &mut u32, bit: u32, wanted: bool) {
            *word &= !bit;
            if wanted {
                *word |= bit;
            }
        }

        let mut edited = false;

        match feature {
            Feature::Base => {
                edit_leaf(&mut self.current_cpuid, 0x8000_0001, 0, |leaf| {
                    bit_set(&mut leaf.edx, CPUID_80000001_EDX_LM, wanted);
                    edited = true;
                });
                edit_leaf(&mut self.current_cpuid, 0x0000_0001, 0, |leaf| {
                    bit_set(&mut leaf.edx, CPUID_00000001_EDX_MSR, wanted);
                    edited = true;
                });
                edit_leaf(&mut self.current_cpuid, 0x0000_0007, 0, |leaf| {
                    bit_set(&mut leaf.ebx, CPUID_00000007_EBX_CLSTAC, wanted);
                    edited = true;
                });
            }
            Feature::Syscall => {
                edit_leaf(&mut self.current_cpuid, 0x8000_0001, 0, |leaf| {
                    bit_set(&mut leaf.edx, CPUID_80000001_EDX_SYSCALL, wanted);
                    edited = true;
                });
            }
            Feature::XSave => {
                edit_leaf(&mut self.current_cpuid, 0x0000_0001, 0, |leaf| {
                    bit_set(&mut leaf.ecx, CPUID_00000001_ECX_XSAVE, wanted);
                    edited = true;
                });
            },
            Feature::Pdpe1Gb => {
                edit_leaf(&mut self.current_cpuid, 0x8000_0001, 0, |leaf| {
                    bit_set(&mut leaf.edx, CPUID_80000001_EDX_PDPE1GB, wanted);
                    edited = true;
                });
            },
            Feature::StateSSE => {
                edit_leaf(&mut self.current_cpuid, 0x0000_000d, 0, |leaf| {
                    bit_set(&mut leaf.eax, 1, wanted);
                    bit_set(&mut leaf.eax, CPUID_0000000D_EAX_SSE, wanted);
                    edited = true;
                });
            }
            Feature::StateAVX => {
                edit_leaf(&mut self.current_cpuid, 0x0000_000d, 0, |leaf| {
                    bit_set(&mut leaf.eax, CPUID_0000000D_EAX_AVX, wanted);
                    edited = true;
                });
            }
            Feature::StateAVX512 => {
                edit_leaf(&mut self.current_cpuid, 0x0000_000d, 0, |leaf| {
                    bit_set(&mut leaf.eax, CPUID_0000000D_EAX_AVX512, wanted);
                    edited = true;
                });
            }
            Feature::Pse => {
                edit_leaf(&mut self.current_cpuid, 0x0000_0001, 0, |leaf| {
                    bit_set(&mut leaf.edx, CPUID_00000001_EDX_PSE, wanted);
                    edited = true;
                });
            }
        }

        assert!(edited);

        self.vcpu.set_cpuid2(&self.current_cpuid).expect("can set cpuid");
    }

    /// configure page tables for identity mapping of all memory from guest address zero up to the
    /// end of added memory regions, rounded up to the next GiB.
    ///
    /// if `sregs` is provided, update `cr0`, `cr3`, and `cr4` in support of protected-mode or
    /// long-mode paging. this is a fixed pattern: if control registers have not been changed since
    /// `Vm::create` then there will be no change to these control registers and `sregs` can be
    /// omitted.
    ///
    /// panics if the end of added memory regions is above 512 GiB.
    pub unsafe fn configure_identity_paging(&mut self, sregs: Option<&mut kvm_sregs>) {
        // we're only setting up one PDPT, which can have up to 512 PDPTE covering 1G each.
        assert!(self.mem_ceiling() <= 512 * GB);

        assert!(self.cpuid_supports(Feature::Pdpe1Gb));
        self.cpuid_set(Feature::Pdpe1Gb, true);

        let pt = self.page_tables();

        let pml4_ent =
            1 << 0 | // P
            1 << 1 | // RW
            1 << 2 | // user access allowed. but no user code will run so not strictly needed.
            0 << 3 | // PWT (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 4 | // PCD (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 5 | // A
            0 << 6 | // ignored
            0 << 7 | // PS (reserved must-be-0)
            0 << 11 | // R (for ordinary paging, ignored; for HLAT ...)
            pt.pdpt_addr().0;
        unsafe {
            pt.pml4_mut().write(pml4_ent);
        }

        let mut mapped: u64 = 0;
        // we've set up the first PML4 to point to a PDPT, so we should actually set it up!
        let pdpt = pt.pdpt_mut();
        // PDPTEs start at the start of PDPT..
        let mut pdpte = pdpt;
        let entry_bits: u64 =
            1 << 0 | // P
            1 << 1 | // RW
            1 << 2 | // user accesses allowed (everything is under privilege level 0 tho)
            0 << 3 | // PWT (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 4 | // PCD (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 5 | // Accessed
            0 << 6 | // Dirty
            1 << 7 | // Page size (1 implies 1G page)
            1 << 8 | // Global (if cr4.pge)
            0 << 9 |
            0 << 10 |
            0 << 11 | // for ordinary paging, ignored. for HLAT, ...
            0 << 12; // PAT (TODO: configure explicitly, but PAT0 is sufficient. verify MTRR sets PAT0 to WB?)

        while mapped < self.mem_ceiling() {
            let phys_num = mapped >> 30;
            let entry = entry_bits | (phys_num << 30);
            unsafe {
                pdpte.write(entry);
                pdpte = pdpte.offset(1);
            }
            // eprintln!("mapped 1g at {:08x}", mapped);
            mapped += 1 << 30;
        }

        if let Some(sregs) = sregs {
            sregs.cr0 |= 0x8000_0001; // cr0.PE | cr0.PG
            sregs.cr3 = pt.pml4_addr().0 as u64;
            sregs.cr4 |= 1 << 5; // enable PAE
        }
    }

    /// configure page tables for identity mapping of all memory from guest address zero up to the
    /// end of added memory regions, rounded up to the next 4MiB.
    ///
    /// if `sregs` is provided, update `cr0`, `cr3`, and `cr4` in support of protected-mode paging.
    /// this is a fixed pattern: if control registers have not been changed since `Vm::create` then
    /// there will be no change to these control registers and `sregs` can be omitted.
    pub unsafe fn configure_identity_paging_32b(&mut self, sregs: Option<&mut kvm_sregs>) {
        // because we'll set PDEs to map 4M pages and cr3 points at a page-aligned block of 1024
        // 4-byte PDEs, that gives us 4KiB of memory used to map 4GiB of address space. that's all
        // of 32-bit, so we don't need to check an upper bound.

        assert!(self.cpuid_supports(Feature::Pse));
        self.cpuid_set(Feature::Pse, true);

        let pt = self.page_tables();

        let mut mapped: u64 = 0;
        // "pml4_mut" is really just the start of page table memory. we'll pun this in 32-bit with
        // the knowledge it's really a block of PDEs.
        let pd = pt.pml4_mut() as *mut u32;
        let mut pde = pd;
        let entry_bits: u32 =
            1 << 0 | // P
            1 << 1 | // RW
            1 << 2 | // user accesses allowed (everything is under privilege level 0 tho)
            0 << 3 | // PWT (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 4 | // PCD (TODO: configure PAT explicitly, but PAT0 is sufficient)
            0 << 5 | // Accessed
            0 << 6 | // Dirty
            1 << 7 | // Page size (1 implies 4M page)
            1 << 8 | // Global (if cr4.pge)
            0 << 9 |
            0 << 10 |
            0 << 11 | // for ordinary paging, ignored. for HLAT, ...
            0 << 12; // PAT (TODO: configure explicitly, but PAT0 is sufficient. verify MTRR sets PAT0 to WB?)

        while mapped < self.mem_ceiling() {
            let phys_num = (mapped as u32) >> 22;
            let entry = entry_bits | (phys_num << 22);
            unsafe {
                pde.write(entry);
                pde = pde.offset(1);
            }
            mapped += 1 << 22;
        }

        // page size extensions; collaborates with page tables' PS bit to make 4MiB pages in 32-bit
        // mode. see SDM section 2.5 "CONTROL REGISTERS".
        const PSE: u64 = 1 << 4;

        if let Some(sregs) = sregs {
            sregs.cr0 |= 0x8000_0001; // cr0.PE | cr0.PG
            sregs.cr3 = pt.pml4_addr().0 as u64;
            sregs.cr4 |= PSE;
        }
    }

    unsafe fn configure_selectors(&mut self, sregs: &mut kvm_sregs) {
        // we have to set descriptor information directly. this avoids having to load selectors
        // as the first instructions on the vCPU, which is simplifying. but if we want the
        // information in these selectors to match with anything in a GDT (i do!) we'll have to
        // keep this initial state lined up with GDT entries ourselves.
        //
        // we could avoid setting up the GDT for the most part, but anything that might
        // legitimately load the "valid" current segment selector would instead clobber the
        // selector with zeroes.

        sregs.cs.base = 0;
        sregs.cs.limit = 0;
        sregs.cs.selector = self.selector_cs();
        sregs.cs.type_ = 0b1011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.cs.present = 1;
        sregs.cs.dpl = 0;
        sregs.cs.db = 0;
        sregs.cs.s = 1;
        sregs.cs.l = 1;
        sregs.cs.g = 0;
        sregs.cs.avl = 0;

        sregs.ds.base = 0;
        sregs.ds.limit = 0xffffffff;
        sregs.ds.selector = self.selector_ds();
        sregs.ds.type_ = 0b0011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.ds.present = 1;
        sregs.ds.dpl = 0;
        sregs.ds.db = 0;
        sregs.ds.s = 1;
        sregs.ds.l = 0;
        sregs.ds.g = 0;
        sregs.ds.avl = 0;

        sregs.es = sregs.ds;
        sregs.fs = sregs.ds;
        sregs.gs = sregs.ds;
        // linux populates the vmcb cpl field with whatever's in ss.dpl. what the hell???
        sregs.ss = sregs.ds;

        sregs.gdt.base = self.gdt_addr().0;
        sregs.gdt.limit = 256 * 8 - 1;

        unsafe {
            self.gdt_entry_mut(self.selector_cs() >> 3).write(encode_segment(&sregs.cs));
            self.gdt_entry_mut(self.selector_ds() >> 3).write(encode_segment(&sregs.ds));
        }
    }

    /// configure selectors for 32-bit code exceution. this is basically the same as 64-bit, but we
    /// set a limit and set `cs.db` so that the default operand size is a normal 32-bit.
    unsafe fn configure_selectors_32b(&mut self, sregs: &mut kvm_sregs) {
        // we have to set descriptor information directly. this avoids having to load selectors
        // as the first instructions on the vCPU, which is simplifying. but if we want the
        // information in these selectors to match with anything in a GDT (i do!) we'll have to
        // keep this initial state lined up with GDT entries ourselves.
        //
        // we could avoid setting up the GDT for the most part, but anything that might
        // legitimately load the "valid" current segment selector would instead clobber the
        // selector with zeroes.

        sregs.cs.base = 0;
        sregs.cs.limit = 0xffffffff;
        sregs.cs.selector = self.selector_cs();
        sregs.cs.type_ = 0b1011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.cs.present = 1;
        sregs.cs.dpl = 0;
        sregs.cs.db = 1;
        sregs.cs.s = 1;
        sregs.cs.l = 0;
        sregs.cs.g = 1;
        sregs.cs.avl = 0;

        sregs.ds.base = 0;
        sregs.ds.limit = 0xffffffff;
        sregs.ds.selector = self.selector_ds();
        sregs.ds.type_ = 0b0011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.ds.present = 1;
        sregs.ds.dpl = 0;
        sregs.ds.db = 1;
        sregs.ds.s = 1;
        sregs.ds.l = 0;
        sregs.ds.g = 1;
        sregs.ds.avl = 0;

        sregs.es = sregs.ds;
        sregs.fs = sregs.ds;
        sregs.gs = sregs.ds;
        // linux populates the vmcb cpl field with whatever's in ss.dpl. what the hell???
        sregs.ss = sregs.ds;

        sregs.gdt.base = self.gdt_addr().0;
        sregs.gdt.limit = 256 * 8 - 1;

        unsafe {
            self.gdt_entry_mut(self.selector_cs() >> 3).write(encode_segment(&sregs.cs));
            self.gdt_entry_mut(self.selector_ds() >> 3).write(encode_segment(&sregs.ds));
        }
    }

    /// configure selectors for 16-bit code exceution.
    ///
    /// unlike other modes, this sets `cs` to execute code at the linear address given by
    /// [`Self::code_addr`]. `ds` is configured to overlap with `cs`. this way, when executing
    /// 16-bit code the VM can simply be configured to `ip = 0`, and code addresses match data
    /// addresses. additionally, clear `cs.db` so that the default operand size is 16-bit.
    unsafe fn configure_selectors_16b(&mut self, sregs: &mut kvm_sregs) {
        // we have to set descriptor information directly. this avoids having to load selectors
        // as the first instructions on the vCPU, which is simplifying. but if we want the
        // information in these selectors to match with anything in a GDT (i do!) we'll have to
        // keep this initial state lined up with GDT entries ourselves.
        //
        // we could avoid setting up the GDT for the most part, but anything that might
        // legitimately load the "valid" current segment selector would instead clobber the
        // selector with zeroes.

        sregs.cs.base = 0;
        sregs.cs.limit = 0xfffff;
        sregs.cs.selector = self.selector_cs();
        sregs.cs.type_ = 0b1011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.cs.present = 1;
        sregs.cs.dpl = 0;
        sregs.cs.db = 0;
        sregs.cs.s = 1;
        sregs.cs.l = 0;
        sregs.cs.g = 1;
        sregs.cs.avl = 0;

        unsafe {
            self.gdt_entry_mut(self.selector_cs_idt_16b() >> 3).write(encode_segment(&sregs.cs));
        }

        // and now adjust for the real cs for code execution to happen in..
        sregs.cs.base = self.code_addr().0;

        sregs.ds.base = self.code_addr().0;
        sregs.ds.limit = 0xfffff;
        sregs.ds.selector = self.selector_ds();
        sregs.ds.type_ = 0b0011; // see SDM table 3-1 Code- and Data-Segment Types
        sregs.ds.present = 1;
        sregs.ds.dpl = 0;
        sregs.ds.db = 0;
        sregs.ds.s = 1;
        sregs.ds.l = 0;
        sregs.ds.g = 1;
        sregs.ds.avl = 0;

        sregs.es = sregs.ds;
        sregs.fs = sregs.ds;
        sregs.gs = sregs.ds;
        // linux populates the vmcb cpl field with whatever's in ss.dpl. what the hell???
        sregs.ss = sregs.ds;

        sregs.gdt.base = self.gdt_addr().0;
        sregs.gdt.limit = 256 * 8 - 1;

        unsafe {
            self.gdt_entry_mut(self.selector_cs() >> 3).write(encode_segment(&sregs.cs));
            self.gdt_entry_mut(self.selector_ds() >> 3).write(encode_segment(&sregs.ds));
        }
    }

    fn write_idt_entry(
        &mut self,
        intr_nr: u8,
        interrupt_handler_cs: u16,
        interrupt_handler_addr: GuestAddress
    ) {
        let idt_ptr = self.idt_entry_mut(intr_nr);

        // entries in the IDT, interrupt and trap descriptors (in the AMD APM, "interrupt-gate"
        // and "trap-gate" descriptors), are described (in the AMD APM) by
        // "Figure 4-24. Interrupt-Gate and Trap-Gate Descriptors—Long Mode". reproduced here:
        //
        //  3   2                 1        |          1                   0
        //  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6|5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
        // |---------------------------------------------------------------|
        // |                            res,ign                            | +12
        // |                      target offset[63:32]                     | +8
        // |     target offset[31:16]      |P|DPL|0| type  | res,ign | IST | +4
        // |     target selector           |    target offset[15:0]        | +0
        // |---------------------------------------------------------------|
        //
        // descriptors are encoded with P set, DPL at 0, and type set to 0b1110. TODO: frankly
        // i don't know the mechanical difference between type 0x0e and type 0x0f, but 0x0e
        // works for now.
        let idt_attr_bits = 0b1_00_0_1110_00000_000;
        let low_hi = (interrupt_handler_addr.0 as u32 & 0xffff_0000) | idt_attr_bits;
        let low_lo = (interrupt_handler_cs as u32) << 16 | (interrupt_handler_addr.0 as u32 & 0x0000_ffff);

        unsafe {
            idt_ptr.offset(0).write(low_lo);
            idt_ptr.offset(1).write(low_hi);
            idt_ptr.offset(2).write((interrupt_handler_addr.0 >> 32) as u32);
            idt_ptr.offset(3).write(0); // reserved
        }
    }

    /// 16-bit/32-bit IDT entries, described in the APM as
    ///
    /// > Interrupt-Gate and Trap-Gate Descriptors—Legacy Mode
    ///
    /// have a different (smaller!) format.
    fn write_idt_entry_legacy(
        &mut self,
        intr_nr: u8,
        interrupt_handler_cs: u16,
        interrupt_handler_addr: GuestAddress
    ) {
        assert!(interrupt_handler_addr.0 <= u32::MAX as u64);
        let idt_ptr = self.idt_entry_legacy_mut(intr_nr);

        // entries in the IDT, interrupt and trap descriptors (in the AMD APM, "interrupt-gate"
        // and "trap-gate" descriptors), are described (in the AMD APM) by
        // "Figure 4-24. Interrupt-Gate and Trap-Gate Descriptors—Long Mode". reproduced here:
        //
        //  3   2                 1        |          1                   0
        //  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6|5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
        // |---------------------------------------------------------------|
        // |     target offset[31:16]      |P|DPL|0| type  | res,ign | IST | +4
        // |     target selector           |    target offset[15:0]        | +0
        // |---------------------------------------------------------------|
        //
        // descriptors are encoded with P set, DPL at 0, and type set to 0b1110. TODO: frankly
        // i don't know the mechanical difference between type 0x0e and type 0x0f, but 0x0e
        // works for now.
        let idt_attr_bits = 0b1_00_0_1110_00000_000;
        let low_hi = (interrupt_handler_addr.0 as u32 & 0xffff_0000) | idt_attr_bits;
        let low_lo = (interrupt_handler_cs as u32) << 16 | (interrupt_handler_addr.0 as u32 & 0x0000_ffff);

        unsafe {
            idt_ptr.offset(0).write(low_lo);
            idt_ptr.offset(1).write(low_hi);
        }
    }

    fn configure_idt(&mut self, regs: &mut kvm_regs, sregs: &mut kvm_sregs) {
        sregs.idt.base = self.idt_addr().0;
        sregs.idt.limit = IDT_ENTRIES * 16 - 1; // IDT is 256 entries of 16 bytes each

        for i in 0..IDT_ENTRIES {
            let interrupt_handler_addr = GuestAddress(self.interrupt_handlers_start().0 + i as u64);
            self.write_idt_entry(
                i.try_into().expect("<u8::MAX interrupts"),
                self.selector_cs(),
                interrupt_handler_addr
            );
        }

        // all interrupt handlers are just `hlt`. their position is used to detect which
        // exception/interrupt occurred.
        unsafe {
            std::slice::from_raw_parts_mut(
                self.host_ptr(self.interrupt_handlers_start()),
                IDT_ENTRIES as usize
            ).fill(0xf4);
        }

        // finally, set `rsp` to a valid region so that the CPU can push necessary state (see
        // AMD APM section "8.9.3 Interrupt Stack Frame") to actually enter the interrupt
        // handler. if we didn't do this, rsp will probably be zero or something, underflow,
        // page fault on push to 0xffffffff_ffffffff, and just triple fault.
        //
        // TODO: this is our option in 16- and 32-bit modes, but in long mode all the interrupt
        // descriptors could set something in IST to switch stacks outright for exception
        // handling. this might be nice to test rsp permutations in 64-bit code? alternatively
        // we might just have to limit possible rsp permutations so as to be able to test in
        // 16- and 32-bit modes anyway.
        regs.rsp = self.stack_addr().0;
        self.idt_configured = true;
    }

    /// IDT configuration in 32-bit mode is funky because the interrupt handlers live in a totally
    /// different region of memory and need a different value in `cs`.
    fn configure_idt_32b(&mut self, regs: &mut kvm_regs, sregs: &mut kvm_sregs) {
        sregs.idt.base = self.idt_addr().0;
        sregs.idt.limit = IDT_ENTRIES * 8 - 1; // legacy IDT is 256 entries of 8 bytes each

        for i in 0..IDT_ENTRIES {
            let interrupt_handler_addr = GuestAddress(self.interrupt_handlers_start().0 + i as u64);
            self.write_idt_entry_legacy(
                i.try_into().expect("<u8::MAX interrupts"),
                self.selector_cs(),
                interrupt_handler_addr
            );
        }

        // all interrupt handlers are just `hlt`. their position is used to detect which
        // exception/interrupt occurred.
        unsafe {
            std::slice::from_raw_parts_mut(
                self.host_ptr(self.interrupt_handlers_start()),
                IDT_ENTRIES as usize
            ).fill(0xf4);
        }

        // finally, set `rsp` to a valid region so that the CPU can push necessary state (see
        // AMD APM section "8.9.3 Interrupt Stack Frame") to actually enter the interrupt
        // handler. if we didn't do this, rsp will probably be zero or something, underflow,
        // page fault on push to 0xffffffff_ffffffff, and just triple fault.
        //
        // TODO: this is our option in 16- and 32-bit modes, but in long mode all the interrupt
        // descriptors could set something in IST to switch stacks outright for exception
        // handling. this might be nice to test rsp permutations in 64-bit code? alternatively
        // we might just have to limit possible rsp permutations so as to be able to test in
        // 16- and 32-bit modes anyway.
        regs.rsp = self.stack_addr().0;
        self.idt_configured = true;
    }

    /// IDT configuration in 16-bit mode is funky because the interrupt handlers live in a totally
    /// different region of memory and need a different value in `cs`.
    fn configure_idt_16b(&mut self, regs: &mut kvm_regs, sregs: &mut kvm_sregs) {
        sregs.idt.base = self.idt_addr().0;
        sregs.idt.limit = IDT_ENTRIES * 8 - 1; // IDT is 256 entries of 8 bytes each

        for i in 0..IDT_ENTRIES {
            let interrupt_handler_addr = GuestAddress(self.interrupt_handlers_start().0 + i as u64);
            self.write_idt_entry_legacy(
                i.try_into().expect("<u8::MAX interrupts"),
                self.selector_cs_idt_16b(),
                interrupt_handler_addr
            );
        }

        // all interrupt handlers are just `hlt`. their position is used to detect which
        // exception/interrupt occurred.
        unsafe {
            std::slice::from_raw_parts_mut(
                self.host_ptr(self.interrupt_handlers_start()),
                IDT_ENTRIES as usize
            ).fill(0xf4);
        }

        // finally, set `rsp` to a valid region so that the CPU can push necessary state (see
        // AMD APM section "8.9.3 Interrupt Stack Frame") to actually enter the interrupt
        // handler. if we didn't do this, rsp will probably be zero or something, underflow,
        // page fault on push to 0xffffffff_ffffffff, and just triple fault.
        //
        // TODO: this is our option in 16- and 32-bit modes, but in long mode all the interrupt
        // descriptors could set something in IST to switch stacks outright for exception
        // handling. this might be nice to test rsp permutations in 64-bit code? alternatively
        // we might just have to limit possible rsp permutations so as to be able to test in
        // 16- and 32-bit modes anyway.
        regs.rsp = self.stack_addr().0;
        self.idt_configured = true;
    }

    /// configure the vCPU for executing instructions in the hardware-supported extensions.
    /// on a fresh vCPU, various extension may be "supported" but result in `#UD` when executed,
    /// unless additional configuration is done (as this function does).
    ///
    /// the Intel SDM describes `INITIALIZING SSE/SSE2/SSE3/SSSE3 EXTENSIONS` but does not point
    /// out this `#UD` behavior so directly. the AMD APM does not seem to discuss it at all?
    ///
    /// this function configures the vCPU to be ready to execute `SSE*` instructions.
    fn configure_extensions(&mut self, sregs: &mut kvm_sregs, xcrs: &mut kvm_xcrs) {
        // these bit positions in control registers, and their behaviors, are described more
        // comprehensively in Voluem 3,
        // > `2.5 CONTROL REGISTERS`

        // CR0
        const TS: u32 = 3;
        // CR4
        const OSFXSR: u32 = 9;
        const OSXMMEXCPT: u32 = 10;
        const OSXSAVE: u32 = 18;

        // XCR0 (see "EXTENDED CONTROL REGISTERS (INCLUDING XCR0)")
        // these bits are the same as in cpuid leaf 0xd.eax
        const XCR0_SSE: u64 = CPUID_0000000D_EAX_SSE as u64;
        const XCR0_AVX: u64 = CPUID_0000000D_EAX_AVX as u64;
        const XCR0_AVX512: u64 = CPUID_0000000D_EAX_AVX512 as u64;

        // operations on `xmm` registers result in `#UD` even if CPUID says that SSE should be
        // quite functional. this is true even for SSE or SSE2 instructions on an `x86_64` system
        // (which makes SSE a non-optional baseline!)
        //
        // the Intel SDM implies this through somewhat tortured language in the section
        // "Checking for Intel® SSE and SSE2 Support":
        // > If an operating system did not provide adequate system level support for Intel
        // > SSE, executing an Intel SSE or SSE2 instructions can also generate #UD.
        //
        // to fully understand this statement, realize that `an operating system .. provide[s]
        // adequate system level support" by setting CR4.OSFXSR,
        //
        // > Set the OSFXSR flag (bit 9 in control register CR4) to indicate that the operating
        // > system supports saving and restoring the SSE/SSE2/SSE3/SSSE3 execution environment
        //
        // so OSFXSR is how "the operating system" indicates save/restore state, and must be set to
        // execute SSE (and later) SIMD instructions even if we never will use `fxsave` or even
        // switch tasks on the vCPU.
        sregs.cr4 |= 1 << OSFXSR;

        // there is a similar relationship between SIMD extension functionality and CR4.OSXSAVE.
        // this passage in the SDM under "XSAVE-SUPPORTED FEATURES AND STATE-COMPONENT BITMAPS"
        // draws a fairly direct connection:
        //
        // > As will be explained in Section 13.3, the XSAVE feature set is enabled only if
        // > CR4.OSXSAVE[bit 18] = 1. If CR4.OSXSAVE = 0, the processor treats XSAVE-enabled state
        // > features and their state components as if all bits in XCR0 were clear; the state
        // > components cannot be modified and the features’ instructions cannot be executed.
        //
        // but the consequence is contradicted by the next paragraph,
        //
        // > Processors allow modification of this state, as well as execution of x87 FPU
        // > instructions and SSE instructions [...] , regardless of the value of CR4.OSXSAVE and
        // > XCR0.
        //
        // we will see that CR4.OSXSAVE must be set for other SIMD extensions below, as well.
        sregs.cr4 |= 1 << OSXSAVE;

        // SSE3, SSSE3, and SSE4 involve a bit extra:
        // > Intel SSE3, SSSE3, and Intel SSE4 will cause a DNA Exception (#NM) if the processor
        // > attempts to execute an Intel SSE3 instruction while CR0.TS[bit 3] = 1
        sregs.cr0 &= !(1 << TS);

        // > Set the OSXMMEXCPT flag (bit 10 in control register CR4) to indicate that the operating
        // > system supports the handling of SSE/SSE2/SSE3 SIMD floating-point exceptions (#XM).
        //
        // this is somewhat better than just getting an uncategorized #UD.
        sregs.cr4 |= 1 << OSXMMEXCPT;

        assert!(xcrs.nr_xcrs > 0);
        assert_eq!(xcrs.xcrs[0].xcr, 0);

        let mut needs_xsave = false;
        if self.cpuid_supports(Feature::StateSSE) {
            self.cpuid_set(Feature::StateSSE, true);
            xcrs.xcrs[0].value |= 1;
            xcrs.xcrs[0].value |= XCR0_SSE;
            needs_xsave = true;
        }
        if self.cpuid_supports(Feature::StateAVX) {
            self.cpuid_set(Feature::StateAVX, true);
            xcrs.xcrs[0].value |= XCR0_AVX;
            needs_xsave = true;
        }
        if self.cpuid_supports(Feature::StateAVX512) {
            self.cpuid_set(Feature::StateAVX512, true);
            xcrs.xcrs[0].value |= XCR0_AVX512;
            needs_xsave = true;
        }

        if needs_xsave {
            if self.cpuid_supports(Feature::XSave) {
                self.cpuid_set(Feature::XSave, true);
            } else {
                panic!(
                    "look, there's no CPU that supports SSE but not xsave. \
                    i only checked to be thorough.");
            }
        }
    }

    fn configure_syscalls(&mut self, vcpu_sregs: &mut kvm_sregs) {
        assert!(self.cpuid_supports(Feature::Syscall));
        self.cpuid_set(Feature::Syscall, true);

        // > System-Call Extension (SCE) Bit.
        vcpu_sregs.efer |= 0x0000_0001;

        let msrs = Msrs::from_entries(&[
            kvm_msr_entry {
                // LSTAR (C000_0082h)
                index: 0xc000_0082,
                data: self.syscall_addr().0,
                reserved: 0,
            },
            kvm_msr_entry {
                // CSTAR (C000_0083h)
                index: 0xc000_0083,
                data: self.syscall_addr().0,
                reserved: 0,
            }
        ]).unwrap();
        self.set_msrs(&msrs).unwrap();

        // fill the syscall landing area with hlt to trap out immediately.
        self.mem_slice_mut(self.syscall_addr(), 16).fill(0xf4);

        self.syscall_configured = true;
    }
}