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
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! This module implements the interactive control process and the entry point
//! for the worker process.

mod cli_args;
mod console;
mod meshworker;
mod serial_io;
mod storage_builder;
mod tracing_init;
mod ttrpc;

// `pub` so that the missing_docs warning fires for options without
// documentation.
pub use cli_args::Options;

use crate::cli_args::SecureBootTemplateCli;
use anyhow::bail;
use anyhow::Context;
use chipset_resources::battery::HostBatteryUpdate;
use clap::CommandFactory;
use clap::FromArgMatches;
use clap::Parser;
use cli_args::DiskCliKind;
use cli_args::EndpointConfigCli;
use cli_args::NicConfigCli;
use cli_args::SerialConfigCli;
use cli_args::UefiConsoleModeCli;
use floppy_resources::FloppyDiskConfig;
use framebuffer::FramebufferAccess;
use framebuffer::FRAMEBUFFER_SIZE;
use futures::executor::block_on;
use futures::io::AllowStdIo;
use futures::AsyncReadExt;
use futures::AsyncWrite;
use futures::AsyncWriteExt;
use futures::FutureExt;
use futures::StreamExt;
use futures_concurrency::stream::Merge;
use gdma_resources::GdmaDeviceHandle;
use gdma_resources::VportDefinition;
use guid::Guid;
use hvlite_defs::config::Config;
use hvlite_defs::config::DeviceVtl;
use hvlite_defs::config::HypervisorConfig;
use hvlite_defs::config::LateMapVtl0MemoryPolicy;
use hvlite_defs::config::LoadMode;
use hvlite_defs::config::MemoryConfig;
use hvlite_defs::config::ProcessorTopologyConfig;
use hvlite_defs::config::SerialInformation;
use hvlite_defs::config::VirtioBus;
use hvlite_defs::config::VmbusConfig;
use hvlite_defs::config::VpciDeviceConfig;
use hvlite_defs::config::Vtl2BaseAddressType;
use hvlite_defs::config::Vtl2Config;
use hvlite_defs::config::DEFAULT_MMIO_GAPS;
use hvlite_defs::config::DEFAULT_MMIO_GAPS_WITH_VTL2;
use hvlite_defs::config::DEFAULT_PCAT_BOOT_ORDER;
use hvlite_defs::rpc::PulseSaveRestoreError;
use hvlite_defs::rpc::VmRpc;
use hvlite_defs::worker::VmWorkerParameters;
use hvlite_defs::worker::VM_WORKER;
use hvlite_helpers::crash_dump::spawn_dump_handler;
use hvlite_helpers::disk::open_disk_type;
use input_core::MultiplexedInputHandle;
use inspect::InspectMut;
use inspect::InspectionBuilder;
use io::Read;
use mesh::error::RemoteError;
use mesh::rpc::Rpc;
use mesh::rpc::RpcSend;
use mesh::CancelContext;
use mesh::RecvError;
use mesh_worker::launch_local_worker;
use mesh_worker::WorkerEvent;
use mesh_worker::WorkerHandle;
use meshworker::VmmMesh;
use net_backend_resources::mac_address::MacAddress;
use pal_async::driver::Driver;
use pal_async::pipe::PolledPipe;
use pal_async::task::Spawn;
use pal_async::task::Task;
use pal_async::timer::PolledTimer;
use pal_async::DefaultDriver;
use pal_async::DefaultPool;
use scsidisk_resources::SimpleScsiDiskHandle;
use scsidisk_resources::SimpleScsiDvdHandle;
use serial_16550_resources::ComPort;
use serial_io::SerialIo;
use sparse_mmap::alloc_shared_memory;
use std::cell::RefCell;
use std::fmt::Write as _;
use std::future::pending;
use std::io;
#[cfg(unix)]
use std::io::IsTerminal;
use std::io::Write;
use std::net::TcpListener;
use std::path::Path;
use std::path::PathBuf;
use std::pin::pin;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use std::time::Instant;
use storvsp_resources::ScsiControllerRequest;
use storvsp_resources::ScsiDeviceAndPath;
use storvsp_resources::ScsiPath;
use tpm_resources::TpmDeviceHandle;
use tpm_resources::TpmRegisterLayout;
use tracing_helpers::AnyhowValueExt;
use ttrpc::TtrpcWorker;
use uidevices_resources::SynthKeyboardHandle;
use uidevices_resources::SynthMouseHandle;
use uidevices_resources::SynthVideoHandle;
use video_core::SharedFramebufferHandle;
use vm_manifest_builder::BaseChipsetType;
use vm_manifest_builder::MachineArch;
use vm_manifest_builder::VmChipsetResult;
use vm_manifest_builder::VmManifestBuilder;
use vm_resource::kind::DiskHandleKind;
use vm_resource::kind::NetEndpointHandleKind;
use vm_resource::kind::VmbusDeviceHandleKind;
use vm_resource::IntoResource;
use vm_resource::Resource;
use vmbus_serial_resources::VmbusSerialDeviceHandle;
use vmbus_serial_resources::VmbusSerialPort;
use vmcore::non_volatile_store::resources::EphemeralNonVolatileStoreHandle;
use vmgs_resources::VmgsFileHandle;
use vmotherboard::ChipsetDeviceHandle;
use vnc_worker_defs::VncParameters;

pub fn hvlite_main() {
    // Save the current state of the terminal so we can restore it back to
    // normal before exiting.
    #[cfg(unix)]
    let orig_termios = io::stderr().is_terminal().then(term::get_termios);

    let exit_code = match do_main() {
        Ok(_) => 0,
        Err(err) => {
            eprintln!("fatal error: {:?}", err);
            1
        }
    };

    // Restore the terminal to its initial state.
    #[cfg(unix)]
    if let Some(orig_termios) = orig_termios {
        term::set_termios(orig_termios);
    }

    // Terminate the process immediately without graceful shutdown of DLLs or
    // C++ destructors or anything like that. This is all unnecessary and saves
    // time on Windows.
    //
    // Do flush stdout, though, since there may be buffered data.
    let _ = io::stdout().flush();
    pal::process::terminate(exit_code);
}

#[derive(Default)]
struct VmResources {
    console_in: Option<Box<dyn AsyncWrite + Send + Unpin>>,
    framebuffer_access: Option<FramebufferAccess>,
    shutdown_ic: Option<mesh::Sender<hyperv_ic_resources::shutdown::ShutdownRpc>>,
    scsi_rpc: Option<mesh::Sender<ScsiControllerRequest>>,
    ged_rpc: Option<mesh::Sender<get_resources::ged::GuestEmulationRequest>>,
    #[cfg(windows)]
    switch_ports: Vec<vmswitch::kernel::SwitchPort>,
}

struct ConsoleState<'a> {
    device: &'a str,
    input: Box<dyn AsyncWrite + Unpin + Send>,
}

fn vm_config_from_command_line(
    spawner: impl Spawn,
    opt: &Options,
) -> anyhow::Result<(Config, VmResources)> {
    let serial_pool = DefaultPool::new();
    let serial_driver = serial_pool.driver();
    // Ensure the serial driver stays alive with no tasks.
    serial_driver.spawn("leak", pending::<()>()).detach();
    thread::Builder::new()
        .name("serial".to_string())
        .spawn(|| serial_pool.run())
        .unwrap();

    let console_state: RefCell<Option<ConsoleState<'_>>> = RefCell::new(None);
    let setup_serial = |name: &str, cli_cfg, device| -> anyhow::Result<_> {
        Ok(match cli_cfg {
            SerialConfigCli::Console => {
                if let Some(console_state) = console_state.borrow().as_ref() {
                    bail!("console already set by {}", console_state.device);
                }
                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
                let (serial_read, serial_write) = AsyncReadExt::split(serial);
                *console_state.borrow_mut() = Some(ConsoleState {
                    device,
                    input: Box::new(serial_write),
                });
                thread::Builder::new()
                    .name(name.to_owned())
                    .spawn(move || {
                        let _ = block_on(futures::io::copy(
                            serial_read,
                            &mut AllowStdIo::new(term::raw_stdout()),
                        ));
                    })
                    .unwrap();
                Some(config)
            }
            SerialConfigCli::Stderr => {
                let (config, serial) = serial_io::anonymous_serial_pair(&serial_driver)?;
                thread::Builder::new()
                    .name(name.to_owned())
                    .spawn(move || {
                        let _ = block_on(futures::io::copy(
                            serial,
                            &mut AllowStdIo::new(term::raw_stderr()),
                        ));
                    })
                    .unwrap();
                Some(config)
            }
            SerialConfigCli::None => None,
            SerialConfigCli::Pipe(path) => {
                Some(serial_io::bind_serial(&path).context("failed to bind serial")?)
            }
            SerialConfigCli::NewConsole(app) => {
                let path = console::random_console_path();
                let config =
                    serial_io::bind_serial(&path).context("failed to bind console serial")?;
                console::launch_console(app.as_deref(), &path)
                    .context("failed to launch console")?;

                Some(config)
            }
        })
    };

    // TODO: unify virtio serial handling and remove this.
    let setup_serial_virtio = |name, cli_cfg, device| -> anyhow::Result<_> {
        Ok(match cli_cfg {
            SerialConfigCli::Console => {
                if console_state.borrow().is_some() {
                    bail!("console already set");
                }
                let mut io = SerialIo::new().context("creating serial IO")?;
                io.spawn_copy_out(name, term::raw_stdout());
                *console_state.borrow_mut() = Some(ConsoleState {
                    device,
                    input: Box::new(PolledPipe::new(&serial_driver, io.input.unwrap())?),
                });
                Some(io.config)
            }
            SerialConfigCli::Stderr => {
                let mut io = SerialIo::new().context("creating serial IO")?;
                io.spawn_copy_out(name, term::raw_stderr());
                // Ensure there is no input so that the serial devices don't see
                // EOF and think the port is disconnected.
                io.config.input = None;
                Some(io.config)
            }
            SerialConfigCli::None => None,
            SerialConfigCli::Pipe(path) => {
                let mut io = SerialIo::new().context("creating serial IO")?;
                io.spawn_copy_listener(serial_driver.clone(), name, &path)
                    .with_context(|| format!("listening on pipe {}", path.display()))?
                    .detach();
                Some(io.config)
            }
            SerialConfigCli::NewConsole(app) => {
                let path = console::random_console_path();

                let mut io = SerialIo::new().context("creating serial IO")?;
                io.spawn_copy_listener(serial_driver.clone(), name, &path)
                    .with_context(|| format!("listening on pipe {}", path.display()))?
                    .detach();

                console::launch_console(app.as_deref(), &path)
                    .context("failed to launch console")?;
                Some(io.config)
            }
        })
    };

    let virtio_console = opt.virtio_console || opt.virtio_console_pci;
    let mut vmbus_devices = Vec::new();

    let serial0_cfg = setup_serial(
        "com1",
        opt.com1.clone().unwrap_or({
            if !virtio_console {
                SerialConfigCli::Console
            } else {
                SerialConfigCli::None
            }
        }),
        if cfg!(guest_arch = "x86_64") {
            "ttyS0"
        } else {
            "ttyAMA0"
        },
    )?;
    let serial1_cfg = setup_serial(
        "com2",
        opt.com2.clone().unwrap_or(SerialConfigCli::None),
        if cfg!(guest_arch = "x86_64") {
            "ttyS1"
        } else {
            "ttyAMA1"
        },
    )?;
    let serial2_cfg = setup_serial(
        "com3",
        opt.com3.clone().unwrap_or(SerialConfigCli::None),
        if cfg!(guest_arch = "x86_64") {
            "ttyS2"
        } else {
            "ttyAMA2"
        },
    )?;
    let serial3_cfg = setup_serial(
        "com4",
        opt.com4.clone().unwrap_or(SerialConfigCli::None),
        if cfg!(guest_arch = "x86_64") {
            "ttyS3"
        } else {
            "ttyAMA3"
        },
    )?;
    let virtio_serial_cfg = setup_serial_virtio(
        "virtio_serial",
        opt.virtio_serial.clone().unwrap_or({
            if virtio_console {
                SerialConfigCli::Console
            } else {
                SerialConfigCli::None
            }
        }),
        if opt.virtio_console_pci {
            "hvc1"
        } else {
            "hvc0"
        },
    )?;
    let with_vmbus_com1_serial = if let Some(vmbus_com1_cfg) = setup_serial(
        "vmbus_com1",
        opt.vmbus_com1_serial
            .clone()
            .unwrap_or(SerialConfigCli::None),
        "vmbus_com1",
    )? {
        vmbus_devices.push((
            DeviceVtl::Vtl2,
            VmbusSerialDeviceHandle {
                port: VmbusSerialPort::Com1,
                backend: vmbus_com1_cfg,
            }
            .into_resource(),
        ));
        true
    } else {
        false
    };
    let with_vmbus_com2_serial = if let Some(vmbus_com2_cfg) = setup_serial(
        "vmbus_com2",
        opt.vmbus_com2_serial
            .clone()
            .unwrap_or(SerialConfigCli::None),
        "vmbus_com2",
    )? {
        vmbus_devices.push((
            DeviceVtl::Vtl2,
            VmbusSerialDeviceHandle {
                port: VmbusSerialPort::Com2,
                backend: vmbus_com2_cfg,
            }
            .into_resource(),
        ));
        true
    } else {
        false
    };

    let mut resources = VmResources::default();
    let mut console_str = "";
    if let Some(ConsoleState { device, input }) = console_state.into_inner() {
        resources.console_in = Some(input);
        console_str = device;
    }

    if opt.shared_memory {
        tracing::warn!("--shared-memory/-M flag has no effect and will be removed");
    }

    const MAX_PROCESSOR_COUNT: u32 = 1024;

    if opt.processors == 0 || opt.processors > MAX_PROCESSOR_COUNT {
        bail!("invalid proc count: {}", opt.processors);
    }

    // Total SCSI channel count should not exceed the processor count
    // (at most, one channel per VP).
    if opt.scsi_sub_channels > (MAX_PROCESSOR_COUNT - 1) as u16 {
        bail!(
            "invalid SCSI sub-channel count: requested {}, max {}",
            opt.scsi_sub_channels,
            MAX_PROCESSOR_COUNT - 1
        );
    }

    let mut storage = storage_builder::StorageBuilder::new();
    for &cli_args::DiskCli {
        vtl,
        ref kind,
        read_only,
        is_dvd,
        underhill,
    } in &opt.disk
    {
        storage.add(
            vtl,
            underhill,
            storage_builder::DiskLocation::Scsi(None),
            kind,
            is_dvd,
            read_only,
        )?;
    }

    for &cli_args::IdeDiskCli {
        ref kind,
        read_only,
        channel,
        device,
        is_dvd,
    } in &opt.ide
    {
        storage.add(
            DeviceVtl::Vtl0,
            None,
            storage_builder::DiskLocation::Ide(channel, device),
            kind,
            is_dvd,
            read_only,
        )?;
    }

    for &cli_args::DiskCli {
        vtl,
        ref kind,
        read_only,
        is_dvd,
        underhill,
    } in &opt.nvme
    {
        storage.add(
            vtl,
            underhill,
            storage_builder::DiskLocation::Nvme(None),
            kind,
            is_dvd,
            read_only,
        )?;
    }

    let floppy_disks: Vec<_> = opt
        .floppy
        .iter()
        .map(|disk| -> anyhow::Result<_> {
            let &cli_args::FloppyDiskCli {
                ref kind,
                read_only,
            } = disk;
            Ok(FloppyDiskConfig {
                disk_type: disk_open(kind, read_only)?,
                read_only,
            })
        })
        .collect::<Result<Vec<_>, _>>()?;

    let mut mana_nics = [(); 3].map(|()| None);
    let mut underhill_nics = Vec::new();
    let mut vpci_devices = Vec::new();

    let mut nic_index = 0;
    for cli_cfg in &opt.net {
        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
        if cli_cfg.underhill {
            if !opt.no_alias_map {
                anyhow::bail!("must specify --no-alias-map to offer NICs to VTL2");
            }
            let mana = mana_nics[2].get_or_insert_with(|| {
                let vpci_instance_id = Guid::new_random();
                underhill_nics.push(vtl2_settings_proto::NicDeviceLegacy {
                    instance_id: vpci_instance_id.to_string(),
                    subordinate_instance_id: None,
                    max_sub_channels: None,
                });
                (vpci_instance_id, GdmaDeviceHandle { vports: Vec::new() })
            });
            mana.1.vports.push(VportDefinition {
                mac_address: vport.mac_address,
                endpoint: vport.endpoint,
            });
        } else {
            vmbus_devices.push(vport.into_netvsp_handle());
        }
    }

    if opt.nic {
        let nic_config = parse_endpoint(
            &NicConfigCli {
                vtl: DeviceVtl::Vtl0,
                endpoint: EndpointConfigCli::Consomme { cidr: None },
                max_queues: None,
                underhill: false,
            },
            &mut nic_index,
            &mut resources,
        )?;
        vmbus_devices.push(nic_config.into_netvsp_handle());
    }

    if opt.mcr {
        tracing::info!("Instantiating MCR controller");

        // Arbitrary but constant instance ID to be consistent across boots.
        const MCR_INSTANCE_ID: Guid = Guid::from_static_str("07effd8f-7501-426c-a947-d8345f39113d");

        vpci_devices.push(VpciDeviceConfig {
            vtl: DeviceVtl::Vtl0,
            instance_id: MCR_INSTANCE_ID,
            resource: mcr_resources::McrControllerHandle {
                instance_id: MCR_INSTANCE_ID,
            }
            .into_resource(),
        });
    }

    #[cfg(windows)]
    let mut kernel_vmnics = Vec::new();
    #[cfg(windows)]
    for (index, switch_id) in opt.kernel_vmnic.iter().enumerate() {
        // Pick a random MAC address.
        let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
        getrandom::getrandom(&mut mac_address[3..]).expect("rng failure");

        // Pick a fixed instance ID based on the index.
        const BASE_INSTANCE_ID: Guid =
            Guid::from_static_str("00000000-435d-11ee-9f59-00155d5016fc");
        let instance_id = Guid {
            data1: index as u32,
            ..BASE_INSTANCE_ID
        };

        let switch_id = if switch_id == "default" {
            DEFAULT_SWITCH
        } else {
            switch_id
        };
        let (port_id, port) = new_switch_port(switch_id)?;
        resources.switch_ports.push(port);

        kernel_vmnics.push(hvlite_defs::config::KernelVmNicConfig {
            instance_id,
            mac_address: mac_address.into(),
            switch_port_id: port_id,
        });
    }

    for vport in &opt.mana {
        let vport = parse_endpoint(vport, &mut nic_index, &mut resources)?;
        mana_nics[vport.vtl as usize]
            .get_or_insert_with(|| (Guid::new_random(), GdmaDeviceHandle { vports: Vec::new() }))
            .1
            .vports
            .push(VportDefinition {
                mac_address: vport.mac_address,
                endpoint: vport.endpoint,
            });
    }

    vpci_devices.extend(mana_nics.into_iter().enumerate().filter_map(|(vtl, nic)| {
        nic.map(|(instance_id, handle)| VpciDeviceConfig {
            vtl: match vtl {
                0 => DeviceVtl::Vtl0,
                1 => DeviceVtl::Vtl1,
                2 => DeviceVtl::Vtl2,
                _ => unreachable!(),
            },
            instance_id,
            resource: handle.into_resource(),
        })
    }));

    #[cfg(windows)]
    let vpci_resources: Vec<_> = opt
        .device
        .iter()
        .map(|path| -> anyhow::Result<_> {
            Ok(virt_whp::device::DeviceHandle(
                whp::VpciResource::new(
                    None,
                    Default::default(),
                    &whp::VpciResourceDescriptor::Sriov(path, 0, 0),
                )
                .with_context(|| format!("opening PCI device {}", path))?,
            ))
        })
        .collect::<Result<_, _>>()?;

    // Create a vmbusproxy handle if needed by any devices.
    #[cfg(windows)]
    let vmbusproxy_handle = if !kernel_vmnics.is_empty() {
        Some(vmbus_proxy::ProxyHandle::new().context("failed to open vmbusproxy handle")?)
    } else {
        None
    };

    let framebuffer = if opt.gfx || opt.vtl2_gfx || opt.vnc || opt.pcat {
        let vram = alloc_shared_memory(FRAMEBUFFER_SIZE)?;
        let (fb, fba) =
            framebuffer::framebuffer(vram, FRAMEBUFFER_SIZE, 0).context("creating framebuffer")?;
        resources.framebuffer_access = Some(fba);
        Some(fb)
    } else {
        None
    };

    let is_arm = cfg!(guest_arch = "aarch64");
    let is_x86 = cfg!(guest_arch = "x86_64");

    let load_mode;
    let with_hv;

    let any_serial_configured = serial0_cfg.is_some()
        || serial1_cfg.is_some()
        || serial2_cfg.is_some()
        || serial3_cfg.is_some();

    let has_com3 = serial2_cfg.is_some();

    let mut chipset = VmManifestBuilder::new(
        if opt.igvm.is_some() {
            BaseChipsetType::HclHost
        } else if opt.pcat {
            BaseChipsetType::HypervGen1
        } else if opt.uefi {
            BaseChipsetType::HypervGen2Uefi
        } else if opt.hv {
            BaseChipsetType::HyperVGen2LinuxDirect
        } else {
            BaseChipsetType::UnenlightenedLinuxDirect
        },
        if is_x86 {
            MachineArch::X86_64
        } else {
            MachineArch::Aarch64
        },
    );

    if framebuffer.is_some() {
        chipset = chipset.with_framebuffer();
    }
    if opt.guest_watchdog {
        chipset = chipset.with_guest_watchdog();
    }
    if any_serial_configured {
        chipset = chipset.with_serial([serial0_cfg, serial1_cfg, serial2_cfg, serial3_cfg]);
    }
    if opt.battery {
        let (tx, rx) = mesh::channel();
        tx.send(HostBatteryUpdate::default_present());
        chipset = chipset.with_battery(rx);
    }

    let VmChipsetResult {
        chipset,
        mut chipset_devices,
    } = chipset
        .build()
        .context("failed to build chipset configuration")?;

    if let Some(path) = &opt.igvm {
        let file = fs_err::File::open(path)
            .context("failed to open igvm file")?
            .into();
        let cmdline = opt.cmdline.join(" ");
        with_hv = true;

        load_mode = LoadMode::Igvm {
            file,
            cmdline,
            vtl2_base_address: opt.igvm_vtl2_relocation_type,
            com_serial: has_com3.then(|| SerialInformation {
                io_port: ComPort::Com3.io_port(),
                irq: ComPort::Com3.irq().into(),
            }),
        };
    } else if opt.pcat {
        // Emit a nice error early instead of complaining about missing firmware.
        if !is_x86 {
            anyhow::bail!("pcat not supported on this architecture");
        }
        with_hv = true;

        let firmware = hvlite_pcat_locator::find_pcat_bios(opt.pcat_firmware.as_deref())?;
        load_mode = LoadMode::Pcat {
            firmware,
            boot_order: opt
                .pcat_boot_order
                .map(|x| x.0)
                .unwrap_or(DEFAULT_PCAT_BOOT_ORDER),
        };
    } else if opt.uefi {
        use hvlite_defs::config::UefiConsoleMode;

        with_hv = true;

        let firmware = fs_err::File::open(
            (opt.uefi_firmware.0)
                .as_ref()
                .context("must provide uefi firmware when booting with uefi")?,
        )
        .context("failed to open uefi firmware")?;

        // TODO: It would be better to default memory protections to on, but currently Linux does not boot via UEFI due to what
        //       appears to be a GRUB memory protection fault. Memory protections are therefore only enabled if configured.
        load_mode = LoadMode::Uefi {
            firmware: firmware.into(),
            enable_debugging: opt.uefi_debug,
            enable_memory_protections: opt.uefi_enable_memory_protections,
            disable_frontpage: opt.disable_frontpage,
            enable_tpm: opt.tpm,
            enable_battery: opt.battery,
            enable_serial: any_serial_configured,
            enable_vpci_boot: false,
            uefi_console_mode: opt.uefi_console_mode.map(|m| match m {
                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
                UefiConsoleModeCli::Com1 => UefiConsoleMode::Com1,
                UefiConsoleModeCli::Com2 => UefiConsoleMode::Com2,
                UefiConsoleModeCli::None => UefiConsoleMode::None,
            }),
        };
    } else {
        // Linux Direct
        let mut cmdline = "panic=-1 debug".to_string();

        with_hv = opt.hv;
        if with_hv {
            cmdline += " pci=off";
        }

        if !console_str.is_empty() {
            let _ = write!(&mut cmdline, " console={}", console_str);
        }
        if opt.gfx {
            cmdline += " console=tty";
        }
        for extra in &opt.cmdline {
            let _ = write!(&mut cmdline, " {}", extra);
        }

        let kernel = fs_err::File::open(
            (opt.kernel.0)
                .as_ref()
                .context("must provide kernel when booting with linux direct")?,
        )
        .context("failed to open kernel")?;
        let initrd = (opt.initrd.0)
            .as_ref()
            .map(fs_err::File::open)
            .transpose()
            .context("failed to open initrd")?;

        let custom_dsdt = match &opt.custom_dsdt {
            Some(path) => {
                let mut v = Vec::new();
                fs_err::File::open(path)
                    .context("failed to open custom dsdt")?
                    .read_to_end(&mut v)
                    .context("failed to read custom dsdt")?;
                Some(v)
            }
            None => None,
        };

        load_mode = LoadMode::Linux {
            kernel: kernel.into(),
            initrd: initrd.map(Into::into),
            cmdline,
            custom_dsdt,
            enable_serial: any_serial_configured,
        };
    }

    let openhcl_vtl = if opt.vtl2 {
        DeviceVtl::Vtl2
    } else {
        DeviceVtl::Vtl0
    };

    if (opt.vtl2 || opt.get) && with_hv {
        let vtl2_settings = vtl2_settings_proto::Vtl2Settings {
            version: vtl2_settings_proto::vtl2_settings_base::Version::V1.into(),
            fixed: Some(Default::default()),
            dynamic: Some(vtl2_settings_proto::Vtl2SettingsDynamic {
                storage_controllers: storage.build_underhill(),
                nic_devices: underhill_nics,
            }),
            namespace_settings: Vec::default(),
        };

        let (send, guest_request_recv) = mesh::channel();
        resources.ged_rpc = Some(send);
        vmbus_devices.extend([
            (
                openhcl_vtl,
                get_resources::gel::GuestEmulationLogHandle.into_resource(),
            ),
            (
                openhcl_vtl,
                get_resources::ged::GuestEmulationDeviceHandle {
                    firmware: if opt.pcat {
                        get_resources::ged::GuestFirmwareConfig::Pcat {
                            boot_order: opt
                                .pcat_boot_order
                                .map_or(DEFAULT_PCAT_BOOT_ORDER, |x| x.0)
                                .map(|x| match x {
                                    hvlite_defs::config::PcatBootDevice::Floppy => {
                                        get_resources::ged::PcatBootDevice::Floppy
                                    }
                                    hvlite_defs::config::PcatBootDevice::HardDrive => {
                                        get_resources::ged::PcatBootDevice::HardDrive
                                    }
                                    hvlite_defs::config::PcatBootDevice::Optical => {
                                        get_resources::ged::PcatBootDevice::Optical
                                    }
                                    hvlite_defs::config::PcatBootDevice::Network => {
                                        get_resources::ged::PcatBootDevice::Network
                                    }
                                }),
                        }
                    } else {
                        use get_resources::ged::UefiConsoleMode;

                        get_resources::ged::GuestFirmwareConfig::Uefi {
                            enable_vpci_boot: storage.has_vtl0_nvme(),
                            firmware_debug: opt.uefi_debug,
                            disable_frontpage: opt.disable_frontpage,
                            console_mode: match opt.uefi_console_mode.unwrap_or(UefiConsoleModeCli::Default) {
                                UefiConsoleModeCli::Default => UefiConsoleMode::Default,
                                UefiConsoleModeCli::Com1 => UefiConsoleMode::COM1,
                                UefiConsoleModeCli::Com2 => UefiConsoleMode::COM2,
                                UefiConsoleModeCli::None => UefiConsoleMode::None,
                            },
                        }
                    },
                    com1: with_vmbus_com1_serial,
                    com2: with_vmbus_com2_serial,
                    vtl2_settings: Some(prost::Message::encode_to_vec(&vtl2_settings)),
                    vmbus_redirection: opt.vmbus_redirect,
                    framebuffer: opt
                        .vtl2_gfx
                        .then(|| SharedFramebufferHandle.into_resource()),
                    guest_request_recv,
                    enable_tpm: opt.tpm,
                    firmware_event_send: None,
                    secure_boot_enabled: opt.secure_boot,
                    secure_boot_template: match opt.secure_boot_template {
                        Some(SecureBootTemplateCli::Windows) => {
                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftWindows
                        },
                        Some(SecureBootTemplateCli::UefiCa) => {
                            get_resources::ged::GuestSecureBootTemplateType::MicrosoftUefiCertificateAuthoritiy
                        }
                        None => {
                            get_resources::ged::GuestSecureBootTemplateType::None
                        },
                    },
                    enable_battery: opt.battery,
                }
                .into_resource(),
            ),
        ]);
    }

    if opt.tpm && !opt.vtl2 {
        let register_layout = if cfg!(guest_arch = "x86_64") {
            TpmRegisterLayout::IoPort
        } else {
            TpmRegisterLayout::Mmio
        };

        let (ppi_store, nvram_store) = if opt.vmgs_file.is_some() {
            (
                VmgsFileHandle::new(vmgs_format::FileId::TPM_PPI, true).into_resource(),
                VmgsFileHandle::new(vmgs_format::FileId::TPM_NVRAM, true).into_resource(),
            )
        } else {
            (
                EphemeralNonVolatileStoreHandle.into_resource(),
                EphemeralNonVolatileStoreHandle.into_resource(),
            )
        };

        chipset_devices.push(ChipsetDeviceHandle {
            name: "tpm".to_string(),
            resource: TpmDeviceHandle {
                ppi_store,
                nvram_store,
                refresh_tpm_seeds: false,
                get_attestation_report: None,
                request_ak_cert: None,
                register_layout,
                guest_secret_key: None,
            }
            .into_resource(),
        });
    }

    let custom_uefi_vars = {
        use firmware_uefi_custom_vars::CustomVars;

        // load base vars from specified template, or use an empty set of base
        // vars if none was specified.
        let base_vars = match opt.secure_boot_template {
            Some(template) => {
                if is_x86 {
                    match template {
                        SecureBootTemplateCli::Windows => {
                            hyperv_secure_boot_templates::x64::microsoft_windows()
                        }
                        SecureBootTemplateCli::UefiCa => {
                            hyperv_secure_boot_templates::x64::microsoft_uefi_ca()
                        }
                    }
                } else if is_arm {
                    match template {
                        SecureBootTemplateCli::Windows => {
                            hyperv_secure_boot_templates::aarch64::microsoft_windows()
                        }
                        SecureBootTemplateCli::UefiCa => {
                            hyperv_secure_boot_templates::aarch64::microsoft_uefi_ca()
                        }
                    }
                } else {
                    anyhow::bail!("no secure boot template for current guest_arch")
                }
            }
            None => CustomVars::default(),
        };

        // TODO: fallback to VMGS read if no command line flag was given

        let custom_uefi_json_data = match &opt.custom_uefi_json {
            Some(file) => Some(fs_err::read(file).context("opening custom uefi json file")?),
            None => None,
        };

        // obtain the final custom uefi vars by applying the delta onto the base vars
        match custom_uefi_json_data {
            Some(data) => {
                let delta = hyperv_uefi_custom_vars_json::load_delta_from_json(&data)?;
                base_vars.apply_delta(delta)?
            }
            None => base_vars,
        }
    };

    let vga_firmware = if opt.pcat {
        Some(hvlite_pcat_locator::find_svga_bios(
            opt.vga_firmware.as_deref(),
        )?)
    } else {
        None
    };

    if opt.gfx {
        vmbus_devices.extend([
            (
                DeviceVtl::Vtl0,
                SynthVideoHandle {
                    framebuffer: SharedFramebufferHandle.into_resource(),
                }
                .into_resource(),
            ),
            (
                DeviceVtl::Vtl0,
                SynthKeyboardHandle {
                    source: MultiplexedInputHandle {
                        // Save 0 for PS/2
                        elevation: 1,
                    }
                    .into_resource(),
                }
                .into_resource(),
            ),
            (
                DeviceVtl::Vtl0,
                SynthMouseHandle {
                    source: MultiplexedInputHandle {
                        // Save 0 for PS/2
                        elevation: 1,
                    }
                    .into_resource(),
                }
                .into_resource(),
            ),
        ]);
    }

    let vsock_listener = |path: Option<&str>| -> anyhow::Result<_> {
        if let Some(path) = path {
            cleanup_socket(path.as_ref());
            let listener = unix_socket::UnixListener::bind(path)
                .with_context(|| format!("failed to bind to hybrid vsock path: {}", path))?;
            Ok(Some(listener))
        } else {
            Ok(None)
        }
    };

    let vtl0_vsock_listener = vsock_listener(opt.vsock_path.as_deref())?;
    let vtl2_vsock_listener = vsock_listener(opt.vtl2_vsock_path.as_deref())?;

    // If VTL2 is enabled, and we are not in VTL2 self allocate mode, provide an
    // mmio gap for VTL2.
    let mmio_gaps = if opt.vtl2
        && !matches!(
            opt.igvm_vtl2_relocation_type,
            Vtl2BaseAddressType::Vtl2Allocate { .. },
        ) {
        DEFAULT_MMIO_GAPS_WITH_VTL2.into()
    } else {
        DEFAULT_MMIO_GAPS.into()
    };

    if let Some(path) = &opt.underhill_dump_path {
        let (resource, task) = spawn_dump_handler(&spawner, path.clone(), None);
        task.detach();
        vmbus_devices.push((openhcl_vtl, resource));
    }

    #[cfg(guest_arch = "aarch64")]
    let topology_arch = hvlite_defs::config::Aarch64TopologyConfig {
        // TODO: allow this to be configured from the command line
        gic_config: None,
    };
    #[cfg(guest_arch = "x86_64")]
    let topology_arch = hvlite_defs::config::X86TopologyConfig {
        apic_id_offset: opt.apic_id_offset,
        x2apic: opt.x2apic,
    };

    let with_isolation = if let Some(isolation) = &opt.isolation {
        // TODO: For now, isolation is only supported with VTL2.
        if !opt.vtl2 {
            anyhow::bail!("isolation is only currently supported with vtl2");
        }

        // TODO: Alias map support is not yet implement with isolation.
        if !opt.no_alias_map {
            anyhow::bail!("alias map not supported with isolation");
        }

        match isolation {
            cli_args::IsolationCli::Vbs => Some(hvlite_defs::config::IsolationType::Vbs),
        }
    } else {
        None
    };

    if with_hv {
        let (send, recv) = mesh::channel();
        resources.shutdown_ic = Some(send);
        vmbus_devices.push((
            DeviceVtl::Vtl0,
            hyperv_ic_resources::shutdown::ShutdownIcHandle { recv }.into_resource(),
        ));
    }

    if let Some(hive_path) = &opt.imc {
        let file = fs_err::File::open(hive_path).context("failed to open imc hive")?;
        vmbus_devices.push((
            DeviceVtl::Vtl0,
            vmbfs_resources::VmbfsImcDeviceHandle { file: file.into() }.into_resource(),
        ));
    }

    let mut virtio_devices = Vec::new();
    for cli_cfg in &opt.virtio_net {
        if cli_cfg.underhill {
            anyhow::bail!("use --net uh:[...] to add underhill NICs")
        }
        let vport = parse_endpoint(cli_cfg, &mut nic_index, &mut resources)?;
        virtio_devices.push((
            VirtioBus::Auto,
            virtio_resources::net::VirtioNetHandle {
                max_queues: vport.max_queues,
                mac_address: vport.mac_address,
                endpoint: vport.endpoint,
            }
            .into_resource(),
        ));
    }

    for (tag, root_path) in &opt.virtio_fs {
        virtio_devices.push((
            opt.virtio_fs_bus,
            virtio_resources::fs::VirtioFsHandle {
                tag: tag.clone(),
                fs: virtio_resources::fs::VirtioFsBackend::HostFs {
                    root_path: root_path.clone(),
                },
            }
            .into_resource(),
        ));
    }

    for (tag, root_path) in &opt.virtio_fs_shmem {
        virtio_devices.push((
            opt.virtio_fs_bus,
            virtio_resources::fs::VirtioFsHandle {
                tag: tag.clone(),
                fs: virtio_resources::fs::VirtioFsBackend::SectionFs {
                    root_path: root_path.clone(),
                },
            }
            .into_resource(),
        ));
    }

    for (tag, root_path) in &opt.virtio_9p {
        virtio_devices.push((
            VirtioBus::Auto,
            virtio_resources::p9::VirtioPlan9Handle {
                tag: tag.clone(),
                root_path: root_path.clone(),
                debug: opt.virtio_9p_debug,
            }
            .into_resource(),
        ));
    }

    if let Some(path) = &opt.virtio_pmem {
        virtio_devices.push((
            VirtioBus::Auto,
            virtio_resources::pmem::VirtioPmemHandle { path: path.clone() }.into_resource(),
        ));
    }

    let mut cfg = Config {
        chipset,
        load_mode,
        floppy_disks,
        vpci_devices,
        ide_disks: Vec::new(),
        memory: MemoryConfig {
            mem_size: opt.memory,
            mmio_gaps,
            prefetch_memory: opt.prefetch,
        },
        processor_topology: ProcessorTopologyConfig {
            proc_count: opt.processors,
            vps_per_socket: opt.vps_per_socket,
            enable_smt: match opt.smt {
                cli_args::SmtConfigCli::Auto => None,
                cli_args::SmtConfigCli::Force => Some(true),
                cli_args::SmtConfigCli::Off => Some(false),
            },
            arch: topology_arch,
        },
        hypervisor: HypervisorConfig {
            with_hv,
            with_vtl2: opt.vtl2.then_some(Vtl2Config {
                vtl0_alias_map: !opt.no_alias_map,
                late_map_vtl0_memory: match opt.late_map_vtl0_policy {
                    cli_args::Vtl0LateMapPolicyCli::Off => None,
                    cli_args::Vtl0LateMapPolicyCli::Log => Some(LateMapVtl0MemoryPolicy::Log),
                    cli_args::Vtl0LateMapPolicyCli::Halt => Some(LateMapVtl0MemoryPolicy::Halt),
                    cli_args::Vtl0LateMapPolicyCli::Exception => {
                        Some(LateMapVtl0MemoryPolicy::InjectException)
                    }
                },
                vtl2_emulates_apic: opt.vtl2_emulates_apic,
            }),
            with_isolation,
            user_mode_hv_enlightenments: opt.no_enlightenments,
            user_mode_apic: opt.user_mode_apic,
        },
        #[cfg(windows)]
        kernel_vmnics,
        input: mesh::MpscReceiver::new(),
        framebuffer,
        vga_firmware,
        vtl2_gfx: opt.vtl2_gfx,
        virtio_console_pci: opt.virtio_console_pci,
        virtio_serial: virtio_serial_cfg,
        virtio_devices,
        vmbus: with_hv.then_some(VmbusConfig {
            vsock_listener: vtl0_vsock_listener,
            vsock_path: opt.vsock_path.clone(),
            vtl2_redirect: opt.vmbus_redirect,
            vmbus_max_version: opt.vmbus_max_version,
            #[cfg(windows)]
            vmbusproxy_handle,
        }),
        vtl2_vmbus: (with_hv && opt.vtl2).then_some(VmbusConfig {
            vsock_listener: vtl2_vsock_listener,
            vsock_path: opt.vtl2_vsock_path.clone(),
            ..Default::default()
        }),
        vmbus_devices,
        chipset_devices,
        #[cfg(windows)]
        vpci_resources,
        vmgs_file: opt
            .vmgs_file
            .as_ref()
            .map(|p| p.to_string_lossy().into_owned()),
        secure_boot_enabled: opt.secure_boot,
        custom_uefi_vars,
        firmware_event_send: None,
        debugger_rpc: None,
        generation_id_recv: None,
    };

    storage.build_config(&mut cfg, &mut resources, opt.scsi_sub_channels)?;
    Ok((cfg, resources))
}

// Tries to remove `path` if it is confirmed to be a Unix socket.
fn cleanup_socket(path: &Path) {
    #[cfg(windows)]
    let is_socket = pal::windows::fs::is_unix_socket(path).unwrap_or(false);
    #[cfg(not(windows))]
    let is_socket = path.metadata().map_or(false, |meta| {
        std::os::unix::fs::FileTypeExt::is_socket(&meta.file_type())
    });

    if is_socket {
        let _ = std::fs::remove_file(path);
    }
}

#[cfg(windows)]
const DEFAULT_SWITCH: &str = "C08CB7B8-9B3C-408E-8E30-5E16A3AEB444";

#[cfg(windows)]
fn new_switch_port(
    switch_id: &str,
) -> anyhow::Result<(
    hvlite_defs::config::SwitchPortId,
    vmswitch::kernel::SwitchPort,
)> {
    let id = vmswitch::kernel::SwitchPortId {
        switch: switch_id.parse().context("invalid switch id")?,
        port: Guid::new_random(),
    };
    let _ = vmswitch::hcn::Network::open(&id.switch)
        .with_context(|| format!("could not find switch {}", id.switch))?;

    let port = vmswitch::kernel::SwitchPort::new(&id).context("failed to create switch port")?;

    let id = hvlite_defs::config::SwitchPortId {
        switch: id.switch,
        port: id.port,
    };
    Ok((id, port))
}

fn parse_endpoint(
    cli_cfg: &NicConfigCli,
    index: &mut usize,
    resources: &mut VmResources,
) -> anyhow::Result<NicConfig> {
    let _ = resources;
    let endpoint = match &cli_cfg.endpoint {
        EndpointConfigCli::Consomme { cidr } => {
            net_backend_resources::consomme::ConsommeHandle { cidr: cidr.clone() }.into_resource()
        }
        EndpointConfigCli::None => net_backend_resources::null::NullHandle.into_resource(),
        EndpointConfigCli::Dio { id } => {
            #[cfg(windows)]
            {
                let (port_id, port) = new_switch_port(id.as_deref().unwrap_or(DEFAULT_SWITCH))?;
                resources.switch_ports.push(port);
                net_backend_resources::dio::WindowsDirectIoHandle {
                    switch_port_id: net_backend_resources::dio::SwitchPortId {
                        switch: port_id.switch,
                        port: port_id.port,
                    },
                }
                .into_resource()
            }

            #[cfg(not(windows))]
            {
                let _ = id;
                bail!("cannot use dio on non-windows platforms")
            }
        }
        EndpointConfigCli::Tap { name } => {
            net_backend_resources::tap::TapHandle { name: name.clone() }.into_resource()
        }
    };

    // Pick a random MAC address.
    let mut mac_address = [0x00, 0x15, 0x5D, 0, 0, 0];
    getrandom::getrandom(&mut mac_address[3..]).expect("rng failure");

    // Pick a fixed instance ID based on the index.
    const BASE_INSTANCE_ID: Guid = Guid::from_static_str("00000000-da43-11ed-936a-00155d6db52f");
    let instance_id = Guid {
        data1: *index as u32,
        ..BASE_INSTANCE_ID
    };
    *index += 1;

    Ok(NicConfig {
        vtl: cli_cfg.vtl,
        instance_id,
        endpoint,
        mac_address: mac_address.into(),
        max_queues: cli_cfg.max_queues,
    })
}

#[derive(Debug)]
struct NicConfig {
    vtl: DeviceVtl,
    instance_id: Guid,
    mac_address: MacAddress,
    endpoint: Resource<NetEndpointHandleKind>,
    max_queues: Option<u16>,
}

impl NicConfig {
    fn into_netvsp_handle(self) -> (DeviceVtl, Resource<VmbusDeviceHandleKind>) {
        (
            self.vtl,
            netvsp_resources::NetvspHandle {
                instance_id: self.instance_id,
                mac_address: self.mac_address,
                endpoint: self.endpoint,
                max_queues: self.max_queues,
            }
            .into_resource(),
        )
    }
}

fn disk_open(disk_cli: &DiskCliKind, read_only: bool) -> anyhow::Result<Resource<DiskHandleKind>> {
    let disk_type = match disk_cli {
        &DiskCliKind::Memory(len) => Resource::new(disk_backend_resources::RamDiskHandle { len }),
        DiskCliKind::File(path) => open_disk_type(path, read_only)
            .with_context(|| format!("failed to open {}", path.display()))?,
        DiskCliKind::Blob { kind, url } => Resource::new(disk_backend_resources::BlobDiskHandle {
            url: url.to_owned(),
            format: match kind {
                cli_args::BlobKind::Flat => disk_backend_resources::BlobDiskFormat::Flat,
                cli_args::BlobKind::Vhd1 => disk_backend_resources::BlobDiskFormat::FixedVhd1,
            },
        }),
        DiskCliKind::MemoryDiff(inner) => {
            Resource::new(disk_backend_resources::RamDiffDiskHandle {
                lower: disk_open(inner, true)?,
            })
        }
        DiskCliKind::PersistentReservationsWrapper(inner) => Resource::new(
            disk_backend_resources::DiskWithReservationsHandle(disk_open(inner, read_only)?),
        ),
    };

    Ok(disk_type)
}

fn do_main() -> anyhow::Result<()> {
    #[cfg(windows)]
    pal::windows::disable_hard_error_dialog();

    tracing_init::enable_tracing()?;

    // Try to run as a worker host.
    // On success the worker runs to completion and then exits the process (does
    // not return). Any worker host setup errors are return and bubbled up.
    meshworker::run_vmm_mesh_host()?;

    let opt = Options::parse();
    if let Some(path) = &opt.write_saved_state_proto {
        mesh::payload::protofile::DescriptorWriter::new(vmcore::save_restore::saved_state_roots())
            .write_to_path(path)
            .context("failed to write protobuf descriptors")?;
        return Ok(());
    }

    if let Some(path) = opt.relay_console_path {
        return console::relay_console(&path);
    }

    if let Some(path) = opt.ttrpc.as_ref().or(opt.grpc.as_ref()) {
        block_on(async {
            let _ = std::fs::remove_file(path);
            let listener =
                unix_socket::UnixListener::bind(path).context("failed to bind to socket")?;

            let transport = if opt.ttrpc.is_some() {
                ttrpc::RpcTransport::Ttrpc
            } else {
                ttrpc::RpcTransport::Grpc
            };

            // This is a local launch
            let mut handle = launch_local_worker::<TtrpcWorker>(ttrpc::Parameters {
                listener,
                transport,
            })
            .await?;

            tracing::info!(%transport, path = %path.display(), "listening");

            // Signal the the parent process that the server is ready.
            pal::close_stdout().context("failed to close stdout")?;

            handle.join().await?;

            Ok(())
        })
    } else {
        DefaultPool::run_with(|driver| async move {
            let mesh = VmmMesh::new(&driver, opt.single_process)?;
            let result = run_control(&driver, &mesh, opt).await;
            mesh.shutdown().await;
            result
        })
    }
}

fn maybe_with_radix_u64(s: &str) -> Result<u64, String> {
    let (radix, prefix_len) = if s.starts_with("0x") || s.starts_with("0X") {
        (16, 2)
    } else if s.starts_with("0o") || s.starts_with("0O") {
        (8, 2)
    } else if s.starts_with("0b") || s.starts_with("0B") {
        (2, 2)
    } else {
        (10, 0)
    };

    u64::from_str_radix(&s[prefix_len..], radix).map_err(|e| format!("{e}"))
}

#[derive(Parser)]
#[clap(
    disable_help_flag = true,
    disable_version_flag = true,
    no_binary_name = true,
    help_template("{subcommands}")
)]
enum InteractiveCommand {
    /// Restart the VM worker (experimental).
    ///
    /// This restarts the VM worker while preserving state.
    #[clap(visible_alias = "R")]
    Restart,

    /// Inject an NMI.
    #[clap(visible_alias = "n")]
    Nmi,

    /// Pause the VM.
    #[clap(visible_alias = "p")]
    Pause,

    /// Resume the VM.
    #[clap(visible_alias = "r")]
    Resume,

    /// Do a pulsed save restore (pause, save, reset, restore, resume) to the VM.
    #[clap(visible_alias = "psr")]
    PulseSaveRestore,

    /// Schedule a pulsed save restore (pause, save, reset, restore, resume) to the VM.
    #[clap(visible_alias = "spsr")]
    SchedulePulseSaveRestore {
        /// The interval between pulse save restore operations in seconds.
        /// None or 0 means any previous scheduled pulse save restores will be cleared.
        interval: Option<u64>,
    },

    /// Hot add a disk.
    #[clap(visible_alias = "d")]
    AddDisk {
        #[clap(long = "ro")]
        read_only: bool,
        #[clap(long = "dvd")]
        is_dvd: bool,
        #[clap(long, default_value_t)]
        target: u8,
        #[clap(long, default_value_t)]
        path: u8,
        #[clap(long, default_value_t)]
        lun: u8,
        #[clap(long)]
        ram: Option<u64>,
        file_path: Option<PathBuf>,
    },

    /// Hot remove a disk.
    #[clap(visible_alias = "D")]
    RmDisk {
        #[clap(long)]
        target: u8,
        #[clap(long)]
        path: u8,
        #[clap(long)]
        lun: u8,
    },

    /// Inspect program state.
    #[clap(visible_alias = "x")]
    Inspect {
        /// Enumerate state recursively.
        #[clap(short, long)]
        recursive: bool,
        /// The recursive depth limit.
        #[clap(short, long, requires("recursive"))]
        limit: Option<usize>,
        /// Target the paravisor.
        #[clap(short = 'v', long)]
        paravisor: bool,
        /// The element path to inspect.
        element: Option<String>,
        /// Update the path with a new value.
        #[clap(short, long, conflicts_with("recursive"))]
        update: Option<String>,
    },

    /// Restart the VNC worker.
    #[clap(visible_alias = "V")]
    RestartVnc,

    /// Start an hvsocket terminal window.
    #[clap(visible_alias = "v")]
    Hvsock {
        /// the terminal emulator to run (defaults to conhost.exe or xterm)
        #[clap(short, long)]
        term: Option<String>,
        /// the vsock port to connect to
        port: u32,
    },

    /// Quit the program.
    #[clap(visible_alias = "q")]
    Quit,

    /// Write input to the VM console.
    ///
    /// This will write each input parameter to the console's associated serial
    /// port, separated by spaces.
    #[clap(visible_alias = "i")]
    Input { data: Vec<String> },

    /// Switch to input mode.
    ///
    /// Once in input mode, Ctrl-Q returns to command mode.
    #[clap(visible_alias = "I")]
    InputMode,

    /// Reset the VM.
    Reset,

    /// Send a request to the VM to shut it down.
    Shutdown {
        /// Reboot the VM instead of powering it off.
        #[clap(long, short = 'r')]
        reboot: bool,
        /// Hibernate the VM instead of powering it off.
        #[clap(long, short = 'h', conflicts_with = "reboot")]
        hibernate: bool,
        /// Tell the guest to force the power state transition.
        #[clap(long, short = 'f')]
        force: bool,
    },

    /// Clears the current halt condition, resuming the VPs if the VM is
    /// running.
    #[clap(visible_alias = "ch")]
    ClearHalt,

    /// Update the image in VTL2.
    ServiceVtl2 {
        /// Just restart the user-mode paravisor process, not the full
        /// firmware.
        #[clap(long, short = 'u')]
        user_mode_only: bool,
        /// The path to the new IGVM file. If missing, use the originally
        /// configured path.
        #[clap(long, conflicts_with("user_mode_only"))]
        igvm: Option<PathBuf>,
    },

    /// Read guest memory
    ReadMemory {
        /// Guest physical address to start at.
        #[clap(value_parser=maybe_with_radix_u64)]
        gpa: u64,
        /// How many bytes to dump.
        #[clap(value_parser=maybe_with_radix_u64)]
        size: u64,
        /// File to save the data to. If omitted,
        /// the data will be presented as a hex dump.
        #[clap(long, short = 'f')]
        file: Option<PathBuf>,
    },

    /// Write guest memory
    WriteMemory {
        /// Guest physical address to start at
        #[clap(value_parser=maybe_with_radix_u64)]
        gpa: u64,
        /// Hex string encoding data, with no `0x` radix.
        /// If omitted, the source file must be specified.
        hex: Option<String>,
        /// File to write the data from.
        #[clap(long, short = 'f')]
        file: Option<PathBuf>,
    },

    /// Inject an artificial panic into HvLite
    Panic,
}

struct CommandParser {
    app: clap::Command,
}

impl CommandParser {
    fn new() -> Self {
        // Update the help template for each subcommand.
        let mut app = InteractiveCommand::command();
        for sc in app.get_subcommands_mut() {
            *sc = sc
                .clone()
                .help_template("{about-with-newline}\n{usage-heading}\n    {usage}\n\n{all-args}");
        }
        Self { app }
    }

    fn parse(&mut self, line: &str) -> clap::error::Result<InteractiveCommand> {
        let args = shell_words::split(line)
            .map_err(|err| self.app.error(clap::error::ErrorKind::ValueValidation, err))?;
        let matches = self.app.try_get_matches_from_mut(args)?;
        InteractiveCommand::from_arg_matches(&matches).map_err(|err| err.format(&mut self.app))
    }
}

fn new_hvsock_service_id(port: u32) -> Guid {
    // This GUID is an embedding of the AF_VSOCK port into an
    // AF_HYPERV service ID.
    Guid {
        data1: port,
        .."00000000-facb-11e6-bd58-64006a7986d3".parse().unwrap()
    }
}

async fn run_control(driver: &DefaultDriver, mesh: &VmmMesh, opt: Options) -> anyhow::Result<()> {
    let (mut vm_config, mut resources) = vm_config_from_command_line(driver, &opt)?;

    let mut vnc_worker = None;
    if opt.gfx || opt.vnc {
        let listener = TcpListener::bind(format!("127.0.0.1:{}", opt.vnc_port))
            .with_context(|| format!("binding to VNC port {}", opt.vnc_port))?;

        let input_send = vm_config.input.sender();
        let framebuffer = resources.framebuffer_access.expect("synth video enabled");

        let vnc_host = mesh
            .make_host("vnc", None)
            .await
            .context("spawning vnc process failed")?;

        vnc_worker = Some(
            vnc_host
                .launch_worker(
                    vnc_worker_defs::VNC_WORKER_TCP,
                    VncParameters {
                        listener,
                        framebuffer,
                        input_send,
                    },
                )
                .await?,
        )
    }

    // spin up the debug worker
    let gdb_worker = if let Some(port) = opt.gdb {
        let listener = TcpListener::bind(format!("127.0.0.1:{}", port))
            .with_context(|| format!("binding to gdb port {}", port))?;

        let (req_tx, req_rx) = mesh::channel();
        vm_config.debugger_rpc = Some(req_rx);

        let gdb_host = mesh
            .make_host("gdb", None)
            .await
            .context("spawning gdbstub process failed")?;

        Some(
            gdb_host
                .launch_worker(
                    debug_worker_defs::DEBUGGER_WORKER,
                    debug_worker_defs::DebuggerParameters {
                        listener,
                        req_chan: req_tx,
                        vp_count: vm_config.processor_topology.proc_count,
                    },
                )
                .await
                .context("failed to launch gdbstub worker")?,
        )
    } else {
        None
    };

    // spin up the VM
    let (vm_rpc, rpc_recv) = mesh::channel();
    let vm_rpc = Arc::new(vm_rpc);
    let (notify_send, notify_recv) = mesh::channel();
    let mut vm_worker = {
        let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;

        let params = VmWorkerParameters {
            hypervisor: opt.hypervisor,
            cfg: vm_config,
            saved_state: None,
            rpc: rpc_recv,
            notify: notify_send,
        };
        vm_host
            .launch_worker(VM_WORKER, params)
            .await
            .context("failed to launch vm worker")?
    };

    if !opt.paused {
        vm_rpc.call(VmRpc::Resume, ()).await?;
    }

    let mut diag_inspector = DiagInspector::new(
        driver.clone(),
        vm_rpc.clone(),
        if opt.vtl2 {
            DeviceVtl::Vtl2
        } else {
            DeviceVtl::Vtl0
        },
    );

    let (console_command_send, console_command_recv) = mesh::channel();
    let (inspect_completion_engine_send, inspect_completion_engine_recv) = mesh::channel();

    let mut console_in = resources.console_in;
    thread::Builder::new()
        .name("stdio-thread".to_string())
        .spawn(move || {
            // install panic hook to restore cooked terminal (linux)
            #[cfg(unix)]
            if io::stderr().is_terminal() {
                term::revert_terminal_on_panic()
            }

            let mut rl = rustyline::Editor::<
                interactive_console::HvLiteRustylineEditor,
                rustyline::history::FileHistory,
            >::with_config(
                rustyline::Config::builder()
                    .completion_type(rustyline::CompletionType::List)
                    .build(),
            )
            .unwrap();

            rl.set_helper(Some(interactive_console::HvLiteRustylineEditor {
                hvlite_inspect_req: Arc::new(inspect_completion_engine_send),
            }));

            let history_file = {
                const HISTORY_FILE: &str = ".hvlite_history";

                // using a `None` to kick off the `.or()` chain in order to make
                // it a bit easier to visually inspect the fallback chain.
                let history_folder = None
                    .or_else(dirs::state_dir)
                    .or_else(dirs::data_local_dir)
                    .map(|path| path.join("hvlite"));

                if let Some(history_folder) = history_folder {
                    if let Err(err) = std::fs::create_dir_all(&history_folder) {
                        tracing::warn!(
                            error = &err as &dyn std::error::Error,
                            "could not create directory: {}",
                            history_folder.display()
                        )
                    }

                    Some(history_folder.join(HISTORY_FILE))
                } else {
                    None
                }
            };

            if let Some(history_file) = &history_file {
                tracing::info!("restoring history from {}", history_file.display());
                if rl.load_history(history_file).is_err() {
                    tracing::info!("could not find existing {}", history_file.display());
                }
            }

            // Enable Ctrl-Backspace to delete the current word.
            rl.bind_sequence(
                rustyline::KeyEvent::new('\x08', rustyline::Modifiers::CTRL),
                rustyline::Cmd::Kill(rustyline::Movement::BackwardWord(1, rustyline::Word::Emacs)),
            );

            let mut parser = CommandParser::new();

            let mut stdin = io::stdin();
            loop {
                // Raw console text until Ctrl-Q.
                term::set_raw_console(true);

                if let Some(input) = console_in.as_mut() {
                    let mut buf = [0; 32];
                    loop {
                        let n = stdin.read(&mut buf).unwrap();
                        let mut b = &buf[..n];
                        let stop = if let Some(ctrlq) = b.iter().position(|x| *x == 0x11) {
                            b = &b[..ctrlq];
                            true
                        } else {
                            false
                        };
                        block_on(input.as_mut().write_all(b)).expect("BUGBUG");
                        if stop {
                            break;
                        }
                    }
                }

                term::set_raw_console(false);

                loop {
                    let line = rl.readline("openvmm> ");
                    if line.is_err() {
                        break;
                    }
                    let line = line.unwrap();
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    if let Err(err) = rl.add_history_entry(&line) {
                        tracing::warn!(
                            err = &err as &dyn std::error::Error,
                            "error adding to .hvlite_history"
                        )
                    }

                    match parser.parse(trimmed) {
                        Ok(cmd) => match cmd {
                            InteractiveCommand::Input { data } => {
                                let mut data = data.join(" ");
                                data.push('\n');
                                if let Some(input) = console_in.as_mut() {
                                    block_on(input.write_all(data.as_bytes())).expect("BUGBUG");
                                }
                            }
                            InteractiveCommand::InputMode => break,
                            cmd => {
                                // Send the command to the main thread for processing.
                                let (processing_done_send, processing_done_recv) =
                                    mesh::oneshot::<()>();
                                console_command_send.send((cmd, processing_done_send));
                                let _ = block_on(processing_done_recv);
                            }
                        },
                        Err(err) => {
                            err.print().unwrap();
                        }
                    }

                    if let Some(history_file) = &history_file {
                        rl.append_history(history_file).unwrap();
                    }
                }
            }
        })
        .unwrap();

    let mut state_change_task = None::<Task<Result<StateChange, RecvError>>>;
    let mut pulse_save_restore_interval: Option<Duration> = None;
    let mut pending_shutdown = None;

    enum StateChange {
        Pause(bool),
        Resume(bool),
        Reset(Result<(), RemoteError>),
        PulseSaveRestore(Result<(), PulseSaveRestoreError>),
    }

    enum Event {
        Command((InteractiveCommand, mesh::OneshotSender<()>)),
        InspectRequestFromCompletionEngine(
            (InspectTarget, String, mesh::OneshotSender<inspect::Node>),
        ),
        Quit,
        Halt(vmm_core_defs::HaltReason),
        PulseSaveRestore,
        Worker(WorkerEvent),
        VncWorker(WorkerEvent),
        StateChange(Result<StateChange, RecvError>),
        ShutdownResult(Result<hyperv_ic_resources::shutdown::ShutdownResult, RecvError>),
    }

    let mut console_command_recv = console_command_recv
        .map(Event::Command)
        .chain(futures::stream::repeat_with(|| Event::Quit));

    let mut notify_recv = notify_recv.map(Event::Halt);

    let mut inspect_completion_engine_recv =
        inspect_completion_engine_recv.map(Event::InspectRequestFromCompletionEngine);

    let mut quit = false;
    loop {
        let event = {
            let pulse_save_restore = pin!(async {
                match pulse_save_restore_interval {
                    Some(wait) => {
                        PolledTimer::new(driver).sleep(wait).await;
                        Event::PulseSaveRestore
                    }
                    None => pending().await,
                }
            });

            let vm = (&mut vm_worker).map(Event::Worker);
            let vnc = futures::stream::iter(vnc_worker.as_mut())
                .flatten()
                .map(Event::VncWorker);
            let change = futures::stream::iter(state_change_task.as_mut().map(|x| x.into_stream()))
                .flatten()
                .map(Event::StateChange);
            let shutdown = pin!(async {
                if let Some(s) = &mut pending_shutdown {
                    Event::ShutdownResult(s.await)
                } else {
                    pending().await
                }
            });

            (
                &mut console_command_recv,
                &mut inspect_completion_engine_recv,
                &mut notify_recv,
                pulse_save_restore.into_stream(),
                vm,
                vnc,
                change,
                shutdown.into_stream(),
            )
                .merge()
                .next()
                .await
                .unwrap()
        };

        let (cmd, _processing_done_send) = match event {
            Event::Command(message) => message,
            Event::InspectRequestFromCompletionEngine((vtl, path, res)) => {
                let mut inspection =
                    InspectionBuilder::new(&path)
                        .depth(Some(1))
                        .inspect(inspect_obj(
                            vtl,
                            mesh,
                            &vm_worker,
                            vnc_worker.as_ref(),
                            gdb_worker.as_ref(),
                            &mut diag_inspector,
                        ));
                let _ = CancelContext::new()
                    .with_timeout(Duration::from_secs(1))
                    .until_cancelled(inspection.resolve())
                    .await;

                let node = inspection.results();
                res.send(node);
                continue;
            }
            Event::Quit => break,
            Event::Halt(reason) => {
                match reason {
                    vmm_core_defs::HaltReason::Reset
                        if !opt.halt_on_reset && state_change_task.is_none() =>
                    {
                        tracing::info!("guest-initiated reset");
                        state_change(
                            driver,
                            &vm_rpc,
                            &mut state_change_task,
                            VmRpc::Reset,
                            StateChange::Reset,
                        );
                    }
                    _ => {
                        tracing::info!(?reason, "guest halted");
                    }
                }
                continue;
            }
            Event::PulseSaveRestore => {
                vm_rpc.call(VmRpc::PulseSaveRestore, ()).await??;
                continue;
            }
            Event::Worker(event) => {
                match event {
                    WorkerEvent::Stopped => {
                        if quit {
                            tracing::info!("vm stopped");
                        } else {
                            tracing::error!("vm worker unexpectedly stopped");
                        }
                        break;
                    }
                    WorkerEvent::Failed(err) => {
                        tracing::error!(error = &err as &dyn std::error::Error, "vm worker failed");
                        break;
                    }
                    WorkerEvent::RestartFailed(err) => {
                        tracing::error!(
                            error = &err as &dyn std::error::Error,
                            "vm worker restart failed"
                        );
                    }
                    WorkerEvent::Started => {
                        tracing::info!("vm worker restarted");
                    }
                }
                continue;
            }
            Event::VncWorker(event) => {
                match event {
                    WorkerEvent::Stopped => tracing::error!("vnc unexpectedly stopped"),
                    WorkerEvent::Failed(err) => {
                        tracing::error!(
                            error = &err as &dyn std::error::Error,
                            "vnc worker failed"
                        );
                    }
                    WorkerEvent::RestartFailed(err) => {
                        tracing::error!(
                            error = &err as &dyn std::error::Error,
                            "vnc worker restart failed"
                        );
                    }
                    WorkerEvent::Started => {
                        tracing::info!("vnc worker restarted");
                    }
                }
                continue;
            }
            Event::StateChange(r) => {
                match r {
                    Ok(sc) => match sc {
                        StateChange::Pause(success) => {
                            if success {
                                tracing::info!("pause complete");
                            } else {
                                tracing::warn!("already paused");
                            }
                        }
                        StateChange::Resume(success) => {
                            if success {
                                tracing::info!("resumed complete");
                            } else {
                                tracing::warn!("already running");
                            }
                        }
                        StateChange::Reset(r) => match r {
                            Ok(()) => tracing::info!("reset complete"),
                            Err(err) => tracing::error!(
                                error = &err as &dyn std::error::Error,
                                "reset failed"
                            ),
                        },
                        StateChange::PulseSaveRestore(r) => match r {
                            Ok(()) => tracing::info!("pulse save/restore complete"),
                            Err(err) => tracing::error!(
                                error = &err as &dyn std::error::Error,
                                "pulse save/restore failed"
                            ),
                        },
                    },
                    Err(err) => {
                        tracing::error!(
                            error = &err as &dyn std::error::Error,
                            "communication failure during state change"
                        );
                    }
                }
                state_change_task = None;
                continue;
            }
            Event::ShutdownResult(r) => {
                match r {
                    Ok(r) => match r {
                        hyperv_ic_resources::shutdown::ShutdownResult::Ok => {
                            tracing::info!("shutdown initiated");
                        }
                        hyperv_ic_resources::shutdown::ShutdownResult::NotReady => {
                            tracing::error!("shutdown ic not ready");
                        }
                        hyperv_ic_resources::shutdown::ShutdownResult::AlreadyInProgress => {
                            tracing::error!("shutdown already in progress");
                        }
                        hyperv_ic_resources::shutdown::ShutdownResult::Failed(hr) => {
                            tracing::error!("shutdown failed with error code {hr:#x}");
                        }
                    },
                    Err(err) => {
                        tracing::error!(
                            error = &err as &dyn std::error::Error,
                            "communication failure during shutdown"
                        );
                    }
                }
                pending_shutdown = None;
                continue;
            }
        };

        fn inspect_obj<'a>(
            target: InspectTarget,
            mesh: &'a VmmMesh,
            vm_worker: &'a WorkerHandle,
            vnc_worker: Option<&'a WorkerHandle>,
            gdb_worker: Option<&'a WorkerHandle>,
            diag_inspector: &'a mut DiagInspector,
        ) -> impl 'a + InspectMut {
            inspect::adhoc_mut(move |req| match target {
                InspectTarget::Host => {
                    let mut resp = req.respond();
                    resp.field("mesh", mesh)
                        .field("vm", vm_worker)
                        .field("vnc", vnc_worker)
                        .field("gdb", gdb_worker);
                }
                InspectTarget::Paravisor => {
                    diag_inspector.inspect_mut(req);
                }
            })
        }

        fn state_change<U: 'static + Send>(
            driver: impl Spawn,
            vm_rpc: &mesh::Sender<VmRpc>,
            state_change_task: &mut Option<Task<Result<StateChange, RecvError>>>,
            f: impl FnOnce(Rpc<(), U>) -> VmRpc,
            g: impl FnOnce(U) -> StateChange + 'static + Send,
        ) {
            if state_change_task.is_some() {
                tracing::error!("state change already in progress");
            } else {
                let rpc = vm_rpc.call(f, ());
                *state_change_task =
                    Some(driver.spawn("state-change", async move { Ok(g(rpc.await?)) }));
            }
        }

        match cmd {
            InteractiveCommand::Panic => {
                panic!("injected panic")
            }
            InteractiveCommand::Restart => {
                // create a new host process
                let vm_host = mesh.make_host("vm", opt.log_file.clone()).await?;

                vm_worker.restart(&vm_host);
            }
            InteractiveCommand::Pause => {
                state_change(
                    driver,
                    &vm_rpc,
                    &mut state_change_task,
                    VmRpc::Pause,
                    StateChange::Pause,
                );
            }
            InteractiveCommand::Resume => {
                state_change(
                    driver,
                    &vm_rpc,
                    &mut state_change_task,
                    VmRpc::Resume,
                    StateChange::Resume,
                );
            }
            InteractiveCommand::Reset => {
                state_change(
                    driver,
                    &vm_rpc,
                    &mut state_change_task,
                    VmRpc::Reset,
                    StateChange::Reset,
                );
            }
            InteractiveCommand::PulseSaveRestore => {
                state_change(
                    driver,
                    &vm_rpc,
                    &mut state_change_task,
                    VmRpc::PulseSaveRestore,
                    StateChange::PulseSaveRestore,
                );
            }
            InteractiveCommand::SchedulePulseSaveRestore { interval } => {
                pulse_save_restore_interval = match interval {
                    Some(seconds) if seconds != 0 => Some(Duration::from_secs(seconds)),
                    _ => {
                        // Treat None and 0 seconds as do not perform scheduled pulse save restores anymore.
                        None
                    }
                }
            }
            InteractiveCommand::Shutdown {
                reboot,
                hibernate,
                force,
            } => {
                if pending_shutdown.is_some() {
                    println!("shutdown already in progress");
                } else if let Some(ic) = &resources.shutdown_ic {
                    let params = hyperv_ic_resources::shutdown::ShutdownParams {
                        shutdown_type: if hibernate {
                            hyperv_ic_resources::shutdown::ShutdownType::Hibernate
                        } else if reboot {
                            hyperv_ic_resources::shutdown::ShutdownType::Reboot
                        } else {
                            hyperv_ic_resources::shutdown::ShutdownType::PowerOff
                        },
                        force,
                    };
                    pending_shutdown =
                        Some(ic.call(hyperv_ic_resources::shutdown::ShutdownRpc::Shutdown, params));
                } else {
                    println!("no shutdown ic configured");
                }
            }
            InteractiveCommand::Nmi => {
                let _ = vm_rpc.call(VmRpc::Nmi, 0).await;
            }
            InteractiveCommand::ClearHalt => {
                vm_rpc.call(VmRpc::ClearHalt, ()).await.ok();
            }
            InteractiveCommand::AddDisk {
                read_only,
                target,
                path,
                lun,
                ram,
                file_path,
                is_dvd,
            } => {
                let action = async {
                    let scsi = resources.scsi_rpc.as_ref().context("no scsi controller")?;
                    let disk_type = match ram {
                        None => {
                            let path = file_path.context("no filename passed")?;
                            open_disk_type(path.as_ref(), read_only)
                                .with_context(|| format!("failed to open {}", path.display()))?
                        }
                        Some(size) => {
                            Resource::new(disk_backend_resources::RamDiskHandle { len: size })
                        }
                    };

                    let device = if is_dvd {
                        SimpleScsiDvdHandle {
                            media: Some(disk_type),
                            requests: None,
                        }
                        .into_resource()
                    } else {
                        SimpleScsiDiskHandle {
                            disk: disk_type,
                            read_only,
                            parameters: Default::default(),
                        }
                        .into_resource()
                    };

                    let cfg = ScsiDeviceAndPath {
                        path: ScsiPath { path, target, lun },
                        device,
                    };

                    scsi.call_failable(ScsiControllerRequest::AddDevice, cfg)
                        .await?;

                    anyhow::Result::<_>::Ok(())
                };

                if let Err(error) = action.await {
                    tracing::error!(error = error.as_error(), "error adding disk")
                }
            }
            InteractiveCommand::RmDisk { target, path, lun } => {
                let action = async {
                    let scsi = resources.scsi_rpc.as_ref().context("no scsi controller")?;
                    scsi.call_failable(
                        ScsiControllerRequest::RemoveDevice,
                        ScsiPath { target, path, lun },
                    )
                    .await?;
                    anyhow::Ok(())
                };

                if let Err(error) = action.await {
                    tracing::error!(error = error.as_error(), "error removing disk")
                }
            }
            InteractiveCommand::Inspect {
                recursive,
                limit,
                paravisor,
                element,
                update,
            } => {
                let obj = inspect_obj(
                    if paravisor {
                        InspectTarget::Paravisor
                    } else {
                        InspectTarget::Host
                    },
                    mesh,
                    &vm_worker,
                    vnc_worker.as_ref(),
                    gdb_worker.as_ref(),
                    &mut diag_inspector,
                );

                if let Some(value) = update {
                    let Some(element) = element else {
                        anyhow::bail!("must provide element for update")
                    };

                    let value = async {
                        let update = inspect::update(&element, &value, obj);
                        let value = CancelContext::new()
                            .with_timeout(Duration::from_secs(1))
                            .until_cancelled(update)
                            .await??;
                        anyhow::Ok(value)
                    }
                    .await;
                    match value {
                        Ok(node) => println!("{:#}", node),
                        Err(err) => println!("error: {:#}", err),
                    }
                } else {
                    let element = element.unwrap_or_default();
                    let depth = if recursive { limit } else { Some(0) };
                    let node = async {
                        let mut inspection =
                            InspectionBuilder::new(&element).depth(depth).inspect(obj);
                        let _ = CancelContext::new()
                            .with_timeout(Duration::from_secs(1))
                            .until_cancelled(inspection.resolve())
                            .await;
                        inspection.results()
                    }
                    .await;

                    println!("{:#}", node);
                }
            }
            InteractiveCommand::RestartVnc => {
                if let Some(vnc) = &mut vnc_worker {
                    let action = || async move {
                        let vnc_host = mesh
                            .make_host("vnc", None)
                            .await
                            .context("spawning vnc process failed")?;

                        vnc.restart(&vnc_host);
                        anyhow::Result::<_>::Ok(())
                    };

                    if let Err(error) = (action)().await {
                        eprintln!("error: {}", error);
                    }
                } else {
                    eprintln!("ERROR: no VNC server running");
                }
            }
            InteractiveCommand::Hvsock { term, port } => {
                let vm_rpc = &vm_rpc;
                let action = || async move {
                    let service_id = new_hvsock_service_id(port);
                    let pool = DefaultPool::new();
                    let socket = vm_rpc
                        .call_failable(
                            VmRpc::ConnectHvsock,
                            (
                                CancelContext::new().with_timeout(Duration::from_secs(2)),
                                service_id,
                                DeviceVtl::Vtl0,
                            ),
                        )
                        .await?;
                    let path = console::relay_console_server(&pool.driver(), socket)?;
                    console::launch_console(term.as_ref().map(|x| x.as_ref()), &path)?;
                    thread::spawn(move || pool.run());
                    anyhow::Result::<_>::Ok(())
                };

                if let Err(error) = (action)().await {
                    eprintln!("error: {}", error);
                }
            }
            InteractiveCommand::ServiceVtl2 {
                user_mode_only,
                igvm,
            } => {
                let r = async {
                    let start;
                    if user_mode_only {
                        let diag = connect_diag(driver.clone(), &vm_rpc, DeviceVtl::Vtl2).await?;
                        start = Instant::now();
                        diag.restart().await?;
                    } else {
                        let path = igvm
                            .as_ref()
                            .or(opt.igvm.as_ref())
                            .context("no igvm file loaded")?;
                        let file = fs_err::File::open(path)?;
                        start = Instant::now();
                        hvlite_helpers::underhill::service_underhill(
                            &vm_rpc,
                            resources.ged_rpc.as_ref().context("no GED")?,
                            file.into(),
                        )
                        .await?;
                    }
                    anyhow::Ok(start)
                }
                .await;
                let end = Instant::now();
                match r {
                    Ok(start) => {
                        println!("servicing time: {}ms", (end - start).as_millis());
                    }
                    Err(err) => eprintln!("error: {:#}", err),
                }
            }
            InteractiveCommand::Quit => {
                tracing::info!("quitting");
                // Work around the detached SCSI task holding up worker stop.
                // TODO: Fix the underlying bug
                resources.scsi_rpc = None;

                vm_worker.stop();
                quit = true;
            }
            InteractiveCommand::ReadMemory { gpa, size, file } => {
                let size = size as usize;
                let data = vm_rpc.call(VmRpc::ReadMemory, (gpa, size)).await?;

                match data {
                    Ok(bytes) => {
                        if let Some(file) = file {
                            if let Err(err) = fs_err::write(file, bytes) {
                                eprintln!("error: {err:?}");
                            }
                        } else {
                            let width = 16;
                            let show_ascii = true;

                            let mut dump = String::new();
                            for (i, chunk) in bytes.chunks(width).enumerate() {
                                let hex_part: Vec<String> =
                                    chunk.iter().map(|byte| format!("{:02x}", byte)).collect();
                                let hex_line = hex_part.join(" ");

                                if show_ascii {
                                    let ascii_part: String = chunk
                                        .iter()
                                        .map(|&byte| {
                                            if byte.is_ascii_graphic() || byte == b' ' {
                                                byte as char
                                            } else {
                                                '.'
                                            }
                                        })
                                        .collect();
                                    dump.push_str(&format!(
                                        "{:04x}: {:<width$}  {}\n",
                                        i * width,
                                        hex_line,
                                        ascii_part,
                                        width = width * 3 - 1
                                    ));
                                } else {
                                    dump.push_str(&format!("{:04x}: {}\n", i * width, hex_line));
                                }
                            }

                            println!("{dump}");
                        }
                    }
                    Err(err) => {
                        eprintln!("error: {err:?}");
                    }
                }
            }
            InteractiveCommand::WriteMemory { gpa, hex, file } => {
                if hex.is_some() == file.is_some() {
                    eprintln!("error: either path to the file or the hex string must be specified");
                    continue;
                }

                let data = if let Some(file) = file {
                    let data = fs_err::read(file);
                    match data {
                        Ok(data) => data,
                        Err(err) => {
                            eprintln!("error: {err:?}");
                            continue;
                        }
                    }
                } else if let Some(hex) = hex {
                    if hex.len() & 1 != 0 {
                        eprintln!(
                            "error: expected even number of hex digits (2 hex digits per byte)"
                        );
                        continue;
                    }
                    let data: Result<Vec<u8>, String> = (0..hex.len())
                        .step_by(2)
                        .map(|i| {
                            u8::from_str_radix(&hex[i..i + 2], 16).map_err(|e| {
                                format!("invalid hex character at position {}: {}", i, e)
                            })
                        })
                        .collect();

                    match data {
                        Ok(data) => data,
                        Err(err) => {
                            eprintln!("error: {err}");
                            continue;
                        }
                    }
                } else {
                    unreachable!();
                };

                if data.is_empty() {
                    eprintln!("error: no data to write");
                    continue;
                }

                if let Err(err) = vm_rpc.call(VmRpc::WriteMemory, (gpa, data)).await? {
                    eprintln!("error: {err:?}");
                }
            }
            InteractiveCommand::Input { .. } | InteractiveCommand::InputMode => unreachable!(),
        }
    }

    vm_worker.stop();
    vm_worker.join().await?;
    Ok(())
}

async fn connect_diag(
    driver: impl Driver + Spawn,
    vm_rpc: &mesh::Sender<VmRpc>,
    openhcl_vtl: DeviceVtl,
) -> anyhow::Result<diag_client::DiagClient> {
    let service_id = new_hvsock_service_id(1);
    let socket = vm_rpc
        .call_failable(
            VmRpc::ConnectHvsock,
            (
                CancelContext::new().with_timeout(Duration::from_secs(2)),
                service_id,
                openhcl_vtl,
            ),
        )
        .await?;
    let diag_client = diag_client::DiagClient::from_conn(driver, socket);
    Ok(diag_client)
}

/// An object that implements [`InspectMut`] by sending an inspect request over
/// TTRPC to the guest (typically the paravisor running in VTL2), then stitching
/// the response back into the inspect tree.
///
/// This also caches the TTRPC connection to the guest so that only the first
/// inspect request has to wait for the connection to be established.
pub struct DiagInspector(DiagInspectorInner);

enum DiagInspectorInner {
    NotStarted {
        driver: DefaultDriver,
        vm_rpc: Arc<mesh::Sender<VmRpc>>,
        openhcl_vtl: DeviceVtl,
    },
    Started {
        send: mesh::Sender<inspect::Deferred>,
        _task: Task<()>,
    },
    Invalid,
}

impl DiagInspector {
    pub fn new(
        driver: DefaultDriver,
        vm_rpc: Arc<mesh::Sender<VmRpc>>,
        openhcl_vtl: DeviceVtl,
    ) -> Self {
        Self(DiagInspectorInner::NotStarted {
            driver,
            vm_rpc,
            openhcl_vtl,
        })
    }

    fn start(&mut self) -> &mesh::Sender<inspect::Deferred> {
        loop {
            match self.0 {
                DiagInspectorInner::NotStarted { .. } => {
                    let DiagInspectorInner::NotStarted {
                        driver,
                        vm_rpc,
                        openhcl_vtl,
                    } = std::mem::replace(&mut self.0, DiagInspectorInner::Invalid)
                    else {
                        unreachable!()
                    };
                    let (send, recv) = mesh::channel();
                    let task = driver
                        .clone()
                        .spawn("diag-inspect", Self::run(driver, vm_rpc, recv, openhcl_vtl));

                    self.0 = DiagInspectorInner::Started { send, _task: task };
                }
                DiagInspectorInner::Started { ref send, .. } => break send,
                DiagInspectorInner::Invalid => unreachable!(),
            }
        }
    }

    async fn run(
        driver: DefaultDriver,
        vm_rpc: Arc<mesh::Sender<VmRpc>>,
        mut recv: mesh::Receiver<inspect::Deferred>,
        openhcl_vtl: DeviceVtl,
    ) {
        let mut last_client = None;
        while let Some(deferred) = recv.next().await {
            let client = if let Some(client) = &mut last_client {
                client
            } else {
                match connect_diag(driver.clone(), &vm_rpc, openhcl_vtl).await {
                    Ok(client) => last_client.insert(client),
                    Err(err) => {
                        deferred.complete_external(
                            inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}"))),
                            inspect::SensitivityLevel::Unspecified,
                        );
                        continue;
                    }
                }
            };

            let info = deferred.external_request();
            let result = match info.request_type {
                inspect::ExternalRequestType::Inspect { depth } => {
                    if depth == 0 {
                        Ok(inspect::Node::Unevaluated)
                    } else {
                        // TODO: Support taking timeouts from the command line
                        client
                            .inspect(info.path, Some(depth - 1), Some(Duration::from_secs(1)))
                            .await
                    }
                }
                inspect::ExternalRequestType::Update { value } => {
                    (client.update(info.path, value).await).map(inspect::Node::Value)
                }
            };
            deferred.complete_external(
                result.unwrap_or_else(|err| {
                    last_client = None;
                    inspect::Node::Failed(inspect::Error::Mesh(format!("{err:#}")))
                }),
                inspect::SensitivityLevel::Unspecified,
            )
        }
    }
}

impl InspectMut for DiagInspector {
    fn inspect_mut(&mut self, req: inspect::Request<'_>) {
        self.start().send(req.defer());
    }
}

enum InspectTarget {
    Host,
    Paravisor,
}

mod interactive_console {
    use super::InteractiveCommand;
    use rustyline::Helper;
    use rustyline::Highlighter;
    use rustyline::Hinter;
    use rustyline::Validator;

    #[derive(Helper, Highlighter, Hinter, Validator)]
    pub(crate) struct HvLiteRustylineEditor {
        pub hvlite_inspect_req: std::sync::Arc<
            mesh::Sender<(
                super::InspectTarget,
                String,
                mesh::OneshotSender<inspect::Node>,
            )>,
        >,
    }

    impl rustyline::completion::Completer for HvLiteRustylineEditor {
        type Candidate = String;

        fn complete(
            &self,
            line: &str,
            pos: usize,
            _ctx: &rustyline::Context<'_>,
        ) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
            let Ok(cmd) = shell_words::split(line) else {
                return Ok((0, Vec::with_capacity(0)));
            };

            let completions = futures::executor::block_on(
                clap_dyn_complete::Complete {
                    cmd,
                    raw: Some(line.into()),
                    position: Some(pos),
                }
                .generate_completions::<InteractiveCommand>(None, self),
            );

            let pos_from_end = {
                let line = line.chars().take(pos).collect::<String>();

                let trailing_ws = line.len() - line.trim_end().len();

                if trailing_ws > 0 {
                    line.len() - trailing_ws + 1 // +1 for the space
                } else {
                    let last_word = shell_words::split(&line)
                        .unwrap_or_default()
                        .last()
                        .cloned()
                        .unwrap_or_default();

                    line.len() - last_word.len()
                }
            };

            Ok((pos_from_end, completions))
        }
    }

    impl clap_dyn_complete::CustomCompleterFactory for &HvLiteRustylineEditor {
        type CustomCompleter = HvLiteComplete;
        async fn build(&self, _ctx: &clap_dyn_complete::RootCtx<'_>) -> Self::CustomCompleter {
            HvLiteComplete {
                hvlite_inspect_req: self.hvlite_inspect_req.clone(),
            }
        }
    }

    pub struct HvLiteComplete {
        hvlite_inspect_req: std::sync::Arc<
            mesh::Sender<(
                super::InspectTarget,
                String,
                mesh::OneshotSender<inspect::Node>,
            )>,
        >,
    }

    impl clap_dyn_complete::CustomCompleter for HvLiteComplete {
        async fn complete(
            &self,
            ctx: &clap_dyn_complete::RootCtx<'_>,
            subcommand_path: &[&str],
            arg_id: &str,
        ) -> Vec<String> {
            match (subcommand_path, arg_id) {
                (["hvlite_entry", "inspect"], "element") => {
                    let on_error = vec!["failed/to/connect".into()];

                    let (parent_path, to_complete) = (ctx.to_complete)
                        .rsplit_once('/')
                        .unwrap_or(("", ctx.to_complete));

                    let node = {
                        let paravisor = {
                            let raw_arg = ctx
                                .matches
                                .subcommand()
                                .unwrap()
                                .1
                                .get_one::<String>("paravisor")
                                .map(|x| x.as_str())
                                .unwrap_or_default();
                            raw_arg == "true"
                        };

                        let (tx, rx) = mesh::oneshot();
                        self.hvlite_inspect_req.send((
                            if paravisor {
                                super::InspectTarget::Paravisor
                            } else {
                                super::InspectTarget::Host
                            },
                            parent_path.to_owned(),
                            tx,
                        ));
                        let Ok(node) = rx.await else {
                            return on_error;
                        };

                        node
                    };

                    let mut completions = Vec::new();

                    if let inspect::Node::Dir(dir) = node {
                        for entry in dir {
                            if entry.name.starts_with(to_complete) {
                                if parent_path.is_empty() {
                                    completions.push(format!("{}/", entry.name))
                                } else {
                                    completions.push(format!(
                                        "{}/{}{}",
                                        parent_path,
                                        entry.name,
                                        if matches!(entry.node, inspect::Node::Dir(..)) {
                                            "/"
                                        } else {
                                            ""
                                        }
                                    ))
                                }
                            }
                        }
                    } else {
                        return on_error;
                    }

                    completions
                }
                _ => Vec::new(),
            }
        }
    }
}