morpheus_network/mainloop/
bare_metal.rs

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
//! Bare-metal main loop for post-ExitBootServices execution.
//!
//! This module provides the complete end-to-end runner that:
//! 1. Initializes the VirtIO-net driver using ASM layer
//! 2. Creates the smoltcp interface and sockets
//! 3. Runs the 5-phase main loop
//! 4. Orchestrates ISO download and disk write
//! 5. Writes manifest to disk for boot entry discovery
//!
//! # Reference
//! NETWORK_IMPL_GUIDE.md §6, §7

#![allow(unused_variables)]
#![allow(dead_code)]

use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec;
use alloc::vec::Vec;

use smoltcp::iface::{Config, Interface, SocketSet, SocketStorage};
use smoltcp::socket::dhcpv4::{Event as Dhcpv4Event, Socket as Dhcpv4Socket};
use smoltcp::socket::dns::{GetQueryResultError, Socket as DnsSocket};
use smoltcp::socket::tcp::{Socket as TcpSocket, SocketBuffer as TcpSocketBuffer};
use smoltcp::time::Instant;
use smoltcp::wire::{
    DnsQueryType, EthernetAddress, HardwareAddress, IpAddress, IpCidr, Ipv4Address, Ipv4Cidr,
};

use crate::boot::handoff::{BootHandoff, BLK_TYPE_VIRTIO, TRANSPORT_MMIO, TRANSPORT_PCI_MODERN};
use crate::boot::init::TimeoutConfig;
use crate::driver::block_io_adapter::VirtioBlkBlockIo;
use crate::driver::block_traits::BlockDriver;
use crate::driver::traits::NetworkDriver;
use crate::driver::virtio::{PciModernConfig, TransportType, VirtioTransport};
use crate::driver::virtio::{VirtioConfig, VirtioInitError, VirtioNetDriver};
use crate::driver::virtio_blk::{VirtioBlkConfig, VirtioBlkDriver, VirtioBlkInitError};
use crate::transfer::disk::{ChunkPartition, ChunkSet, PartitionInfo, MAX_CHUNK_PARTITIONS};
use crate::url::Url;

// Import manifest support from morpheus-core (same format bootloader scanner uses)
use morpheus_core::iso::{IsoManifest, MAX_MANIFEST_SIZE};

// Import from sibling modules in the mainloop package
use super::phases::{phase1_rx_refill, phase5_tx_completions};
use super::runner::{get_tsc, MainLoopConfig};

// Import download state machine from state module
use crate::state::download::{DownloadConfig, IsoDownloadState};

// ═══════════════════════════════════════════════════════════════════════════
// SERIAL OUTPUT (POST-EBS)
// ═══════════════════════════════════════════════════════════════════════════

/// Serial port base address (COM1).
const SERIAL_PORT: u16 = 0x3F8;

/// Write a byte to serial port.
#[cfg(target_arch = "x86_64")]
unsafe fn serial_write_byte(byte: u8) {
    // Wait for transmit buffer empty
    loop {
        let status: u8;
        core::arch::asm!(
            "in al, dx",
            in("dx") SERIAL_PORT + 5,
            out("al") status,
            options(nomem, nostack)
        );
        if status & 0x20 != 0 {
            break;
        }
    }
    // Write byte
    core::arch::asm!(
        "out dx, al",
        in("dx") SERIAL_PORT,
        in("al") byte,
        options(nomem, nostack)
    );
}

#[cfg(not(target_arch = "x86_64"))]
unsafe fn serial_write_byte(_byte: u8) {}

/// Write string to serial port.
pub fn serial_print(s: &str) {
    for byte in s.bytes() {
        unsafe {
            serial_write_byte(byte);
        }
    }
}

/// Write string with newline.
pub fn serial_println(s: &str) {
    serial_print(s);
    serial_print("\r\n");
}

/// Print hex number.
pub fn serial_print_hex(value: u64) {
    serial_print("0x");
    for i in (0..16).rev() {
        let nibble = ((value >> (i * 4)) & 0xF) as u8;
        let c = if nibble < 10 {
            b'0' + nibble
        } else {
            b'a' + nibble - 10
        };
        unsafe {
            serial_write_byte(c);
        }
    }
}

/// Print an IPv4 address (e.g., "10.0.2.15").
pub fn print_ipv4(ip: Ipv4Address) {
    let octets = ip.as_bytes();
    for (i, octet) in octets.iter().enumerate() {
        if i > 0 {
            serial_print(".");
        }
        serial_print_decimal(*octet as u32);
    }
}

/// Print a decimal number.
pub fn serial_print_decimal(value: u32) {
    if value == 0 {
        unsafe {
            serial_write_byte(b'0');
        }
        return;
    }
    let mut buf = [0u8; 10];
    let mut i = 0;
    let mut val = value;
    while val > 0 {
        buf[i] = b'0' + (val % 10) as u8;
        val /= 10;
        i += 1;
    }
    while i > 0 {
        i -= 1;
        unsafe {
            serial_write_byte(buf[i]);
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// STREAMING DISK WRITE HELPERS
// ═══════════════════════════════════════════════════════════════════════════

/// Flush the disk write buffer to the block device.
///
/// Writes the buffered data as one or more sector writes.
/// Returns the number of bytes written, or 0 on error.
unsafe fn flush_disk_buffer(blk_driver: &mut VirtioBlkDriver) -> usize {
    if DISK_WRITE_BUFFER_FILL == 0 {
        return 0;
    }

    // Calculate sectors to write (round up)
    let bytes_to_write = DISK_WRITE_BUFFER_FILL;
    let num_sectors = ((bytes_to_write + 511) / 512) as u32;

    // Get the buffer physical address (we're identity mapped post-EBS)
    let buffer_phys = (&raw const DISK_WRITE_BUFFER).cast::<u8>() as u64;

    // Submit write request
    let request_id = DISK_NEXT_REQUEST_ID;
    DISK_NEXT_REQUEST_ID = DISK_NEXT_REQUEST_ID.wrapping_add(1);

    // Poll for completion space first (drain any pending completions)
    while let Some(_completion) = blk_driver.poll_completion() {
        // Just drain pending completions
    }

    // Check if driver can accept a request
    if !blk_driver.can_submit() {
        serial_println("[DISK] ERROR: Block queue full, cannot submit");
        return 0;
    }

    // Submit the write
    if let Err(e) = blk_driver.submit_write(DISK_NEXT_SECTOR, buffer_phys, num_sectors, request_id)
    {
        serial_print("[DISK] ERROR: Write submit failed at sector ");
        serial_print_hex(DISK_NEXT_SECTOR);
        serial_println("");
        return 0;
    }

    // Notify the device
    blk_driver.notify();

    // Poll for completion (with timeout)
    let start_tsc = super::runner::get_tsc();
    let timeout_ticks = 100_000_000; // ~100ms at 1GHz TSC

    loop {
        if let Some(completion) = blk_driver.poll_completion() {
            if completion.request_id == request_id {
                if completion.status == 0 {
                    // Success!
                    DISK_NEXT_SECTOR += num_sectors as u64;
                    DISK_TOTAL_BYTES += bytes_to_write as u64;
                    DISK_WRITE_BUFFER_FILL = 0;
                    return bytes_to_write;
                } else {
                    serial_print("[DISK] ERROR: Write completion status ");
                    serial_print_decimal(completion.status as u32);
                    serial_println("");
                    return 0;
                }
            }
        }

        let now = super::runner::get_tsc();
        if now.wrapping_sub(start_tsc) > timeout_ticks {
            serial_println("[DISK] ERROR: Write completion timeout");
            return 0;
        }

        core::hint::spin_loop();
    }
}

/// Add data to the disk write buffer.
/// Automatically flushes when buffer is full.
/// Returns the number of bytes consumed from the input.
unsafe fn buffer_disk_write(blk_driver: &mut VirtioBlkDriver, data: &[u8]) -> usize {
    let mut consumed = 0;
    let mut remaining = data;

    while !remaining.is_empty() {
        // Calculate how much fits in current buffer
        let space_left = DISK_WRITE_BUFFER_SIZE - DISK_WRITE_BUFFER_FILL;
        let to_copy = remaining.len().min(space_left);

        // Copy to buffer
        let dst_start = DISK_WRITE_BUFFER_FILL;
        DISK_WRITE_BUFFER[dst_start..dst_start + to_copy].copy_from_slice(&remaining[..to_copy]);
        DISK_WRITE_BUFFER_FILL += to_copy;
        consumed += to_copy;
        remaining = &remaining[to_copy..];

        // Flush if buffer is full
        if DISK_WRITE_BUFFER_FILL >= DISK_WRITE_BUFFER_SIZE {
            let written = flush_disk_buffer(blk_driver);
            if written == 0 {
                // Write failed, stop
                break;
            }
        }
    }

    consumed
}

/// Flush any remaining data in the buffer (for end of download).
unsafe fn flush_remaining_disk_buffer(blk_driver: &mut VirtioBlkDriver) -> bool {
    if DISK_WRITE_BUFFER_FILL > 0 {
        // Pad the rest with zeros (needed for sector alignment)
        for i in DISK_WRITE_BUFFER_FILL..DISK_WRITE_BUFFER_SIZE {
            DISK_WRITE_BUFFER[i] = 0;
        }
        let written = flush_disk_buffer(blk_driver);
        return written > 0;
    }
    true
}

// ═══════════════════════════════════════════════════════════════════════════
// MANIFEST WRITING (POST-EBS)
// ═══════════════════════════════════════════════════════════════════════════

/// Static buffer for manifest serialization (1 sector = 512 bytes, but
/// manifest can be up to ~1KB, so use 2 sectors).
static mut MANIFEST_BUFFER: [u8; 1024] = [0u8; 1024];

/// Write an ISO manifest to disk at the specified sector.
///
/// The manifest is serialized and written to the manifest sector.
/// This allows the bootloader to discover downloaded ISOs on next boot.
///
/// # Arguments
/// * `blk_driver` - The block driver to write with
/// * `manifest_sector` - Sector number to write manifest at
/// * `manifest` - The manifest to write
///
/// # Returns
/// true if write successful, false otherwise
unsafe fn write_manifest_to_disk(
    blk_driver: &mut VirtioBlkDriver,
    manifest_sector: u64,
    manifest: &IsoManifest,
) -> bool {
    serial_println("[MANIFEST] ═══════════════════════════════════════════════════");
    serial_println("[MANIFEST] Writing ISO manifest to disk");
    serial_println("[MANIFEST] ═══════════════════════════════════════════════════");

    serial_println("[MANIFEST] Serializing manifest structure...");

    // Clear buffer using raw pointer
    let manifest_ptr = (&raw mut MANIFEST_BUFFER).cast::<u8>();
    for i in 0..1024 {
        *manifest_ptr.add(i) = 0;
    }

    // Serialize manifest using raw pointer cast to slice
    let manifest_buffer =
        core::slice::from_raw_parts_mut((&raw mut MANIFEST_BUFFER).cast::<u8>(), 1024);
    let size = match manifest.serialize(manifest_buffer) {
        Ok(s) => s,
        Err(_) => {
            serial_println("[MANIFEST] ERROR: Failed to serialize manifest");
            return false;
        }
    };

    serial_print("[MANIFEST] Serialized size: ");
    serial_print_decimal(size as u32);
    serial_println(" bytes");

    serial_print("[MANIFEST] ISO name: ");
    serial_println(manifest.name_str());

    serial_print("[MANIFEST] Total ISO size: ");
    let total_mb = manifest.total_size / (1024 * 1024);
    let total_gb = manifest.total_size / (1024 * 1024 * 1024);
    if total_gb > 0 {
        serial_print_decimal(total_gb as u32);
        serial_print(" GB (");
        serial_print_decimal(total_mb as u32);
        serial_println(" MB)");
    } else {
        serial_print_decimal(total_mb as u32);
        serial_println(" MB");
    }

    serial_print("[MANIFEST] Chunk count: ");
    serial_print_decimal(manifest.chunks.count as u32);
    serial_println("");

    serial_print("[MANIFEST] Complete: ");
    serial_println(if manifest.is_complete() { "YES" } else { "NO" });

    // Calculate sectors needed (round up)
    let num_sectors = ((size + 511) / 512) as u32;

    serial_println("[MANIFEST] ───────────────────────────────────────────────────");
    serial_println("[MANIFEST] Write location:");
    serial_print("[MANIFEST]   Sector (LBA): ");
    serial_print_hex(manifest_sector);
    serial_println("");
    serial_print("[MANIFEST]   Byte offset: ");
    serial_print_hex(manifest_sector * 512);
    serial_println("");
    serial_print("[MANIFEST]   Sectors to write: ");
    serial_print_decimal(num_sectors);
    serial_println("");
    serial_println("[MANIFEST] ───────────────────────────────────────────────────");

    // Get the buffer physical address
    let buffer_phys = manifest_buffer.as_ptr() as u64;

    serial_println("[MANIFEST] Submitting write request...");

    // Poll for completion space first
    while let Some(_completion) = blk_driver.poll_completion() {
        // Drain pending completions
    }

    // Check if driver can accept a request
    if !blk_driver.can_submit() {
        serial_println("[MANIFEST] ERROR: Block queue full");
        return false;
    }

    // Submit the write
    let request_id = DISK_NEXT_REQUEST_ID;
    DISK_NEXT_REQUEST_ID = DISK_NEXT_REQUEST_ID.wrapping_add(1);

    if let Err(_) = blk_driver.submit_write(manifest_sector, buffer_phys, num_sectors, request_id) {
        serial_println("[MANIFEST] ERROR: Write submit failed");
        return false;
    }

    // Notify the device
    blk_driver.notify();

    serial_println("[MANIFEST] Write submitted, waiting for completion...");

    // Poll for completion (with timeout)
    let start_tsc = super::runner::get_tsc();
    let timeout_ticks = 100_000_000; // ~100ms at 1GHz TSC

    loop {
        if let Some(completion) = blk_driver.poll_completion() {
            if completion.request_id == request_id {
                if completion.status == 0 {
                    serial_println(
                        "[MANIFEST] ═══════════════════════════════════════════════════",
                    );
                    serial_println("[MANIFEST] MANIFEST WRITTEN SUCCESSFULLY");
                    serial_println(
                        "[MANIFEST] ═══════════════════════════════════════════════════",
                    );
                    return true;
                } else {
                    serial_print("[MANIFEST] ERROR: Write completion status ");
                    serial_print_decimal(completion.status as u32);
                    serial_println("");
                    return false;
                }
            }
        }

        let now = super::runner::get_tsc();
        if now.wrapping_sub(start_tsc) > timeout_ticks {
            serial_println("[MANIFEST] ERROR: Write timeout");
            return false;
        }

        core::hint::spin_loop();
    }
}

/// Create and write a completed ISO manifest to disk.
///
/// Called after HTTP download completes to record the ISO location.1G
///
/// # Strategy
/// - If `esp_start_lba > 0`: Write to FAT32 ESP at `/.iso/<name>.manifest`
/// - Else if `manifest_sector > 0`: Write to raw sector (legacy)
/// - Else: Skip manifest writing
unsafe fn finalize_manifest(
    blk_driver: &mut VirtioBlkDriver,
    config: &BareMetalConfig,
    total_bytes: u64,
) -> bool {
    // Check if we have any manifest destination configured
    if config.esp_start_lba == 0 && config.manifest_sector == 0 {
        serial_println("[MANIFEST] No manifest destination configured, skipping");
        return true;
    }

    serial_println("");
    serial_println("=== WRITING ISO MANIFEST ===");
    serial_print("[MANIFEST] ISO name: ");
    serial_println(config.iso_name);
    serial_print("[MANIFEST] Total size: ");
    serial_print_decimal((total_bytes / (1024 * 1024)) as u32);
    serial_println(" MB");

    // Calculate end sector
    let bytes_in_sectors = ((total_bytes + 511) / 512) * 512;
    let num_sectors = bytes_in_sectors / 512;
    let end_sector = config.target_start_sector + num_sectors;

    serial_print("[MANIFEST] Sectors: ");
    serial_print_hex(config.target_start_sector);
    serial_print(" - ");
    serial_print_hex(end_sector);
    serial_println("");

    // Prefer FAT32 writing if ESP is configured
    if config.esp_start_lba > 0 {
        return finalize_manifest_fat32(blk_driver, config, total_bytes, end_sector);
    }

    // Fall back to legacy raw sector write
    finalize_manifest_raw(blk_driver, config, total_bytes, end_sector)
}

/// Write manifest to FAT32 ESP filesystem.
///
/// Creates `/.iso/<name>.manifest` file on the ESP.
/// Uses morpheus_core::iso::IsoManifest for compatibility with bootloader scanner.
unsafe fn finalize_manifest_fat32(
    blk_driver: &mut VirtioBlkDriver,
    config: &BareMetalConfig,
    total_bytes: u64,
    end_sector: u64,
) -> bool {
    serial_println("[MANIFEST] Writing to FAT32 ESP...");
    serial_print("[MANIFEST] ESP start LBA: ");
    serial_print_hex(config.esp_start_lba);
    serial_println("");

    // Use actual start sector (determined by free space scan)
    let start_sector = unsafe { ACTUAL_START_SECTOR };
    serial_print("[MANIFEST] ISO start sector: ");
    serial_print_hex(start_sector);
    serial_println("");

    // Create IsoManifest using morpheus_core (same format bootloader scanner expects)
    let mut manifest = IsoManifest::new(config.iso_name, total_bytes);

    // Add chunk with partition UUID and LBA range
    match manifest.add_chunk(config.partition_uuid, start_sector, end_sector) {
        Ok(idx) => {
            serial_print("[MANIFEST] Added chunk ");
            serial_print_decimal(idx as u32);
            serial_println("");

            // Update chunk with data size and mark as written
            if let Some(chunk) = manifest.chunks.chunks.get_mut(idx) {
                chunk.data_size = total_bytes;
                chunk.written = true;
            }
        }
        Err(_) => {
            serial_println("[MANIFEST] ERROR: Failed to add chunk");
            return false;
        }
    }

    // Mark manifest as complete
    manifest.mark_complete();

    // Create BlockIo adapter for FAT32 operations
    serial_println("[MANIFEST] Creating BlockIo adapter for FAT32...");
    let dma_buffer = core::slice::from_raw_parts_mut(
        (&raw mut DISK_WRITE_BUFFER).cast::<u8>(),
        DISK_WRITE_BUFFER_SIZE,
    );
    let dma_buffer_phys = (&raw const DISK_WRITE_BUFFER).cast::<u8>() as u64;
    let timeout_ticks = 500_000_000u64; // ~500ms (increased for FAT32 ops)

    let mut adapter =
        match VirtioBlkBlockIo::new(blk_driver, dma_buffer, dma_buffer_phys, timeout_ticks) {
            Ok(a) => {
                serial_println("[MANIFEST] BlockIo adapter created");
                a
            }
            Err(_) => {
                serial_println("[MANIFEST] ERROR: Failed to create BlockIo adapter");
                return false;
            }
        };

    // Serialize manifest to buffer
    let mut manifest_buffer = [0u8; MAX_MANIFEST_SIZE];
    let manifest_len = match manifest.serialize(&mut manifest_buffer) {
        Ok(len) => {
            serial_print("[MANIFEST] Serialized ");
            serial_print_decimal(len as u32);
            serial_println(" bytes");
            len
        }
        Err(_) => {
            serial_println("[MANIFEST] ERROR: Failed to serialize manifest");
            return false;
        }
    };

    // Generate 8.3 compatible manifest filename (FAT32 limitation)
    // Example: "tails-6.10.iso" -> "4B2A7C3D.MFS" (CRC32 hash)
    let manifest_filename = morpheus_core::fs::generate_8_3_manifest_name(config.iso_name);
    let manifest_path = format!("/.iso/{}", manifest_filename);

    serial_print("[MANIFEST] Writing to: ");
    serial_println(&manifest_path);

    // Ensure .iso directory exists (no subdirectory needed)
    let _ = morpheus_core::fs::create_directory(&mut adapter, config.esp_start_lba, "/.iso");

    // Write manifest file using morpheus_core FAT32 operations
    match morpheus_core::fs::write_file(
        &mut adapter,
        config.esp_start_lba,
        &manifest_path,
        &manifest_buffer[..manifest_len],
    ) {
        Ok(()) => {
            serial_println("[MANIFEST] OK: Written to ESP");
            true
        }
        Err(e) => {
            serial_print("[MANIFEST] ERROR: FAT32 write failed: ");
            serial_println(match e {
                morpheus_core::fs::Fat32Error::IoError => "IO error",
                morpheus_core::fs::Fat32Error::PartitionTooSmall => "Partition too small",
                morpheus_core::fs::Fat32Error::PartitionTooLarge => "Partition too large",
                morpheus_core::fs::Fat32Error::InvalidBlockSize => "Invalid block size",
                morpheus_core::fs::Fat32Error::NotImplemented => "Not implemented",
            });
            false
        }
    }
}
/// Write manifest to raw disk sector (legacy method).
unsafe fn finalize_manifest_raw(
    blk_driver: &mut VirtioBlkDriver,
    config: &BareMetalConfig,
    total_bytes: u64,
    end_sector: u64,
) -> bool {
    serial_println("[MANIFEST] Writing to raw sector (legacy)...");
    serial_print("[MANIFEST] Sector: ");
    serial_print_hex(config.manifest_sector);
    serial_println("");

    // Use actual start sector (determined by free space scan)
    let start_sector = ACTUAL_START_SECTOR;

    // Use morpheus_core's IsoManifest for raw sector write
    let mut manifest = IsoManifest::new(config.iso_name, total_bytes);

    // Add chunk entry
    match manifest.add_chunk(config.partition_uuid, start_sector, end_sector) {
        Ok(idx) => {
            serial_print("[MANIFEST] Added chunk ");
            serial_print_decimal(idx as u32);
            serial_println("");
        }
        Err(_) => {
            serial_println("[MANIFEST] ERROR: Failed to add chunk");
            return false;
        }
    }

    // Update chunk with data size
    if let Some(chunk) = manifest.chunks.chunks.get_mut(0) {
        chunk.data_size = total_bytes;
        chunk.written = true;
    }

    // Mark as complete
    manifest.mark_complete();

    serial_println("[MANIFEST] Manifest marked as COMPLETE");

    // Write to disk
    write_manifest_to_disk(blk_driver, config.manifest_sector, &manifest)
}

// ═══════════════════════════════════════════════════════════════════════════
// GPT PARTITION CREATION FOR ISO DATA
// ═══════════════════════════════════════════════════════════════════════════

/// Create a GPT partition for ISO data storage.
///
/// This properly claims disk space so other tools won't overwrite our ISO.
/// The partition is created at `start_sector` with size `size_bytes`.
///
/// Returns the partition GUID on success.
unsafe fn create_iso_partition(
    blk_driver: &mut VirtioBlkDriver,
    start_sector: u64,
    size_bytes: u64,
    iso_name: &str,
) -> Option<[u8; 16]> {
    use morpheus_core::disk::gpt_ops::create_partition;
    use morpheus_core::disk::partition::PartitionType;

    serial_println("[GPT] ═══════════════════════════════════════════════════════");
    serial_println("[GPT] Creating partition for ISO data storage");
    serial_println("[GPT] ═══════════════════════════════════════════════════════");

    serial_print("[GPT] ISO name: ");
    serial_println(iso_name);

    serial_print("[GPT] Partition type: BasicData (");
    // EBD0A0A2-B9E5-4433-87C0-68B6B72699C7 is Microsoft Basic Data
    serial_println("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7)");

    serial_print("[GPT] Start sector (LBA): ");
    serial_print_hex(start_sector);
    serial_print(" (byte offset: ");
    serial_print_hex(start_sector * 512);
    serial_println(")");

    // Calculate end sector
    let sectors_needed = (size_bytes + 511) / 512;
    let end_sector = start_sector + sectors_needed - 1;

    serial_print("[GPT] End sector (LBA): ");
    serial_print_hex(end_sector);
    serial_print(" (byte offset: ");
    serial_print_hex(end_sector * 512);
    serial_println(")");

    serial_print("[GPT] Sectors needed: ");
    serial_print_decimal(sectors_needed as u32);
    serial_println("");

    serial_print("[GPT] Partition size: ");
    let size_mb = size_bytes / (1024 * 1024);
    let size_gb = size_bytes / (1024 * 1024 * 1024);
    if size_gb > 0 {
        serial_print_decimal(size_gb as u32);
        serial_print(" GB (");
        serial_print_decimal(size_mb as u32);
        serial_println(" MB)");
    } else {
        serial_print_decimal(size_mb as u32);
        serial_println(" MB");
    }

    // Create BlockIo adapter
    serial_println("[GPT] Creating BlockIO adapter...");
    let dma_buffer = core::slice::from_raw_parts_mut(
        (&raw mut DISK_WRITE_BUFFER).cast::<u8>(),
        DISK_WRITE_BUFFER_SIZE,
    );
    let dma_buffer_phys = (&raw const DISK_WRITE_BUFFER).cast::<u8>() as u64;
    let timeout_ticks = 100_000_000u64;

    let adapter =
        match VirtioBlkBlockIo::new(blk_driver, dma_buffer, dma_buffer_phys, timeout_ticks) {
            Ok(a) => {
                serial_println("[GPT] BlockIO adapter created");
                a
            }
            Err(_) => {
                serial_println("[GPT] ERROR: Failed to create BlockIo adapter");
                return None;
            }
        };

    // Create the partition (BasicData type for ISO storage)
    serial_println("[GPT] Writing partition entry to GPT...");
    serial_println("[GPT] (Reading existing GPT header, finding free slot, writing entry)");

    match create_partition(adapter, PartitionType::BasicData, start_sector, end_sector) {
        Ok(()) => {
            serial_println("[GPT] ───────────────────────────────────────────────────────");
            serial_println("[GPT] PARTITION CREATED SUCCESSFULLY");
            serial_println("[GPT] ───────────────────────────────────────────────────────");
            serial_print("[GPT] Location: sectors ");
            serial_print_hex(start_sector);
            serial_print(" - ");
            serial_print_hex(end_sector);
            serial_println("");
            serial_println("[GPT] Type: Microsoft Basic Data");
            serial_println("[GPT] Status: Active in GPT partition table");
            serial_println("[GPT] ───────────────────────────────────────────────────────");
            // Return a placeholder GUID - the create_partition function generates one
            // TODO: Return actual GUID from create_partition
            Some([
                0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34,
                0x56, 0x78,
            ])
        }
        Err(e) => {
            serial_print("[GPT] ERROR: Failed to create partition: ");
            serial_println(match e {
                morpheus_core::disk::gpt_ops::GptError::IoError => {
                    "IO error (disk read/write failed)"
                }
                morpheus_core::disk::gpt_ops::GptError::InvalidHeader => {
                    "Invalid GPT header (disk may not have GPT)"
                }
                morpheus_core::disk::gpt_ops::GptError::InvalidSize => {
                    "Invalid size/range (outside usable area)"
                }
                morpheus_core::disk::gpt_ops::GptError::NoSpace => {
                    "No free partition slot in GPT table"
                }
                morpheus_core::disk::gpt_ops::GptError::PartitionNotFound => "Partition not found",
                morpheus_core::disk::gpt_ops::GptError::OverlappingPartitions => {
                    "Range overlaps existing partition"
                }
                morpheus_core::disk::gpt_ops::GptError::AlignmentError => "Alignment error",
            });
            None
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// NO-HEAP PARSING HELPERS
// ═══════════════════════════════════════════════════════════════════════════

/// Parse a u16 from a string without allocation.
fn parse_u16(s: &str) -> Option<u16> {
    let mut result: u16 = 0;
    for c in s.bytes() {
        if c < b'0' || c > b'9' {
            return None;
        }
        result = result.checked_mul(10)?;
        result = result.checked_add((c - b'0') as u16)?;
    }
    Some(result)
}

/// Parse a u8 from a string without allocation.
fn parse_u8(s: &str) -> Option<u8> {
    let mut result: u16 = 0;
    for c in s.bytes() {
        if c < b'0' || c > b'9' {
            return None;
        }
        result = result * 10 + (c - b'0') as u16;
        if result > 255 {
            return None;
        }
    }
    Some(result as u8)
}

/// Parse IPv4 address from string without allocation.
/// Format: "a.b.c.d" where a,b,c,d are 0-255.
fn parse_ipv4(s: &str) -> Option<Ipv4Address> {
    let bytes = s.as_bytes();
    let mut octets = [0u8; 4];
    let mut octet_idx = 0;
    let mut current: u16 = 0;
    let mut digit_count = 0;

    for &b in bytes {
        if b == b'.' {
            if digit_count == 0 || current > 255 {
                return None;
            }
            if octet_idx >= 3 {
                return None;
            }
            octets[octet_idx] = current as u8;
            octet_idx += 1;
            current = 0;
            digit_count = 0;
        } else if b >= b'0' && b <= b'9' {
            current = current * 10 + (b - b'0') as u16;
            digit_count += 1;
            if digit_count > 3 || current > 255 {
                return None;
            }
        } else {
            return None;
        }
    }

    // Handle last octet
    if digit_count == 0 || current > 255 || octet_idx != 3 {
        return None;
    }
    octets[3] = current as u8;

    Some(Ipv4Address::new(octets[0], octets[1], octets[2], octets[3]))
}

/// Format an HTTP GET request into a static buffer.
/// Returns the number of bytes written, or None if buffer too small.
fn format_http_get(buffer: &mut [u8], path: &str, host: &str) -> Option<usize> {
    let mut pos = 0;

    // "GET "
    let prefix = b"GET ";
    if pos + prefix.len() > buffer.len() {
        return None;
    }
    buffer[pos..pos + prefix.len()].copy_from_slice(prefix);
    pos += prefix.len();

    // path
    let path_bytes = path.as_bytes();
    if pos + path_bytes.len() > buffer.len() {
        return None;
    }
    buffer[pos..pos + path_bytes.len()].copy_from_slice(path_bytes);
    pos += path_bytes.len();

    // " HTTP/1.1\r\nHost: "
    let mid = b" HTTP/1.1\r\nHost: ";
    if pos + mid.len() > buffer.len() {
        return None;
    }
    buffer[pos..pos + mid.len()].copy_from_slice(mid);
    pos += mid.len();

    // host
    let host_bytes = host.as_bytes();
    if pos + host_bytes.len() > buffer.len() {
        return None;
    }
    buffer[pos..pos + host_bytes.len()].copy_from_slice(host_bytes);
    pos += host_bytes.len();

    // Headers and terminator
    let suffix = b"\r\nUser-Agent: MorpheusX/1.0\r\nAccept: */*\r\nConnection: close\r\n\r\n";
    if pos + suffix.len() > buffer.len() {
        return None;
    }
    buffer[pos..pos + suffix.len()].copy_from_slice(suffix);
    pos += suffix.len();

    Some(pos)
}

/// Case-insensitive starts_with for ASCII strings (no heap allocation).
fn starts_with_ignore_case(s: &str, prefix: &str) -> bool {
    if s.len() < prefix.len() {
        return false;
    }
    let s_bytes = s.as_bytes();
    let p_bytes = prefix.as_bytes();
    for i in 0..p_bytes.len() {
        let a = s_bytes[i].to_ascii_lowercase();
        let b = p_bytes[i].to_ascii_lowercase();
        if a != b {
            return false;
        }
    }
    true
}

/// Case-insensitive contains for ASCII strings (no heap allocation).
fn contains_ignore_case(s: &str, needle: &str) -> bool {
    if needle.len() > s.len() {
        return false;
    }
    let s_bytes = s.as_bytes();
    let n_bytes = needle.as_bytes();

    for i in 0..=(s_bytes.len() - n_bytes.len()) {
        let mut found = true;
        for j in 0..n_bytes.len() {
            if s_bytes[i + j].to_ascii_lowercase() != n_bytes[j].to_ascii_lowercase() {
                found = false;
                break;
            }
        }
        if found {
            return true;
        }
    }
    false
}

/// Parse usize from string without allocation.
fn parse_usize(s: &str) -> Option<usize> {
    let mut result: usize = 0;
    let mut has_digit = false;
    for c in s.bytes() {
        if c >= b'0' && c <= b'9' {
            has_digit = true;
            result = result.checked_mul(10)?;
            result = result.checked_add((c - b'0') as usize)?;
        } else if c == b' ' || c == b'\t' {
            // Skip whitespace at beginning
            if has_digit {
                break; // Stop at whitespace after digits
            }
        } else {
            break; // Stop at non-digit, non-whitespace
        }
    }
    if has_digit {
        Some(result)
    } else {
        None
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// REENTRANCY GUARD
// ═══════════════════════════════════════════════════════════════════════════

/// Static flag to detect reentrancy in polling loop.
/// If this is > 1 during a poll, we have a bug.
static mut POLL_DEPTH: u32 = 0;

/// Increment poll depth, panic if already polling.
#[inline(always)]
fn enter_poll() {
    unsafe {
        POLL_DEPTH += 1;
        if POLL_DEPTH > 1 {
            serial_println("!!! REENTRANCY BUG DETECTED !!!");
            serial_print("Poll depth: ");
            serial_print_decimal(POLL_DEPTH);
            serial_println("");
            // Halt to prevent further corruption
            loop {
                core::hint::spin_loop();
            }
        }
    }
}

/// Decrement poll depth.
#[inline(always)]
fn exit_poll() {
    unsafe {
        if POLL_DEPTH > 0 {
            POLL_DEPTH -= 1;
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// SMOLTCP DEVICE ADAPTER
// ═══════════════════════════════════════════════════════════════════════════

/// Adapter bridging NetworkDriver to smoltcp Device trait.
///
/// This adapter uses a simple design where:
/// - RX: Buffers received data internally, RxToken references it
/// - TX: TxToken writes directly via the driver
pub struct SmoltcpAdapter<'a, D: NetworkDriver> {
    driver: &'a mut D,
    /// Temporary buffer for received packet
    rx_buffer: [u8; 2048],
    /// Length of data in rx_buffer (0 if no pending packet)
    rx_len: usize,
}

impl<'a, D: NetworkDriver> SmoltcpAdapter<'a, D> {
    pub fn new(driver: &'a mut D) -> Self {
        Self {
            driver,
            rx_buffer: [0u8; 2048],
            rx_len: 0,
        }
    }

    /// Try to receive a packet into our internal buffer.
    /// Called before polling smoltcp.
    pub fn poll_receive(&mut self) {
        if self.rx_len == 0 {
            // No pending packet, try to receive
            match self.driver.receive(&mut self.rx_buffer) {
                Ok(Some(len)) => {
                    self.rx_len = len;
                }
                _ => {}
            }
        }
    }

    /// Refill RX queue. Called in main loop Phase 1.
    pub fn refill_rx(&mut self) {
        self.driver.refill_rx_queue();
    }

    /// Collect TX completions. Called in main loop Phase 5.
    pub fn collect_tx(&mut self) {
        self.driver.collect_tx_completions();
    }
}

/// RX token for smoltcp - uses a fixed-size buffer (no heap allocation).
/// Maximum Ethernet frame size is 1514 bytes.
pub struct RxToken {
    buffer: [u8; 2048],
    len: usize,
}

impl smoltcp::phy::RxToken for RxToken {
    fn consume<R, F>(mut self, f: F) -> R
    where
        F: FnOnce(&mut [u8]) -> R,
    {
        f(&mut self.buffer[..self.len])
    }
}

/// TX token for smoltcp - uses a fixed-size stack buffer (no heap allocation).
pub struct TxToken<'a, D: NetworkDriver> {
    driver: &'a mut D,
}

impl<'a, D: NetworkDriver> smoltcp::phy::TxToken for TxToken<'a, D> {
    fn consume<R, F>(self, len: usize, f: F) -> R
    where
        F: FnOnce(&mut [u8]) -> R,
    {
        // Use stack-allocated buffer (NO HEAP!) - max Ethernet frame + some margin
        // Max frame is 1514 bytes, but smoltcp may request up to ~1600 for headers
        const MAX_FRAME: usize = 2048;
        let mut buffer = [0u8; MAX_FRAME];

        let actual_len = if len > MAX_FRAME {
            serial_println("[ADAPTER-TX] ERROR: requested len exceeds buffer!");
            MAX_FRAME
        } else {
            len
        };

        let result = f(&mut buffer[..actual_len]);

        // Fire-and-forget transmit - don't wait for completion
        let _ = self.driver.transmit(&buffer[..actual_len]);

        result
    }
}

impl<'a, D: NetworkDriver> smoltcp::phy::Device for SmoltcpAdapter<'a, D> {
    type RxToken<'b>
        = RxToken
    where
        Self: 'b;
    type TxToken<'b>
        = TxToken<'b, D>
    where
        Self: 'b;

    fn receive(&mut self, _timestamp: Instant) -> Option<(Self::RxToken<'_>, Self::TxToken<'_>)> {
        // First, try to receive if we don't have a pending packet
        self.poll_receive();

        if self.rx_len > 0 {
            // Copy the packet data to RxToken using fixed buffer (NO HEAP!)
            let mut rx_buf = [0u8; 2048];
            let copy_len = self.rx_len.min(rx_buf.len());
            rx_buf[..copy_len].copy_from_slice(&self.rx_buffer[..copy_len]);
            let rx_len = copy_len;
            self.rx_len = 0; // Mark buffer as consumed

            Some((
                RxToken {
                    buffer: rx_buf,
                    len: rx_len,
                },
                TxToken {
                    driver: self.driver,
                },
            ))
        } else {
            None
        }
    }

    fn transmit(&mut self, _timestamp: Instant) -> Option<Self::TxToken<'_>> {
        if self.driver.can_transmit() {
            Some(TxToken {
                driver: self.driver,
            })
        } else {
            None
        }
    }

    fn capabilities(&self) -> smoltcp::phy::DeviceCapabilities {
        let mut caps = smoltcp::phy::DeviceCapabilities::default();
        caps.medium = smoltcp::phy::Medium::Ethernet;
        caps.max_transmission_unit = 1514;
        caps.max_burst_size = Some(32); // Process up to 32 packets per poll for throughput
        caps
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// BARE-METAL ENTRY POINT
// ═══════════════════════════════════════════════════════════════════════════

/// Run result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunResult {
    /// ISO download and write completed successfully.
    Success,
    /// Initialization failed.
    InitFailed,
    /// DHCP timeout.
    DhcpTimeout,
    /// Download failed.
    DownloadFailed,
    /// Disk write failed.
    DiskWriteFailed,
}

/// Configuration for the bare-metal runner.
///
/// NOTE: Uses &'static str instead of String because we cannot allocate
/// after ExitBootServices (the UEFI allocator is gone).
pub struct BareMetalConfig {
    /// URL to download ISO from (must be 'static - allocated before EBS).
    pub iso_url: &'static str,
    /// ISO filename for manifest (e.g., "tails-6.0.iso").
    pub iso_name: &'static str,
    /// Target disk sector to start writing ISO data at.
    pub target_start_sector: u64,
    /// Sector where manifest is stored (raw sector write, legacy).
    /// Set to 0 to use FAT32 manifest instead.
    pub manifest_sector: u64,
    /// ESP partition start LBA for FAT32 manifest writing.
    /// If non-zero, writes manifest to `/.iso/<name>.manifest` on ESP.
    pub esp_start_lba: u64,
    /// Maximum download size in bytes.
    pub max_download_size: u64,
    /// Whether to write to disk (requires VirtIO-blk).
    pub write_to_disk: bool,
    /// Partition UUID for chunk tracking (16 bytes, or zeros if unknown).
    pub partition_uuid: [u8; 16],
}

impl Default for BareMetalConfig {
    fn default() -> Self {
        Self {
            iso_url: "http://10.0.2.2:8000/test-iso.img",
            iso_name: "download.iso",
            // Start writing ISO data AFTER the 4GB ESP partition
            // ESP is sectors 2048 to ~8388608 (1MiB to 4GiB)
            // We start at 4GiB = 8388608 sectors
            target_start_sector: 8388608, // 4GiB in 512-byte sectors
            manifest_sector: 0,           // Use FAT32 by default (set non-zero for raw sector)
            esp_start_lba: 2048,          // Standard GPT ESP at sector 2048
            max_download_size: 4 * 1024 * 1024 * 1024, // 4GB max
            write_to_disk: true,          // Enable disk writes by default
            partition_uuid: [0u8; 16],    // Will be set by bootloader if known
        }
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// DISK WRITE BUFFER (Static - no heap allocation)
// ═══════════════════════════════════════════════════════════════════════════

/// Size of write buffer: 64KB = 128 sectors (optimal for VirtIO-blk)
const DISK_WRITE_BUFFER_SIZE: usize = 64 * 1024;

/// Number of sectors per write operation
const SECTORS_PER_WRITE: u32 = (DISK_WRITE_BUFFER_SIZE / 512) as u32;

/// Static buffer for accumulating data before disk write
static mut DISK_WRITE_BUFFER: [u8; DISK_WRITE_BUFFER_SIZE] = [0u8; DISK_WRITE_BUFFER_SIZE];

/// Current fill level of write buffer
static mut DISK_WRITE_BUFFER_FILL: usize = 0;

/// Next sector to write to
static mut DISK_NEXT_SECTOR: u64 = 0;

/// Actual start sector (after finding free space)
static mut ACTUAL_START_SECTOR: u64 = 0;

/// Total bytes written to disk
static mut DISK_TOTAL_BYTES: u64 = 0;

/// Next request ID for block driver
static mut DISK_NEXT_REQUEST_ID: u32 = 1;

/// Main bare-metal entry point.
///
/// This function:
/// 1. Validates the BootHandoff
/// 2. Initializes VirtIO-net driver
/// 3. Creates smoltcp interface
/// 4. Runs DHCP to get IP
/// 5. Downloads ISO via HTTP
/// 6. Writes ISO to VirtIO-blk disk
///
/// # Safety
/// Must be called after ExitBootServices with valid BootHandoff.
///
/// # Returns
/// Never returns on success (halts after completion).
/// Returns error on failure.
#[cfg(target_arch = "x86_64")]
pub unsafe fn bare_metal_main(handoff: &'static BootHandoff, config: BareMetalConfig) -> RunResult {
    serial_println("=====================================");
    serial_println("  MorpheusX Post-EBS Network Stack");
    serial_println("=====================================");
    serial_println("");

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 1: VERIFY HEAP ALLOCATOR
    // ═══════════════════════════════════════════════════════════════════════
    // Heap should already be initialized by bootloader's efi_main
    // Call init_heap() anyway - it's safe to call multiple times
    crate::alloc_heap::init_heap();
    if crate::alloc_heap::is_initialized() {
        serial_println("[OK] Heap allocator ready (1MB)");
    } else {
        serial_println("[FAIL] Heap allocator not initialized!");
        return RunResult::InitFailed;
    }

    serial_println("[INIT] Validating BootHandoff...");

    if let Err(e) = handoff.validate() {
        serial_println("[FAIL] BootHandoff validation failed");
        return RunResult::InitFailed;
    }
    serial_println("[OK] BootHandoff valid");

    serial_print("[INIT] TSC frequency: ");
    serial_print_hex(handoff.tsc_freq);
    serial_println(" Hz");

    serial_print("[INIT] DMA region: ");
    serial_print_hex(handoff.dma_cpu_ptr);
    serial_print(" - ");
    serial_print_hex(handoff.dma_cpu_ptr + handoff.dma_size);
    serial_println("");

    // Create timeout config
    let timeouts = TimeoutConfig::new(handoff.tsc_freq);
    let loop_config = MainLoopConfig::new(handoff.tsc_freq);

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 2: INITIALIZE NETWORK DEVICE
    // ═══════════════════════════════════════════════════════════════════════
    serial_println("[INIT] Creating VirtIO config...");

    // Create VirtIO config from handoff data
    let virtio_config = VirtioConfig {
        dma_cpu_base: handoff.dma_cpu_ptr as *mut u8,
        dma_bus_base: handoff.dma_cpu_ptr, // In identity-mapped post-EBS, bus=physical=virtual
        dma_size: handoff.dma_size as usize,
        queue_size: VirtioConfig::DEFAULT_QUEUE_SIZE,
        buffer_size: VirtioConfig::DEFAULT_BUFFER_SIZE,
    };

    // Determine transport type from handoff
    serial_print("[INIT] Transport type: ");
    let transport = match handoff.nic_transport_type {
        TRANSPORT_PCI_MODERN => {
            serial_println("PCI Modern");
            serial_print("[INIT] Common cfg: ");
            serial_print_hex(handoff.nic_common_cfg);
            serial_println("");
            serial_print("[INIT] Notify cfg: ");
            serial_print_hex(handoff.nic_notify_cfg);
            serial_println("");
            serial_print("[INIT] Device cfg: ");
            serial_print_hex(handoff.nic_device_cfg);
            serial_println("");
            serial_print("[INIT] Notify off multiplier: ");
            serial_print_decimal(handoff.nic_notify_off_multiplier);
            serial_println("");

            VirtioTransport::pci_modern(PciModernConfig {
                common_cfg: handoff.nic_common_cfg,
                notify_cfg: handoff.nic_notify_cfg,
                notify_off_multiplier: handoff.nic_notify_off_multiplier,
                isr_cfg: handoff.nic_isr_cfg,
                device_cfg: handoff.nic_device_cfg,
                pci_cfg: 0, // Not used for now
            })
        }
        TRANSPORT_MMIO => {
            serial_println("MMIO");
            serial_print("[INIT] MMIO base: ");
            serial_print_hex(handoff.nic_mmio_base);
            serial_println("");
            VirtioTransport::mmio(handoff.nic_mmio_base)
        }
        _ => {
            serial_println("Unknown (defaulting to MMIO)");
            serial_print("[INIT] NIC MMIO base: ");
            serial_print_hex(handoff.nic_mmio_base);
            serial_println("");
            VirtioTransport::mmio(handoff.nic_mmio_base)
        }
    };

    serial_println("[INIT] Initializing VirtIO-net driver...");

    let mut driver =
        match VirtioNetDriver::new_with_transport(transport, virtio_config, handoff.tsc_freq) {
            Ok(d) => {
                serial_println("[OK] VirtIO driver initialized");
                d
            }
            Err(e) => {
                serial_print("[FAIL] VirtIO init error: ");
                match e {
                    VirtioInitError::ResetTimeout => serial_println("reset timeout"),
                    VirtioInitError::FeatureNegotiationFailed => {
                        serial_println("feature negotiation failed")
                    }
                    VirtioInitError::FeaturesRejected => {
                        serial_println("features rejected by device")
                    }
                    VirtioInitError::QueueSetupFailed => serial_println("queue setup failed"),
                    VirtioInitError::RxPrefillFailed(_) => serial_println("RX prefill failed"),
                    VirtioInitError::DeviceError => serial_println("device error"),
                }
                return RunResult::InitFailed;
            }
        };

    // Print real MAC address from driver
    serial_print("[INIT] MAC address: ");
    let mac = driver.mac_address();
    for (i, byte) in mac.iter().enumerate() {
        if i > 0 {
            serial_print(":");
        }
        let hi = byte >> 4;
        let lo = byte & 0xF;
        unsafe {
            serial_write_byte(if hi < 10 { b'0' + hi } else { b'a' + hi - 10 });
            serial_write_byte(if lo < 10 { b'0' + lo } else { b'a' + lo - 10 });
        }
    }
    serial_println("");

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 2.5: INITIALIZE BLOCK DEVICE (VirtIO-blk)
    // ═══════════════════════════════════════════════════════════════════════
    let mut blk_driver: Option<VirtioBlkDriver> = None;

    if config.write_to_disk && handoff.has_block_device() {
        serial_println("[INIT] Initializing VirtIO-blk driver...");
        serial_print("[INIT] Block MMIO base: ");
        serial_print_hex(handoff.blk_mmio_base);
        serial_println("");
        serial_print("[INIT] Block sector size: ");
        serial_print_decimal(handoff.blk_sector_size);
        serial_println("");
        serial_print("[INIT] Block total sectors: ");
        serial_print_hex(handoff.blk_total_sectors);
        serial_println("");

        // Calculate DMA region for block device
        // Use second half of DMA region (first half is for network)
        let blk_dma_offset = handoff.dma_size / 2;
        let blk_dma_base = handoff.dma_cpu_ptr + blk_dma_offset;

        // VirtIO-blk queue layout:
        // - Descriptors: 32 * 16 = 512 bytes
        // - Avail ring: 4 + 32*2 + 2 = 70 bytes (pad to 512)
        // - Used ring: 4 + 32*8 + 2 = 262 bytes (pad to 512)
        // - Headers: 32 * 16 = 512 bytes (one header per desc set)
        // - Status: 32 bytes (one per desc set)
        // - Data buffers: 32 * 64KB = 2MB (for larger writes)

        let blk_config = VirtioBlkConfig {
            queue_size: 32,
            desc_phys: blk_dma_base,
            avail_phys: blk_dma_base + 512,
            used_phys: blk_dma_base + 1024,
            headers_phys: blk_dma_base + 2048,
            status_phys: blk_dma_base + 2048 + 512,
            headers_cpu: blk_dma_base + 2048,
            status_cpu: blk_dma_base + 2048 + 512,
            notify_addr: handoff.blk_mmio_base + 0x50, // Fallback for MMIO, computed for PCI Modern
            transport_type: handoff.blk_transport_type,
        };

        // Create driver based on transport type
        let driver_result = if handoff.blk_transport_type == TRANSPORT_PCI_MODERN {
            serial_println("[INIT] Using PCI Modern transport for VirtIO-blk");
            serial_print("[INIT] common_cfg: ");
            serial_print_hex(handoff.blk_common_cfg);
            serial_println("");
            serial_print("[INIT] notify_cfg: ");
            serial_print_hex(handoff.blk_notify_cfg);
            serial_println("");
            serial_print("[INIT] device_cfg: ");
            serial_print_hex(handoff.blk_device_cfg);
            serial_println("");

            // Build PCI Modern transport config
            let pci_config = PciModernConfig {
                common_cfg: handoff.blk_common_cfg,
                notify_cfg: handoff.blk_notify_cfg,
                notify_off_multiplier: handoff.blk_notify_off_multiplier,
                isr_cfg: handoff.blk_isr_cfg,
                device_cfg: handoff.blk_device_cfg,
                pci_cfg: 0, // Not used
            };
            let transport = VirtioTransport::pci_modern(pci_config);

            unsafe { VirtioBlkDriver::new_with_transport(transport, blk_config, handoff.tsc_freq) }
        } else {
            serial_println("[INIT] Using MMIO transport for VirtIO-blk");
            unsafe { VirtioBlkDriver::new(handoff.blk_mmio_base, blk_config) }
        };

        match driver_result {
            Ok(mut d) => {
                let info = d.info();
                serial_println("[OK] VirtIO-blk driver initialized");
                serial_print("[OK] Disk capacity: ");
                let total_bytes = info.total_sectors * info.sector_size as u64;
                if total_bytes >= 1024 * 1024 * 1024 {
                    serial_print_decimal((total_bytes / (1024 * 1024 * 1024)) as u32);
                    serial_println(" GB");
                } else {
                    serial_print_decimal((total_bytes / (1024 * 1024)) as u32);
                    serial_println(" MB");
                }

                // CRITICAL: Find free space on disk to avoid overwriting existing partitions
                serial_println("[INIT] Scanning GPT for existing partitions...");
                let actual_start_sector = {
                    let dma_buffer = core::slice::from_raw_parts_mut(
                        (&raw mut DISK_WRITE_BUFFER).cast::<u8>(),
                        DISK_WRITE_BUFFER_SIZE,
                    );
                    let dma_buffer_phys = (&raw const DISK_WRITE_BUFFER).cast::<u8>() as u64;
                    let timeout_ticks = 100_000_000u64;

                    match VirtioBlkBlockIo::new(&mut d, dma_buffer, dma_buffer_phys, timeout_ticks)
                    {
                        Ok(mut adapter) => {
                            match crate::transfer::disk::GptOps::find_free_space(&mut adapter) {
                                Ok((free_start, free_end)) => {
                                    let free_size = free_end - free_start + 1;
                                    serial_print("[GPT] Free space found: sectors ");
                                    serial_print_hex(free_start);
                                    serial_print(" - ");
                                    serial_print_hex(free_end);
                                    serial_print(" (");
                                    serial_print_decimal(
                                        (free_size * 512 / (1024 * 1024 * 1024)) as u32,
                                    );
                                    serial_println(" GB)");

                                    // Align to 1MB boundary for performance
                                    let aligned_start = ((free_start + 2047) / 2048) * 2048;
                                    serial_print("[GPT] Using aligned start sector: ");
                                    serial_print_hex(aligned_start);
                                    serial_println("");
                                    aligned_start
                                }
                                Err(e) => {
                                    serial_print("[GPT] WARNING: Could not find free space: ");
                                    serial_println(match e {
                                        crate::transfer::disk::DiskError::IoError => "IO error",
                                        crate::transfer::disk::DiskError::InvalidGpt => {
                                            "Invalid GPT"
                                        }
                                        crate::transfer::disk::DiskError::NoFreeSpace => {
                                            "No free space"
                                        }
                                        _ => "Unknown error",
                                    });
                                    serial_println(
                                        "[GPT] Falling back to config sector (may overlap!)",
                                    );
                                    config.target_start_sector
                                }
                            }
                        }
                        Err(_) => {
                            serial_println("[GPT] WARNING: Could not create BlockIo adapter");
                            serial_println("[GPT] Falling back to config sector (may overlap!)");
                            config.target_start_sector
                        }
                    }
                };

                serial_print("[INIT] ISO data will be written starting at sector: ");
                serial_print_hex(actual_start_sector);
                serial_println("");

                // Create GPT partition for ISO data BEFORE we start writing
                // This properly claims the disk space so other tools won't overwrite it
                serial_println("[INIT] Creating GPT partition for ISO storage...");
                if let Some(part_uuid) = create_iso_partition(
                    &mut d,
                    actual_start_sector,
                    config.max_download_size,
                    config.iso_name,
                ) {
                    serial_println("[OK] ISO partition created and claimed in GPT");
                    // Store partition UUID for manifest
                    // config.partition_uuid = part_uuid; // TODO: make config mutable or use separate storage
                } else {
                    serial_println(
                        "[WARN] Could not create GPT partition - ISO data may be overwritten!",
                    );
                    serial_println("[WARN] Continuing anyway (data will be in unmapped space)");
                }

                // Initialize disk write state using the actual (possibly updated) start sector
                DISK_NEXT_SECTOR = actual_start_sector;
                DISK_WRITE_BUFFER_FILL = 0;
                DISK_TOTAL_BYTES = 0;
                DISK_NEXT_REQUEST_ID = 1;

                // Store actual start sector for manifest
                ACTUAL_START_SECTOR = actual_start_sector;

                blk_driver = Some(d);
            }
            Err(e) => {
                serial_print("[WARN] VirtIO-blk init failed: ");
                match e {
                    VirtioBlkInitError::ResetFailed => serial_println("reset failed"),
                    VirtioBlkInitError::FeatureNegotiationFailed => {
                        serial_println("feature negotiation failed")
                    }
                    VirtioBlkInitError::QueueSetupFailed => serial_println("queue setup failed"),
                    VirtioBlkInitError::DeviceFailed => serial_println("device error"),
                    VirtioBlkInitError::InvalidConfig => serial_println("invalid config"),
                    VirtioBlkInitError::TransportError => serial_println("transport error"),
                }
                serial_println("[WARN] Continuing without disk write support");
            }
        }
    } else if config.write_to_disk {
        serial_println("[WARN] No block device in handoff - disk writes disabled");
    } else {
        serial_println("[INFO] Disk writes disabled by config");
    }

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 3: CREATE SMOLTCP INTERFACE
    // ═══════════════════════════════════════════════════════════════════════
    serial_println("[INIT] Creating smoltcp interface...");

    // Use the MAC address from the driver
    let mac = EthernetAddress(driver.mac_address());
    let hw_addr = HardwareAddress::Ethernet(mac);

    // Create smoltcp config
    let mut iface_config = Config::new(hw_addr);
    iface_config.random_seed = handoff.tsc_freq; // Use TSC frequency as random seed

    // Create the device adapter wrapping our VirtIO driver
    let mut adapter = SmoltcpAdapter::new(&mut driver);

    // Create smoltcp interface
    let mut iface = Interface::new(iface_config, &mut adapter, Instant::from_millis(0));

    // Set up initial IP config (DHCP will configure this later)
    iface.update_ip_addrs(|addrs| {
        // Start with empty - DHCP will fill this
    });

    serial_println("[OK] smoltcp interface created");

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 4: DHCP
    // ═══════════════════════════════════════════════════════════════════════
    serial_println("[NET] Starting DHCP discovery...");

    // Create socket storage
    let mut socket_storage: [SocketStorage; 8] = Default::default();
    let mut sockets = SocketSet::new(&mut socket_storage[..]);

    // Create and add DHCP socket
    let dhcp_socket = Dhcpv4Socket::new();
    let dhcp_handle = sockets.add(dhcp_socket);

    let dhcp_start = get_tsc();
    let dhcp_timeout_ticks = timeouts.dhcp();

    // Track if we got an IP
    #[allow(unused_assignments)]
    let mut got_ip = false;
    #[allow(unused_assignments)]
    let mut our_ip = Ipv4Address::UNSPECIFIED;
    #[allow(unused_assignments)]
    let mut gateway_ip = Ipv4Address::UNSPECIFIED;
    let mut dns_ip = Ipv4Address::UNSPECIFIED;

    // DHCP polling loop
    serial_println("[NET] Sending DHCP DISCOVER...");

    loop {
        let now_tsc = get_tsc();

        // Check timeout
        if now_tsc.wrapping_sub(dhcp_start) > dhcp_timeout_ticks {
            serial_println("[FAIL] DHCP timeout");
            return RunResult::DhcpTimeout;
        }

        // Convert TSC to smoltcp Instant
        let timestamp = tsc_to_instant(now_tsc, handoff.tsc_freq);

        // Phase 1: Refill RX queue
        adapter.refill_rx();

        // Phase 2: Poll smoltcp interface (EXACTLY ONCE per iteration)
        enter_poll(); // Reentrancy guard
        let poll_result = iface.poll(timestamp, &mut adapter, &mut sockets);
        exit_poll(); // Reentrancy guard

        // Check for DHCP events
        let dhcp_socket = sockets.get_mut::<Dhcpv4Socket>(dhcp_handle);
        if let Some(event) = dhcp_socket.poll() {
            match event {
                Dhcpv4Event::Configured(dhcp_config) => {
                    serial_println("[NET] Received DHCP ACK");

                    // Apply the configuration
                    our_ip = dhcp_config.address.address();

                    // Print IP address
                    serial_print("[OK] IP address: ");
                    print_ipv4(our_ip);
                    serial_println("");

                    // Apply IP to interface
                    iface.update_ip_addrs(|addrs| {
                        // Clear existing and add new
                        addrs.clear();
                        addrs.push(IpCidr::Ipv4(dhcp_config.address)).ok();
                    });

                    // Set gateway
                    #[allow(unused_assignments)]
                    if let Some(router) = dhcp_config.router {
                        gateway_ip = router;
                        iface.routes_mut().add_default_ipv4_route(router).ok();
                        serial_print("[OK] Gateway: ");
                        print_ipv4(router);
                        serial_println("");
                    }

                    // Set DNS (if provided)
                    if let Some(dns) = dhcp_config.dns_servers.get(0) {
                        dns_ip = *dns;
                        serial_print("[OK] DNS: ");
                        print_ipv4(*dns);
                        serial_println("");
                    }

                    got_ip = true;
                    break;
                }
                Dhcpv4Event::Deconfigured => {
                    serial_println("[NET] DHCP deconfigured");
                }
            }
        }

        // Phase 5: Collect TX completions
        adapter.collect_tx();

        // Brief yield (don't spin too tight)
        for _ in 0..100 {
            core::hint::spin_loop();
        }
    }

    if !got_ip {
        serial_println("[FAIL] DHCP did not obtain IP");
        return RunResult::DhcpTimeout;
    }

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 5: HTTP DOWNLOAD - NO HEAP ALLOCATION VERSION
    // ═══════════════════════════════════════════════════════════════════════
    serial_print("[HTTP] Downloading from: ");
    serial_println(config.iso_url);

    // Parse URL without heap allocation
    // Format: http://host[:port]/path
    let url_str = config.iso_url;

    // Check scheme
    if url_str.starts_with("https://") {
        serial_println("[FAIL] HTTPS not supported in bare-metal mode");
        return RunResult::DownloadFailed;
    }

    let rest = if let Some(r) = url_str.strip_prefix("http://") {
        r
    } else {
        serial_println("[FAIL] Invalid URL scheme (must be http://)");
        return RunResult::DownloadFailed;
    };

    // Split host[:port] from path
    let (authority, path) = match rest.find('/') {
        Some(idx) => (&rest[..idx], &rest[idx..]),
        None => (rest, "/"),
    };

    // Parse host and port from authority
    let (host_str, server_port): (&str, u16) = if let Some(colon_idx) = authority.rfind(':') {
        let h = &authority[..colon_idx];
        let p = &authority[colon_idx + 1..];
        match parse_u16(p) {
            Some(port) => (h, port),
            None => (authority, 80),
        }
    } else {
        (authority, 80)
    };

    serial_print("[HTTP] Host: ");
    serial_println(host_str);
    serial_print("[HTTP] Port: ");
    serial_print_decimal(server_port as u32);
    serial_println("");
    serial_print("[HTTP] Path: ");
    serial_println(path);

    // Parse host as IP address or do DNS resolution
    let server_ip = match parse_ipv4(host_str) {
        Some(ip) => {
            serial_print("[HTTP] Using IP: ");
            print_ipv4(ip);
            serial_println("");
            ip
        }
        None => {
            // Need DNS resolution
            serial_print("[HTTP] Resolving hostname: ");
            serial_println(host_str);

            if dns_ip == Ipv4Address::UNSPECIFIED {
                serial_println("[FAIL] No DNS server available");
                return RunResult::DownloadFailed;
            }

            // Create DNS socket with the DHCP-provided DNS server
            // Use static storage for DNS queries (smoltcp requires this)
            static mut DNS_QUERIES: [Option<smoltcp::socket::dns::DnsQuery>; 1] = [None];

            let dns_servers: &[IpAddress] = &[IpAddress::Ipv4(dns_ip)];
            let dns_socket = DnsSocket::new(dns_servers, unsafe { &mut DNS_QUERIES[..] });
            let dns_handle = sockets.add(dns_socket);

            // Start DNS query
            let query_handle = {
                let dns = sockets.get_mut::<DnsSocket>(dns_handle);
                match dns.start_query(iface.context(), host_str, DnsQueryType::A) {
                    Ok(h) => h,
                    Err(_) => {
                        serial_println("[FAIL] DNS query start failed");
                        return RunResult::DownloadFailed;
                    }
                }
            };

            serial_println("[DNS] Query started, waiting for response...");

            // Poll until we get DNS response
            let dns_start = get_tsc();
            let dns_timeout = timeouts.tcp_connect(); // Use same timeout as TCP

            let resolved_ip = loop {
                let now_tsc = get_tsc();
                if now_tsc.wrapping_sub(dns_start) > dns_timeout {
                    serial_println("[FAIL] DNS timeout");
                    return RunResult::DownloadFailed;
                }

                let timestamp = tsc_to_instant(now_tsc, handoff.tsc_freq);
                adapter.refill_rx();
                iface.poll(timestamp, &mut adapter, &mut sockets);
                adapter.collect_tx();

                let dns = sockets.get_mut::<DnsSocket>(dns_handle);
                match dns.get_query_result(query_handle) {
                    Ok(addrs) => {
                        // Find first IPv4 address
                        let mut found_ip = None;
                        for addr in addrs {
                            let IpAddress::Ipv4(v4) = addr;
                            found_ip = Some(v4);
                            break;
                        }
                        match found_ip {
                            Some(ip) => break ip,
                            None => {
                                serial_println("[FAIL] DNS response has no IPv4 address");
                                return RunResult::DownloadFailed;
                            }
                        }
                    }
                    Err(GetQueryResultError::Pending) => {
                        // Still waiting, continue polling
                        for _ in 0..100 {
                            core::hint::spin_loop();
                        }
                    }
                    Err(GetQueryResultError::Failed) => {
                        serial_println("[FAIL] DNS query failed");
                        return RunResult::DownloadFailed;
                    }
                }
            };

            serial_print("[OK] DNS resolved: ");
            print_ipv4(resolved_ip);
            serial_println("");
            resolved_ip
        }
    };

    serial_print("[HTTP] Connecting to ");
    print_ipv4(server_ip);
    serial_print(":");
    serial_print_decimal(server_port as u32);
    serial_println("...");

    // Create TCP socket with STATIC buffers (no heap!)
    // Large buffers critical for throughput - 128KB RX allows TCP window scaling
    static mut TCP_RX_STORAGE: [u8; 131072] = [0u8; 131072]; // 128KB RX
    static mut TCP_TX_STORAGE: [u8; 65536] = [0u8; 65536]; // 64KB TX

    let tcp_rx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_RX_STORAGE[..] });
    let tcp_tx_buffer = TcpSocketBuffer::new(unsafe { &mut TCP_TX_STORAGE[..] });
    let mut tcp_socket = TcpSocket::new(tcp_rx_buffer, tcp_tx_buffer);

    // === THROUGHPUT OPTIMIZATIONS ===
    // Disable Nagle's algorithm - we're doing bulk download, Nagle adds latency
    // for small packets but we want ACKs to flow immediately
    tcp_socket.set_nagle_enabled(false);

    // Disable delayed ACKs - send ACKs immediately to keep sender's window open
    // Default is 10ms delay which can throttle high-throughput downloads
    tcp_socket.set_ack_delay(None);

    // Connect to server
    let local_port = 49152 + ((get_tsc() % 16384) as u16); // Random ephemeral port
    let remote_endpoint = (smoltcp::wire::IpAddress::Ipv4(server_ip), server_port);

    if tcp_socket
        .connect(iface.context(), remote_endpoint, local_port)
        .is_err()
    {
        serial_println("[FAIL] TCP connect failed to initiate");
        return RunResult::DownloadFailed;
    }

    let tcp_handle = sockets.add(tcp_socket);

    // Wait for connection to establish
    let connect_start = get_tsc();
    let connect_timeout = timeouts.tcp_connect();

    loop {
        let now_tsc = get_tsc();
        if now_tsc.wrapping_sub(connect_start) > connect_timeout {
            serial_println("[FAIL] TCP connect timeout");
            return RunResult::DownloadFailed;
        }

        let timestamp = tsc_to_instant(now_tsc, handoff.tsc_freq);
        adapter.refill_rx();
        iface.poll(timestamp, &mut adapter, &mut sockets);
        adapter.collect_tx();

        let socket = sockets.get_mut::<TcpSocket>(tcp_handle);
        if socket.may_send() {
            serial_println("[OK] TCP connected");
            break;
        }

        if !socket.is_open() {
            serial_println("[FAIL] TCP connection refused");
            return RunResult::DownloadFailed;
        }
        // No artificial delay - tight poll loop for throughput
    }

    // Build and send HTTP GET request (NO HEAP!)
    serial_println("[HTTP] Sending GET request...");
    serial_print("[HTTP] GET ");
    serial_println(path);

    // Build HTTP request in static buffer
    static mut HTTP_REQUEST_BUF: [u8; 1024] = [0u8; 1024];
    let http_request_slice =
        unsafe { core::slice::from_raw_parts_mut((&raw mut HTTP_REQUEST_BUF).cast::<u8>(), 1024) };
    let request_len = match format_http_get(http_request_slice, path, host_str) {
        Some(len) => len,
        None => {
            serial_println("[FAIL] HTTP request too large for buffer");
            return RunResult::DownloadFailed;
        }
    };

    {
        let socket = sockets.get_mut::<TcpSocket>(tcp_handle);
        if socket
            .send_slice(&http_request_slice[..request_len])
            .is_err()
        {
            serial_println("[FAIL] Failed to send HTTP request");
            return RunResult::DownloadFailed;
        }
    }

    // Poll to send the request (may need multiple polls for large requests)
    let send_start = get_tsc();
    let send_timeout = timeouts.http_send();

    loop {
        let now_tsc = get_tsc();
        if now_tsc.wrapping_sub(send_start) > send_timeout {
            serial_println("[FAIL] HTTP send timeout");
            return RunResult::DownloadFailed;
        }

        let timestamp = tsc_to_instant(now_tsc, handoff.tsc_freq);
        adapter.refill_rx();
        iface.poll(timestamp, &mut adapter, &mut sockets);
        adapter.collect_tx();

        // Check if request has been sent (TX buffer drained)
        let socket = sockets.get_mut::<TcpSocket>(tcp_handle);
        if socket.send_queue() == 0 {
            serial_println("[HTTP] Request sent");
            break;
        }

        if !socket.is_open() {
            serial_println("[FAIL] Connection closed during send");
            return RunResult::DownloadFailed;
        }
        // No artificial delay - tight poll loop for throughput
    }

    // Receive response
    serial_println("[HTTP] Receiving response...");

    let mut total_received: usize = 0;
    let mut headers_done = false;
    let mut content_length: Option<usize> = None;
    let mut body_received: usize = 0;
    let mut http_status: Option<u16> = None;

    // Static buffer for headers (no heap!)
    static mut HEADER_BUFFER: [u8; 16384] = [0u8; 16384];
    // Create slice once with raw pointer - avoids repeated mutable reference warnings
    let header_buffer =
        unsafe { core::slice::from_raw_parts_mut((&raw mut HEADER_BUFFER).cast::<u8>(), 16384) };
    let mut header_len: usize = 0;
    let mut last_progress_kb: usize = 0;

    let recv_start = get_tsc();
    let mut last_activity = recv_start;
    let recv_timeout = handoff.tsc_freq * 300; // 5 minute timeout for large downloads
    let idle_timeout = handoff.tsc_freq * 30; // 30 second idle timeout

    loop {
        let now_tsc = get_tsc();

        // Check total timeout
        if now_tsc.wrapping_sub(recv_start) > recv_timeout {
            serial_println("[FAIL] Download timeout (total time exceeded)");
            return RunResult::DownloadFailed;
        }

        // Check idle timeout (no data received for too long)
        if now_tsc.wrapping_sub(last_activity) > idle_timeout && headers_done {
            serial_println("[FAIL] Download timeout (connection stalled)");
            return RunResult::DownloadFailed;
        }

        // === POLL-DRIVEN RECEIVE LOOP ===
        // smoltcp is entirely poll-based: it won't process packets, send ACKs,
        // or advance TCP state without poll(). We must poll frequently to keep
        // ACKs flowing and prevent sender window stall.
        let timestamp = tsc_to_instant(now_tsc, handoff.tsc_freq);

        // Phase 1: Refill RX buffers so device can receive more packets
        adapter.refill_rx();

        // Phase 2: Poll smoltcp - processes incoming packets, generates ACKs
        iface.poll(timestamp, &mut adapter, &mut sockets);

        // Phase 3: Collect TX completions and notify device of pending TX
        adapter.collect_tx();

        // Phase 4: Try to receive data from socket
        let mut buf = [0u8; 32768];
        let socket = sockets.get_mut::<TcpSocket>(tcp_handle);

        if socket.can_recv() {
            match socket.recv_slice(&mut buf) {
                Ok(len) if len > 0 => {
                    total_received += len;
                    last_activity = now_tsc;

                    if !headers_done {
                        // Accumulate header data in static buffer
                        let space_left = header_buffer.len() - header_len;

                        if len > space_left {
                            serial_println("[FAIL] HTTP headers too large");
                            return RunResult::DownloadFailed;
                        }

                        header_buffer[header_len..header_len + len].copy_from_slice(&buf[..len]);
                        header_len += len;

                        // Look for end of headers
                        if let Some(pos) = find_header_end(&header_buffer[..header_len]) {
                            headers_done = true;
                            serial_println("[HTTP] Headers received");

                            // Parse HTTP status line (NO HEAP!)
                            // Format: "HTTP/1.1 200 OK\r\n"
                            let header_str =
                                core::str::from_utf8(&header_buffer[..pos]).unwrap_or("");

                            // Find first line (status line)
                            if let Some(first_line_end) = header_str.find('\r') {
                                let status_line = &header_str[..first_line_end];

                                // Parse status code manually (avoid split().collect())
                                // Find "HTTP/x.x " prefix, then parse number
                                if let Some(space_after_http) = status_line.find(' ') {
                                    let after_http = &status_line[space_after_http + 1..];
                                    // Find the status code (3 digits)
                                    let status_end =
                                        after_http.find(' ').unwrap_or(after_http.len());
                                    let status_str = &after_http[..status_end];

                                    if let Some(status) = parse_u16(status_str) {
                                        http_status = Some(status);
                                        serial_print("[HTTP] Status: ");
                                        serial_print_decimal(status as u32);
                                        if status_end < after_http.len() {
                                            serial_print(" ");
                                            serial_println(&after_http[status_end + 1..]);
                                        } else {
                                            serial_println("");
                                        }

                                        // Check for HTTP errors
                                        if status >= 400 {
                                            serial_print("[FAIL] HTTP error: ");
                                            serial_print_decimal(status as u32);
                                            serial_println("");
                                            return RunResult::DownloadFailed;
                                        }

                                        // Handle redirects (3xx)
                                        if status >= 300 && status < 400 {
                                            serial_println("[WARN] HTTP redirect - not following");
                                        }
                                    }
                                }
                            }

                            // Parse headers - look for Content-Length (case-insensitive, NO HEAP!)
                            for line in header_str.lines().skip(1) {
                                // Case-insensitive comparison without allocation
                                if starts_with_ignore_case(line, "content-length:") {
                                    // Find the ':' and parse the number after it
                                    if let Some(colon_pos) = line.find(':') {
                                        let value_str = line[colon_pos + 1..].trim();
                                        if let Some(len) = parse_usize(value_str) {
                                            content_length = Some(len);
                                            serial_print("[HTTP] Content-Length: ");
                                            // Print in human readable format
                                            if len >= 1024 * 1024 * 1024 {
                                                serial_print_decimal(
                                                    (len / (1024 * 1024 * 1024)) as u32,
                                                );
                                                serial_println(" GB");
                                            } else if len >= 1024 * 1024 {
                                                serial_print_decimal((len / (1024 * 1024)) as u32);
                                                serial_println(" MB");
                                            } else if len >= 1024 {
                                                serial_print_decimal((len / 1024) as u32);
                                                serial_println(" KB");
                                            } else {
                                                serial_print_decimal(len as u32);
                                                serial_println(" bytes");
                                            }
                                        }
                                    }
                                } else if starts_with_ignore_case(line, "content-type:") {
                                    if let Some(colon_pos) = line.find(':') {
                                        let value = line[colon_pos + 1..].trim();
                                        serial_print("[HTTP] Content-Type: ");
                                        serial_println(value);
                                    }
                                } else if starts_with_ignore_case(line, "transfer-encoding:") {
                                    if contains_ignore_case(line, "chunked") {
                                        serial_println("[HTTP] Transfer-Encoding: chunked");
                                        // NOTE: Chunked encoding would need special handling
                                    }
                                }
                            }

                            // Body starts after \r\n\r\n
                            let body_start = pos + 4;
                            if header_len > body_start {
                                let initial_body = &header_buffer[body_start..header_len];
                                body_received = initial_body.len();

                                // Write initial body data to disk if enabled
                                if let Some(ref mut blk) = blk_driver {
                                    let written = buffer_disk_write(blk, initial_body);
                                    if written != initial_body.len() {
                                        serial_println(
                                            "[WARN] Failed to write initial body to disk",
                                        );
                                    }
                                }
                            }

                            serial_println("[HTTP] Streaming body...");
                        }
                    } else {
                        body_received += len;

                        // Write received data to disk if enabled
                        if let Some(ref mut blk) = blk_driver {
                            let written = buffer_disk_write(blk, &buf[..len]);
                            if written != len {
                                serial_println("[WARN] Incomplete disk write");
                            }
                        }

                        // Print progress every 1MB with inline progress bar
                        let current_mb = body_received / (1024 * 1024);
                        let last_mb = last_progress_kb / 1024; // Reuse variable as MB tracker
                        if current_mb > last_mb {
                            last_progress_kb = current_mb * 1024; // Update tracker

                            // Carriage return to update in place
                            serial_print("\r[");

                            // Progress bar (20 chars wide)
                            if let Some(cl) = content_length {
                                let percent = ((body_received as u64 * 100) / cl as u64) as usize;
                                let filled = percent / 5; // 20 chars = 5% each
                                for i in 0..20 {
                                    if i < filled {
                                        serial_print("=");
                                    } else if i == filled {
                                        serial_print(">");
                                    } else {
                                        serial_print(" ");
                                    }
                                }
                                serial_print("] ");
                                serial_print_decimal(percent as u32);
                                serial_print("% ");
                            } else {
                                serial_print("====================] ");
                            }

                            // Size in MB
                            serial_print_decimal(current_mb as u32);
                            serial_print(" MB");

                            // Speed estimate if we have content-length
                            if let Some(cl) = content_length {
                                serial_print(" / ");
                                serial_print_decimal((cl / (1024 * 1024)) as u32);
                                serial_print(" MB");
                            }

                            serial_print("   "); // Padding to clear old chars
                        }
                    }
                }
                _ => {} // No data this iteration, will poll again
            }
        }

        // Check if download complete
        let socket = sockets.get_mut::<TcpSocket>(tcp_handle);
        if headers_done {
            if let Some(cl) = content_length {
                if body_received >= cl {
                    serial_println("\n[HTTP] Download complete");
                    break;
                }
            }

            // Also check if connection closed
            if !socket.is_open() && socket.recv_queue() == 0 {
                if content_length.is_none() {
                    // No content-length, server closed = complete
                    serial_println("\n[HTTP] Download complete (connection closed)");
                } else if content_length.is_some() && body_received < content_length.unwrap() {
                    // Had content-length but didn't get all data
                    serial_println("\n[WARN] Connection closed before full content received");
                }
                break;
            }
        }
        // Loop continues - poll again next iteration
    }

    // Print download summary
    serial_println("");
    serial_println("=== DOWNLOAD SUMMARY ===");
    serial_print("[HTTP] Total headers + body: ");
    if total_received >= 1024 * 1024 {
        serial_print_decimal((total_received / (1024 * 1024)) as u32);
        serial_println(" MB");
    } else {
        serial_print_decimal((total_received / 1024) as u32);
        serial_println(" KB");
    }
    serial_print("[HTTP] Body only: ");
    if body_received >= 1024 * 1024 {
        serial_print_decimal((body_received / (1024 * 1024)) as u32);
        serial_println(" MB");
    } else {
        serial_print_decimal((body_received / 1024) as u32);
        serial_println(" KB");
    }
    if let Some(status) = http_status {
        serial_print("[HTTP] Final status: ");
        serial_print_decimal(status as u32);
        serial_println("");
    }

    // Verify we got what we expected
    if let Some(cl) = content_length {
        if body_received >= cl {
            serial_println("[OK] Download verified: received >= Content-Length");
        } else {
            serial_print("[WARN] Incomplete: received ");
            serial_print_decimal(body_received as u32);
            serial_print(" of ");
            serial_print_decimal(cl as u32);
            serial_println(" bytes");
        }
    }
    serial_println("");

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 6: FINALIZE DISK WRITE
    // ═══════════════════════════════════════════════════════════════════════
    if let Some(ref mut blk) = blk_driver {
        serial_println("[DISK] Flushing remaining data to disk...");

        // Flush any remaining buffered data
        if flush_remaining_disk_buffer(blk) {
            serial_println("[OK] Disk write finalized");
        } else {
            serial_println("[WARN] Final flush failed");
        }

        // Print disk write summary
        serial_println("");
        serial_println("=== DISK WRITE SUMMARY ===");
        serial_print("[DISK] Total bytes written: ");
        if DISK_TOTAL_BYTES >= 1024 * 1024 * 1024 {
            serial_print_decimal((DISK_TOTAL_BYTES / (1024 * 1024 * 1024)) as u32);
            serial_println(" GB");
        } else if DISK_TOTAL_BYTES >= 1024 * 1024 {
            serial_print_decimal((DISK_TOTAL_BYTES / (1024 * 1024)) as u32);
            serial_println(" MB");
        } else {
            serial_print_decimal((DISK_TOTAL_BYTES / 1024) as u32);
            serial_println(" KB");
        }
        serial_print("[DISK] Start sector: ");
        serial_print_decimal(config.target_start_sector as u32);
        serial_println("");
        serial_print("[DISK] End sector: ");
        serial_print_decimal(DISK_NEXT_SECTOR as u32);
        serial_println("");
        serial_print("[DISK] Sectors written: ");
        serial_print_decimal((DISK_NEXT_SECTOR - config.target_start_sector) as u32);
        serial_println("");

        // ═══════════════════════════════════════════════════════════════════
        // STEP 6.5: WRITE ISO MANIFEST
        // ═══════════════════════════════════════════════════════════════════
        // Write manifest so bootloader can discover this ISO on next boot
        if DISK_TOTAL_BYTES > 0 {
            if finalize_manifest(blk, &config, DISK_TOTAL_BYTES) {
                serial_println("[OK] ISO manifest written successfully");
            } else {
                serial_println("[WARN] Failed to write ISO manifest");
            }
        }

        // ═══════════════════════════════════════════════════════════════════
        // STEP 6.6: FINAL DISK SYNC
        // ═══════════════════════════════════════════════════════════════════
        // Flush VirtIO-blk write cache to ensure all data is persisted
        serial_println("[DISK] Syncing disk cache...");
        use crate::driver::block_traits::BlockDriver;
        match blk.flush() {
            Ok(()) => serial_println("[OK] Disk cache synced"),
            Err(e) => {
                serial_print("[WARN] Disk sync failed: ");
                serial_println(match e {
                    crate::driver::block_traits::BlockError::Unsupported => {
                        "not supported (assuming durable)"
                    }
                    crate::driver::block_traits::BlockError::Timeout => "timeout",
                    crate::driver::block_traits::BlockError::DeviceError => "device error",
                    _ => "unknown error",
                });
            }
        }
    } else {
        serial_println("[NOTE] Disk write disabled - data received but not persisted");
    }
    serial_println("");

    // ═══════════════════════════════════════════════════════════════════════
    // STEP 7: COMPLETE
    // ═══════════════════════════════════════════════════════════════════════
    serial_println("");
    serial_println("=====================================");
    serial_println("  ISO Download Complete!");
    serial_println("=====================================");
    serial_println("");
    serial_println("Ready to boot downloaded image.");
    serial_println("System halted.");

    // Halt
    loop {
        core::arch::asm!("hlt", options(nomem, nostack));
    }
}

#[cfg(not(target_arch = "x86_64"))]
pub unsafe fn bare_metal_main(
    _handoff: &'static BootHandoff,
    _config: BareMetalConfig,
) -> RunResult {
    RunResult::InitFailed
}

// ═══════════════════════════════════════════════════════════════════════════
// FULL INTEGRATED RUNNER (with real state machines)
// ═══════════════════════════════════════════════════════════════════════════

/// Full integrated main loop with real state machines.
///
/// This is the production implementation that uses:
/// - VirtioNetDevice for networking
/// - smoltcp for TCP/IP
/// - IsoDownloadState for orchestration
/// - DiskWriterState for streaming writes
#[cfg(target_arch = "x86_64")]
pub unsafe fn run_full_download<D: NetworkDriver>(
    device: &mut D,
    handoff: &'static BootHandoff,
    iso_url: Url,
) -> RunResult {
    serial_println("[MAIN] Starting full integrated download...");

    let timeouts = TimeoutConfig::new(handoff.tsc_freq);
    let loop_config = MainLoopConfig::new(handoff.tsc_freq);

    // Create download config
    let download_config = DownloadConfig::new(iso_url);

    // Create download state machine
    let mut download_state = IsoDownloadState::new(download_config);

    // Start download (no existing network config, will do DHCP)
    download_state.start(None, get_tsc());

    // Main loop
    let mut iteration = 0u64;
    loop {
        let iteration_start = get_tsc();

        // Phase 1: RX Refill
        phase1_rx_refill(device);

        // Phase 2: Would poll smoltcp here
        // let timestamp = tsc_to_instant(iteration_start, handoff.tsc_freq);
        // iface.poll(timestamp, device, &mut sockets);

        // Phase 3: TX drain (handled by smoltcp)

        // Phase 4: App state step
        // Note: This is simplified - real impl needs smoltcp socket integration
        // let result = download_state.step(...);

        // Phase 5: TX completions
        phase5_tx_completions(device);

        // Check timing
        let elapsed = get_tsc().wrapping_sub(iteration_start);
        if elapsed > loop_config.timing_warning_ticks {
            serial_println("[WARN] Iteration exceeded 5ms");
        }

        iteration += 1;

        // For demonstration, exit after some iterations
        if iteration > 1000 {
            break;
        }
    }

    RunResult::Success
}

#[cfg(not(target_arch = "x86_64"))]
pub unsafe fn run_full_download<D: NetworkDriver>(
    _device: &mut D,
    _handoff: &'static BootHandoff,
    _iso_url: Url,
) -> RunResult {
    RunResult::InitFailed
}

/// Convert TSC ticks to smoltcp Instant.
fn tsc_to_instant(tsc: u64, tsc_freq: u64) -> Instant {
    let ms = tsc / (tsc_freq / 1000);
    Instant::from_millis(ms as i64)
}

/// Find the end of HTTP headers (\r\n\r\n).
/// Returns the position of the first \r in \r\n\r\n.
fn find_header_end(data: &[u8]) -> Option<usize> {
    data.windows(4).position(|w| w == b"\r\n\r\n")
}