patina_dxe_core 21.2.0

A pure rust implementation of the UEFI DXE Core.
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
//! Memory Bin Manager
//!
//! Tracks memory bin regions for hibernate (S4) resume stability. A "memory bin" is
//! a pre-allocated address range for a specific EFI memory type whose size is defined
//! by the platform's Memory Type Information HOB.
//!
//! This module is responsible for:
//!
//! 1. HOB processing: Extracting bin configuration from the Memory Type Information
//!    GUID HOB and optionally consuming a pre-allocated bin region from a Resource
//!    Descriptor HOB produced by PEI.
//!
//! 2. GetMemoryMap "overlay": Post-processing the EFI memory map so that free
//!    (`EfiConventionalMemory`) pages within a bin region are reported as the bin's
//!    memory type.
//!
//! 3. Statistics and config table: Tracking per-type allocation counts and bin
//!    usage so BDS can recommend bin sizes for the next boot.
//!
//! ## License
//!
//! Copyright (c) Microsoft Corporation.
//!
//! SPDX-License-Identifier: Apache-2.0
//!

use crate::allocator::{DEFAULT_PAGE_ALLOCATION_GRANULARITY, RUNTIME_PAGE_ALLOCATION_GRANULARITY};
use patina::{
    base::{UEFI_PAGE_SHIFT, align_up},
    efi_types::{EFI_MAX_MEMORY_TYPE, INVALID_INFORMATION_INDEX},
    pi::hob::{self, EFiMemoryTypeInformation, Hob, HobList, MEMORY_TYPE_INFO_HOB_GUID},
    uefi_pages_to_size, uefi_size_to_pages,
};
use r_efi::efi;

use alloc::vec::Vec;

/// Maximum number of entries in the memory type information array.
const MAX_MEMORY_TYPE_INFO_ENTRIES: usize = EFI_MAX_MEMORY_TYPE + 1;

/// Maximum allocation address.
const MAX_ALLOC_ADDRESS: efi::PhysicalAddress = u64::MAX >> 1;

/// Log target for all memory bin log messages.
const LOG_TARGET: &str = "memory_bin";

/// Returns a human-readable name for a UEFI memory type.
///
/// Returns a `&'static str` for all standard types. Returns `"Unknown"` for unrecognized values.
#[coverage(off)]
pub(crate) fn memory_type_name(memory_type: efi::MemoryType) -> &'static str {
    match memory_type {
        efi::RESERVED_MEMORY_TYPE => "ReservedMemoryType",
        efi::LOADER_CODE => "LoaderCode",
        efi::LOADER_DATA => "LoaderData",
        efi::BOOT_SERVICES_CODE => "BootServicesCode",
        efi::BOOT_SERVICES_DATA => "BootServicesData",
        efi::RUNTIME_SERVICES_CODE => "RuntimeServicesCode",
        efi::RUNTIME_SERVICES_DATA => "RuntimeServicesData",
        efi::CONVENTIONAL_MEMORY => "ConventionalMemory",
        efi::UNUSABLE_MEMORY => "UnusableMemory",
        efi::ACPI_RECLAIM_MEMORY => "ACPIReclaimMemory",
        efi::ACPI_MEMORY_NVS => "ACPIMemoryNVS",
        efi::MEMORY_MAPPED_IO => "MemoryMappedIO",
        efi::MEMORY_MAPPED_IO_PORT_SPACE => "MemoryMappedIOPortSpace",
        efi::PAL_CODE => "PalCode",
        efi::PERSISTENT_MEMORY => "PersistentMemory",
        efi::UNACCEPTED_MEMORY_TYPE => "UnacceptedMemoryType",
        _ => "Unknown",
    }
}

/// Rounds a UEFI page count up to the nearest multiple of pages that correspond to the given
/// byte-level granularity.
///
/// On architectures with a page allocation granularity larger than `UEFI_PAGE_SIZE` (e.g.,
/// AARCH64 with 64KB runtime pages), the GCD allocates in granularity-sized chunks. This
/// function aligns a raw page count to match the actual GCD consumption.
///
/// # Parameters
/// - `pages`: The raw page count to align.
/// - `granularity`: Must be a non-zero multiple of `UEFI_PAGE_SIZE`.
///
/// # Returns
/// The page count rounded up to the nearest multiple of `granularity / UEFI_PAGE_SIZE`.
const fn align_pages_to_granularity(pages: u64, granularity: usize) -> u64 {
    let granularity_pages: u64 = (granularity >> UEFI_PAGE_SHIFT) as u64;
    if granularity_pages <= 1 {
        return pages;
    }
    pages.div_ceil(granularity_pages) * granularity_pages
}

/// Per-memory-type bin statistics.
///
/// Tracks the bin region, current allocation count, and metadata for a single memory type.
/// Mirrors `EFI_MEMORY_TYPE_STATISTICS` in edk2.
#[derive(Debug, Clone, Copy)]
struct MemoryBinStatistics {
    /// The base (lowest) address of this memory type's bin region.
    base_address: efi::PhysicalAddress,
    /// The maximum (highest) address of this memory type's bin region.
    maximum_address: efi::PhysicalAddress,
    /// The number of pages currently allocated within this bin.
    current_number_of_pages: u64,
    /// The total number of pages reserved for this bin.
    number_of_pages: u64,
    /// Index into the `MemoryTypeInformation` array for this type.
    information_index: usize,
    /// Whether this memory type persists into the OS runtime (affects `GetMemoryMap` behavior).
    special: bool,
    /// Whether this memory type should have `EFI_MEMORY_RUNTIME` attribute in the memory map.
    runtime: bool,
}

impl MemoryBinStatistics {
    /// Creates default statistics for a memory type with the given special/runtime flags.
    #[coverage(off)]
    const fn new(special: bool, runtime: bool) -> Self {
        Self {
            base_address: 0,
            maximum_address: MAX_ALLOC_ADDRESS,
            current_number_of_pages: 0,
            number_of_pages: 0,
            information_index: INVALID_INFORMATION_INDEX,
            special,
            runtime,
        }
    }
}

/// Default `MemoryBinStatistics` initialization for all memory types.
///
/// Indexed by `efi::MemoryType` value. Matches edk2's `mMemoryTypeStatistics` initialization.
const DEFAULT_STATISTICS: [MemoryBinStatistics; EFI_MAX_MEMORY_TYPE + 1] = [
    MemoryBinStatistics::new(true, false),  // EfiReservedMemoryType (0)
    MemoryBinStatistics::new(false, false), // EfiLoaderCode (1)
    MemoryBinStatistics::new(false, false), // EfiLoaderData (2)
    MemoryBinStatistics::new(false, false), // EfiBootServicesCode (3)
    MemoryBinStatistics::new(false, false), // EfiBootServicesData (4)
    MemoryBinStatistics::new(true, true),   // EfiRuntimeServicesCode (5)
    MemoryBinStatistics::new(true, true),   // EfiRuntimeServicesData (6)
    MemoryBinStatistics::new(false, false), // EfiConventionalMemory (7)
    MemoryBinStatistics::new(false, false), // EfiUnusableMemory (8)
    MemoryBinStatistics::new(true, false),  // EfiACPIReclaimMemory (9)
    MemoryBinStatistics::new(true, false),  // EfiACPIMemoryNVS (10)
    MemoryBinStatistics::new(false, false), // EfiMemoryMappedIO (11)
    MemoryBinStatistics::new(false, false), // EfiMemoryMappedIOPortSpace (12)
    MemoryBinStatistics::new(true, true),   // EfiPalCode (13)
    MemoryBinStatistics::new(false, false), // EfiPersistentMemory (14)
    MemoryBinStatistics::new(true, false),  // EfiUnacceptedMemoryType (15)
    MemoryBinStatistics::new(false, false), // EfiMaxMemoryType sentinel (16)
];

/// Manages memory bins for hibernate resume stability.
///
/// The `MemoryBinManager` tracks per-memory-type bin regions and allocation statistics.
pub(crate) struct MemoryBinManager {
    /// Per-memory-type bin statistics, indexed by `efi::MemoryType`.
    statistics: [MemoryBinStatistics; EFI_MAX_MEMORY_TYPE + 1],
    /// Current memory type information with peak usage tracking for the BDS config table.
    /// This is a fixed-size array so that raw pointers to it remain valid for the
    /// lifetime of the static `MEMORY_BIN_MANAGER`.
    memory_type_information: [EFiMemoryTypeInformation; MAX_MEMORY_TYPE_INFO_ENTRIES],
    /// Number of valid entries in `memory_type_information`.
    memory_type_information_count: usize,
    /// Whether bins have been initialized.
    initialized: bool,
}

impl MemoryBinManager {
    /// Creates a new uninitialized `MemoryBinManager`.
    pub(crate) const fn new() -> Self {
        Self {
            statistics: DEFAULT_STATISTICS,
            memory_type_information: [EFiMemoryTypeInformation { memory_type: 0, number_of_pages: 0 };
                MAX_MEMORY_TYPE_INFO_ENTRIES],
            memory_type_information_count: 0,
            initialized: false,
        }
    }

    /// Returns whether memory bins have been initialized.
    pub(crate) fn is_initialized(&self) -> bool {
        self.initialized
    }

    /// Returns the allocation granularity for the given memory type.
    pub const fn granularity_for_type(memory_type: efi::MemoryType) -> usize {
        match memory_type {
            efi::RESERVED_MEMORY_TYPE
            | efi::ACPI_MEMORY_NVS
            | efi::RUNTIME_SERVICES_CODE
            | efi::RUNTIME_SERVICES_DATA => RUNTIME_PAGE_ALLOCATION_GRANULARITY,
            _ => DEFAULT_PAGE_ALLOCATION_GRANULARITY,
        }
    }

    /// Calculates the total memory needed for all bins, considering alignment.
    ///
    /// If `bin_top` is non-zero, alignment padding is included in the calculation.
    fn calculate_total_bin_size(memory_type_info: &[EFiMemoryTypeInformation], bin_top: efi::PhysicalAddress) -> u64 {
        let mut total_size: u64 = 0;
        let mut current_top = bin_top;

        for entry in memory_type_info {
            if entry.memory_type as usize >= EFI_MAX_MEMORY_TYPE {
                break;
            }

            let granularity = Self::granularity_for_type(entry.memory_type) as u64;
            let entry_size = uefi_pages_to_size!(entry.number_of_pages as usize) as u64;
            total_size += entry_size;

            if current_top == 0 {
                continue;
            }

            current_top -= entry_size;
            let alignment_padding = current_top & (granularity - 1);
            total_size += alignment_padding;
            current_top &= !(granularity - 1);
        }

        total_size
    }

    /// Calculates a conservative allocation size for a single contiguous bin block.
    ///
    /// Returns `None` if there are no bin entries with pages > 0.
    /// The result includes the raw entry sizes plus worst-case per-entry alignment padding, rounded
    /// up to the maximum bin granularity.
    pub(crate) fn contiguous_alloc_size(memory_type_info: &[EFiMemoryTypeInformation]) -> Option<usize> {
        let mut raw_total: usize = 0;
        let mut entry_count: usize = 0;
        let mut max_granularity = DEFAULT_PAGE_ALLOCATION_GRANULARITY;

        for entry in memory_type_info {
            if entry.memory_type as usize >= EFI_MAX_MEMORY_TYPE {
                break;
            }
            if entry.number_of_pages == 0 {
                continue;
            }
            raw_total += uefi_pages_to_size!(entry.number_of_pages as usize);
            entry_count += 1;
            max_granularity = max_granularity.max(Self::granularity_for_type(entry.memory_type));
        }

        if raw_total == 0 {
            return None;
        }

        // Each entry may need up to (granularity - 1) bytes of alignment padding within the block.
        // Using max_granularity per entry is a safe over-estimate.
        let padded = raw_total + entry_count * max_granularity;
        Some(align_up(padded, max_granularity).unwrap_or(padded))
    }

    /// Returns the maximum allocation granularity across all non-zero bin entries.
    pub(crate) fn max_granularity(memory_type_info: &[EFiMemoryTypeInformation]) -> usize {
        memory_type_info
            .iter()
            .take_while(|e| (e.memory_type as usize) < EFI_MAX_MEMORY_TYPE)
            .filter(|e| e.number_of_pages > 0)
            .map(|e| Self::granularity_for_type(e.memory_type))
            .max()
            .unwrap_or(DEFAULT_PAGE_ALLOCATION_GRANULARITY)
    }

    /// Initializes bins from a pre-allocated range (provided via Resource Descriptor HOB from PEI).
    ///
    /// Divides the range `[start, start + length)` into per-type bins based on `memory_type_info`.
    /// Bins are allocated from the top of the range downward.
    pub(crate) fn initialize_from_range(
        &mut self,
        start: efi::PhysicalAddress,
        length: u64,
        memory_type_info: &[EFiMemoryTypeInformation],
    ) -> bool {
        if self.initialized {
            log::warn!("Memory bins already initialized, ignoring range.");
            return false;
        }

        let end = match start.checked_add(length) {
            Some(end) if end <= MAX_ALLOC_ADDRESS => end,
            _ => {
                log::warn!(
                    target: LOG_TARGET,
                    "Memory bin range invalid: start={:#X} length={:#X} (overflow or exceeds MAX_ALLOC_ADDRESS)",
                    start,
                    length
                );
                return false;
            }
        };

        let total_needed = Self::calculate_total_bin_size(memory_type_info, end);
        if total_needed > length {
            log::warn!(
                target: LOG_TARGET,
                "Memory bin range too small: need {:#X} bytes but only {:#X} available.",
                total_needed,
                length
            );
            return false;
        }

        log::info!(
            target: LOG_TARGET,
            "Initializing memory bins from PEI range: base={:#X} length={:#X} total_needed={:#X}",
            start,
            length,
            total_needed
        );

        let mut top = end;

        for (index, entry) in memory_type_info.iter().enumerate() {
            let mem_type = entry.memory_type;
            if mem_type as usize >= EFI_MAX_MEMORY_TYPE {
                break;
            }
            if entry.number_of_pages == 0 {
                continue;
            }

            let entry_size = uefi_pages_to_size!(entry.number_of_pages as usize) as u64;
            let stats =
                self.statistics.get_mut(mem_type as usize).expect("Defined memory types should be in statistics");
            stats.maximum_address = top - 1;
            top -= entry_size;

            // Align to the type's granularity
            let granularity = Self::granularity_for_type(mem_type) as u64;
            top &= !(granularity - 1);

            stats.base_address = top;
            stats.number_of_pages = entry.number_of_pages as u64;
            stats.information_index = index;

            log::info!(
                target: LOG_TARGET,
                "  Bin[{}] {}: base={:#X} max={:#X} pages={:#X} ({} pages)",
                mem_type,
                memory_type_name(mem_type),
                stats.base_address,
                stats.maximum_address,
                stats.number_of_pages,
                stats.number_of_pages
            );
        }

        self.finalize_information_index(memory_type_info);
        self.copy_memory_type_info(memory_type_info);
        self.initialized = true;

        log::info!(
            target: LOG_TARGET,
            "Memory bins initialized from pre-allocated range."
        );
        true
    }

    /// Sets the `information_index` for each memory type that has a corresponding entry
    /// in the memory type information array.
    fn finalize_information_index(&mut self, memory_type_info: &[EFiMemoryTypeInformation]) {
        for mem_type in 0..EFI_MAX_MEMORY_TYPE {
            let stats = self.statistics.get_mut(mem_type).expect("All defined memory types should be in statistics");
            for (index, entry) in memory_type_info.iter().enumerate() {
                if mem_type == entry.memory_type as usize {
                    stats.information_index = index;
                }
            }
            stats.current_number_of_pages = 0;
        }
        log::trace!(target: LOG_TARGET, "Bin stats: finalized information indices, reset current_number_of_pages to 0 for all types");
    }

    /// Copies memory type information entries into the fixed-size array.
    fn copy_memory_type_info(&mut self, memory_type_info: &[EFiMemoryTypeInformation]) {
        let count = memory_type_info.len().min(self.memory_type_information.len());
        let src = memory_type_info.get(..count).expect("Failed to get source slice");
        let dest = self.memory_type_information.get_mut(..count).expect("Failed to get destination slice");

        dest.copy_from_slice(src);
        self.memory_type_information_count = count;

        if log::log_enabled!(target: LOG_TARGET, log::Level::Trace) {
            log::trace!(
                target: LOG_TARGET,
                "Bin table: initialized with {} entries from HOB",
                count
            );

            if let Some(entries) = self.memory_type_information.get(..count) {
                for entry in entries {
                    log::trace!(
                        target: LOG_TARGET,
                        "  Bin table: {} pages={}",
                        memory_type_name(entry.memory_type),
                        entry.number_of_pages
                    );
                }
            }
        }
    }

    /// Seeds bin statistics from a PEI memory allocation HOB.
    ///
    /// Called for Memory Allocation HOBs that have `name == MEMORY_TYPE_INFO_HOB_GUID`,
    /// indicating they were produced by PEI's bin-aware allocator. All memory bin-type
    /// allocations are expected to be counted regardless of address.
    pub(crate) fn seed_statistics_from_hob(&mut self, memory_type: efi::MemoryType, pages: u64) {
        if !self.initialized {
            return;
        }

        let type_idx = memory_type as usize;
        let Some(stats) = self.statistics.get_mut(type_idx).filter(|s| s.special) else {
            return;
        };

        let aligned_pages = align_pages_to_granularity(pages, Self::granularity_for_type(memory_type));
        stats.current_number_of_pages += aligned_pages;
        log::debug!(
            target: LOG_TARGET,
            "PEI seed: {} +{} pages. total={}",
            memory_type_name(memory_type),
            pages,
            stats.current_number_of_pages
        );
    }

    /// Returns the current tracked page count for the given memory type.
    ///
    /// Returns 0 for invalid memory types.
    #[cfg(test)]
    pub(crate) fn current_pages_for_type(&self, memory_type: efi::MemoryType) -> u64 {
        self.statistics.get(memory_type as usize).map_or(0, |s| s.current_number_of_pages)
    }

    /// Returns an iterator over all active bins: `(memory_type, base_address, max_address, pages)`.
    ///
    /// Only yields bins with `number_of_pages > 0`.
    pub(crate) fn active_bins(
        &self,
    ) -> impl Iterator<Item = (efi::MemoryType, efi::PhysicalAddress, efi::PhysicalAddress, u64)> + '_ {
        self.statistics.iter().enumerate().filter_map(|(idx, stats)| {
            if stats.number_of_pages > 0 && idx < EFI_MAX_MEMORY_TYPE {
                Some((idx as efi::MemoryType, stats.base_address, stats.maximum_address, stats.number_of_pages))
            } else {
                None
            }
        })
    }

    /// Records an allocation for statistics tracking on special (runtime) memory types.
    ///
    /// Only tracks types with active bins (`special == true` and `number_of_pages > 0`).
    /// Updates `current_number_of_pages` and peak tracking in `memory_type_information`.
    pub(crate) fn record_allocation(&mut self, memory_type: efi::MemoryType, pages: u64) {
        if !self.initialized {
            return;
        }

        let type_idx = memory_type as usize;
        let Some(stats) = self.statistics.get_mut(type_idx).filter(|s| s.special) else {
            return;
        };

        let aligned_pages = align_pages_to_granularity(pages, Self::granularity_for_type(memory_type));
        let prev = stats.current_number_of_pages;
        stats.current_number_of_pages += aligned_pages;
        let current = stats.current_number_of_pages;
        let info_idx = stats.information_index;

        log::trace!(
            target: LOG_TARGET,
            "Bin stats: {} current_pages {} -> {} (alloc +{} aligned to {})",
            memory_type_name(memory_type),
            prev,
            current,
            pages,
            aligned_pages
        );

        // Update peak tracking: if current exceeds previous peak, update for BDS
        if let Some(mti_entry) = self.memory_type_information.get_mut(info_idx)
            && current > mti_entry.number_of_pages as u64
        {
            let prev_peak = mti_entry.number_of_pages;
            mti_entry.number_of_pages = current as u32;
            log::trace!(
                target: LOG_TARGET,
                "Bin table: {} pages {} -> {} (peak update)",
                memory_type_name(memory_type),
                prev_peak,
                mti_entry.number_of_pages
            );
        }
    }

    /// Records a deallocation for statistics tracking on special (runtime) memory types.
    ///
    /// Like [`Self::record_allocation`], all special-type frees are counted regardless of address.
    pub(crate) fn record_free(&mut self, memory_type: efi::MemoryType, pages: u64) {
        if !self.initialized {
            return;
        }

        let type_idx = memory_type as usize;
        let Some(stats) = self.statistics.get_mut(type_idx).filter(|s| s.special) else {
            return;
        };

        let aligned_pages = align_pages_to_granularity(pages, Self::granularity_for_type(memory_type));
        let prev = stats.current_number_of_pages;
        stats.current_number_of_pages = stats.current_number_of_pages.saturating_sub(aligned_pages);

        log::trace!(
            target: LOG_TARGET,
            "Bin stats: {} current_pages {} -> {} (free -{} aligned to {})",
            memory_type_name(memory_type),
            prev,
            stats.current_number_of_pages,
            pages,
            aligned_pages
        );
    }

    /// Applies bin descriptors to a populated EFI memory map buffer.
    ///
    /// Post-processes the memory map by converting `EfiConventionalMemory` entries that overlap
    /// with bin regions to the bin's memory type. Entries may be split at bin boundaries.
    ///
    /// `count` is the current number of valid entries in `buffer`.
    /// Returns the new entry count after splitting and conversion.
    ///
    /// # Precondition
    ///
    /// `buffer.len()` must be at least `count + self.max_additional_descriptors()`. Callers
    /// are responsible for reserving this slack so the per-bin split (at most two extra
    /// descriptors per active special bin) always fits.
    pub(crate) fn apply_bin_descriptors(&self, buffer: &mut [efi::MemoryDescriptor], count: usize) -> usize {
        if !self.initialized {
            return count;
        }

        let buffer_len = buffer.len();
        let mut current_count = count;

        for mem_type in 0..(EFI_MAX_MEMORY_TYPE as u32) {
            // Only process special types with actual bin pages
            let Some(stats) = self.statistics.get(mem_type as usize).filter(|s| s.special && s.number_of_pages > 0)
            else {
                continue;
            };

            let bin_start = stats.base_address;
            let bin_end = stats.maximum_address;

            log::debug!(
                target: LOG_TARGET,
                "GetMemoryMap: processing bin[{}] {} range=[{:#X}..{:#X}]",
                mem_type,
                memory_type_name(mem_type),
                bin_start,
                bin_end
            );

            // Repeatedly process until no more modifications are needed.
            // Each pass may split one entry, so restart from the beginning after each modification.
            loop {
                current_count = Self::merge_descriptors(buffer, current_count);

                let entry_count = current_count;
                let mut did_modify = false;

                for i in 0..entry_count {
                    let Some(entry) =
                        buffer.get_mut(i).filter(|e| e.r#type == efi::CONVENTIONAL_MEMORY && e.number_of_pages > 0)
                    else {
                        continue;
                    };

                    let entry_start = entry.physical_start;
                    let entry_end = entry_start + uefi_pages_to_size!(entry.number_of_pages as usize) as u64 - 1;

                    // No overlap
                    if entry_end < bin_start || entry_start > bin_end {
                        continue;
                    }

                    // Case 1: Entry completely within bin
                    if entry_start >= bin_start && entry_end <= bin_end {
                        Self::set_descriptor_type(entry, mem_type, stats.runtime);
                        did_modify = true;
                        break;
                    }

                    // Case 2: Entry starts before bin
                    if entry_start < bin_start {
                        // Calculate the total extra slots needed up front so partial mutation is
                        // prevented if the buffer-sizing precondition is violated.
                        let extra_needed = if entry_end > bin_end { 2 } else { 1 };
                        debug_assert!(
                            current_count + extra_needed <= buffer_len,
                            "apply_bin_descriptors: buffer is too small, caller must reserve max_additional_descriptors()"
                        );
                        if current_count + extra_needed > buffer_len {
                            log::error!(
                                target: LOG_TARGET,
                                "Buffer is too small for memory bin descriptor split, leaving entry as EfiConventionalMemory."
                            );
                            return current_count;
                        }

                        // Shrink original entry to end at bin start
                        let pre_bin_pages = uefi_size_to_pages!((bin_start - entry_start) as usize);
                        entry.number_of_pages = pre_bin_pages as u64;

                        // Insert new entry for in-bin portion
                        current_count = Self::insert_descriptor_after(buffer, current_count, i);
                        let new_idx = i + 1;
                        let new_entry = buffer.get_mut(new_idx).expect("Newly inserted entry not found");
                        new_entry.physical_start = bin_start;
                        new_entry.number_of_pages = uefi_size_to_pages!((entry_end - bin_start + 1) as usize) as u64;
                        Self::set_descriptor_type(new_entry, mem_type, stats.runtime);

                        // If entry also extends past bin end, split again
                        if entry_end > bin_end {
                            new_entry.number_of_pages = uefi_size_to_pages!((bin_end - bin_start + 1) as usize) as u64;

                            current_count = Self::insert_descriptor_after(buffer, current_count, new_idx);
                            let post_idx = new_idx + 1;
                            let post_entry = buffer.get_mut(post_idx).expect("Failed to get post-bin entry");
                            post_entry.physical_start = bin_end + 1;
                            post_entry.number_of_pages = uefi_size_to_pages!((entry_end - bin_end) as usize) as u64;
                            Self::set_descriptor_type(post_entry, efi::CONVENTIONAL_MEMORY, false);
                        }

                        did_modify = true;
                        break;
                    }

                    // Case 3: Entry ends after bin (entry_start >= bin_start implied here)
                    if entry_end > bin_end {
                        debug_assert!(
                            current_count < buffer_len,
                            "apply_bin_descriptors: buffer is too small, caller must reserve max_additional_descriptors() slack"
                        );
                        if current_count + 1 > buffer_len {
                            log::error!(
                                target: LOG_TARGET,
                                "Buffer is too small for memory bin descriptor split, leaving entry as EfiConventionalMemory."
                            );
                            return current_count;
                        }

                        // Shrink original entry to cover only the in-bin portion
                        entry.number_of_pages = uefi_size_to_pages!((bin_end - entry_start + 1) as usize) as u64;
                        Self::set_descriptor_type(entry, mem_type, stats.runtime);

                        // Insert new entry for the post-bin portion
                        current_count = Self::insert_descriptor_after(buffer, current_count, i);
                        let post_idx = i + 1;
                        let post_entry = buffer.get_mut(post_idx).expect("Failed to get newly created post-bin entry");
                        post_entry.physical_start = bin_end + 1;
                        post_entry.number_of_pages = uefi_size_to_pages!((entry_end - bin_end) as usize) as u64;
                        Self::set_descriptor_type(post_entry, efi::CONVENTIONAL_MEMORY, false);

                        did_modify = true;
                        break;
                    }

                    // Reaching here indicates a logic bug. This could potentially be marked unreachable!()
                    // in the future.
                    debug_assert!(
                        false,
                        "apply_bin_descriptors: overlap case fell through; entry=[{:#X}..{:#X}] bin=[{:#X}..{:#X}]",
                        entry_start, entry_end, bin_start, bin_end
                    );
                    break;
                }

                if !did_modify {
                    break;
                }
            }
        }

        Self::merge_descriptors(buffer, current_count)
    }

    /// Returns the current memory type information for config table publishing.
    ///
    /// Contains peak usage data that BDS can use to recommend next-boot bin sizes.
    pub(crate) fn memory_type_information(&self) -> &[EFiMemoryTypeInformation] {
        self.memory_type_information
            .get(..self.memory_type_information_count)
            .expect("Memory Type Info count should be correct")
    }

    /// Returns the maximum number of additional descriptors that bin splitting could add.
    ///
    /// Each active memory bin can cause up to 2 additional descriptor entries (worst case
    /// where an entry spans the entire bin, requiring a triple-split).
    pub(crate) fn max_additional_descriptors(&self) -> usize {
        if !self.initialized {
            return 0;
        }

        self.statistics.iter().filter(|s| s.number_of_pages > 0 && s.special).count() * 2
    }

    /// Sets the type and runtime attribute on a memory descriptor.
    fn set_descriptor_type(descriptor: &mut efi::MemoryDescriptor, memory_type: efi::MemoryType, runtime: bool) {
        descriptor.r#type = memory_type;
        if runtime {
            descriptor.attribute |= efi::MEMORY_RUNTIME;
        } else {
            descriptor.attribute &= !efi::MEMORY_RUNTIME;
        }
    }

    /// Inserts a new descriptor after position `after_idx` by shifting subsequent entries right.
    ///
    /// The new entry is initialized as a copy of `buffer[after_idx]`.
    /// Returns the new total count.
    fn insert_descriptor_after(buffer: &mut [efi::MemoryDescriptor], count: usize, after_idx: usize) -> usize {
        // Shift entries after `after_idx` right by one
        buffer.copy_within((after_idx + 1)..count, after_idx + 2);
        // Copy the current entry as a template for the new one. copy_within will panic if the range is invalid.
        let source = buffer.get(after_idx).copied().expect("Failed to get source entry");
        let dest = buffer.get_mut(after_idx + 1).expect("Failed to get destination entry");
        *dest = source;
        count + 1
    }

    /// Merges consecutive descriptors with the same type and attributes.
    ///
    /// Returns the new count after merging.
    fn merge_descriptors(buffer: &mut [efi::MemoryDescriptor], count: usize) -> usize {
        if count <= 1 {
            return count;
        }

        let mut write_idx = 0;
        for read_idx in 1..count {
            let write_entry = *buffer.get(write_idx).expect("count should be accurate");
            let read_entry = *buffer.get(read_idx).expect("count should be correct");

            let prev_end =
                write_entry.physical_start + uefi_pages_to_size!(write_entry.number_of_pages as usize) as u64;

            if read_entry.r#type == write_entry.r#type
                && read_entry.attribute == write_entry.attribute
                && read_entry.physical_start == prev_end
            {
                // Merge into the current entry
                let write_entry = buffer.get_mut(write_idx).expect("count should be accurate");
                write_entry.number_of_pages += read_entry.number_of_pages;
            } else {
                write_idx += 1;
                if write_idx != read_idx {
                    let write_entry = buffer.get_mut(write_idx).expect("count should be accurate");
                    *write_entry = read_entry;
                }
            }
        }

        write_idx + 1
    }

    /// Resets the bin manager to its initial uninitialized state.
    #[cfg(test)]
    pub(crate) fn reset(&mut self) {
        self.statistics = DEFAULT_STATISTICS;
        self.memory_type_information =
            [EFiMemoryTypeInformation { memory_type: 0, number_of_pages: 0 }; MAX_MEMORY_TYPE_INFO_ENTRIES];
        self.memory_type_information_count = 0;
        self.initialized = false;
    }
}

/// Searches the HOB list for a Resource Descriptor HOB owned by `MEMORY_TYPE_INFO_HOB_GUID`.
///
/// Returns `Some((physical_start, resource_length))` if exactly one valid Resource Descriptor HOB
/// is found with the correct owner, resource type, and attributes. Returns `None` if no match
/// or multiple matches are found.
pub(crate) fn find_memory_type_info_resource_hob(
    hob_list: &HobList,
    memory_type_info: &[EFiMemoryTypeInformation],
) -> Option<(efi::PhysicalAddress, u64)> {
    let target_guid = MEMORY_TYPE_INFO_HOB_GUID;
    let mut count = 0u32;
    let mut result: Option<(efi::PhysicalAddress, u64)> = None;

    for hob_entry in hob_list.iter() {
        let res_desc = match hob_entry {
            Hob::ResourceDescriptor(rd) => rd,
            _ => continue,
        };

        if res_desc.owner != target_guid {
            continue;
        }

        if res_desc.resource_type != hob::EFI_RESOURCE_SYSTEM_MEMORY {
            continue;
        }

        if (res_desc.resource_attribute & hob::MEMORY_ATTRIBUTE_MASK) != hob::TESTED_MEMORY_ATTRIBUTES {
            continue;
        }

        // Reject HOBs whose range overflows or exceeds the maximum allocation address.
        let end = match res_desc.physical_start.checked_add(res_desc.resource_length) {
            Some(end) if end <= MAX_ALLOC_ADDRESS => end,
            _ => {
                log::warn!(
                    target: LOG_TARGET,
                    "Skipping MemoryTypeInformation Resource Descriptor HOB with invalid range: start={:#X} length={:#X}",
                    res_desc.physical_start,
                    res_desc.resource_length
                );
                continue;
            }
        };

        count += 1;

        let total_needed = MemoryBinManager::calculate_total_bin_size(memory_type_info, end);

        if res_desc.resource_length >= total_needed {
            result = Some((res_desc.physical_start, res_desc.resource_length));
        }
    }

    // Reject if multiple Resource Descriptor HOBs with the owner GUID were found to avoid ambiguity
    if count > 1 {
        log::warn!(
            target: LOG_TARGET,
            "Multiple MemoryTypeInformation Resource Descriptor HOBs found ({}), rejecting all.",
            count
        );
        return None;
    }

    if let Some((start, length)) = result {
        log::info!(
            target: LOG_TARGET,
            "Found MemoryTypeInformation Resource Descriptor HOB: base={:#X} length={:#X}",
            start,
            length
        );
    } else {
        log::info!(
            target: LOG_TARGET,
            "No MemoryTypeInformation Resource Descriptor HOB found. DXE will allocate bins."
        );
    }

    result
}

/// Extracts the Memory Type Information from the GUID HOB.
///
/// Returns a Vec of `EFiMemoryTypeInformation` entries with page counts aligned to
/// the appropriate granularity for each memory type.
pub(crate) fn extract_memory_type_info_from_hob(hob_list: &HobList) -> Option<Vec<EFiMemoryTypeInformation>> {
    hob_list.iter().find_map(|hob_entry| {
        if let Hob::GuidHob(hob, data) = hob_entry {
            if hob.name != MEMORY_TYPE_INFO_HOB_GUID.into_inner() {
                return None;
            }

            let entry_size = core::mem::size_of::<EFiMemoryTypeInformation>();
            if data.is_empty() || data.len() > (EFI_MAX_MEMORY_TYPE + 1) * entry_size {
                log::error!(target: LOG_TARGET, "Invalid Memory Type Information HOB data size: {}", data.len());
                return None;
            }

            log::info!(
                target: LOG_TARGET,
                "Found Memory Type Information HOB ({} bytes, {} entries)",
                data.len(),
                data.len() / entry_size
            );

            let ptr = data.as_ptr() as *const EFiMemoryTypeInformation;
            let len = data.len() / entry_size;

            // SAFETY: HOB data is 8-byte aligned per the PI spec.
            // A compile-time assertion in allocator.rs verifies EFiMemoryTypeInformation's alignment requirement
            // is <= 8 bytes.
            let raw_entries = unsafe { core::slice::from_raw_parts(ptr, len) };

            let mut entries: Vec<EFiMemoryTypeInformation> = Vec::with_capacity(len);
            for entry in raw_entries {
                if entry.memory_type as usize >= EFI_MAX_MEMORY_TYPE {
                    // Either the sentinel or an invalid type. Include as-is (since the sentinel terminates processing).
                    entries.push(EFiMemoryTypeInformation {
                        memory_type: entry.memory_type,
                        number_of_pages: entry.number_of_pages,
                    });
                    break;
                }

                // Align page count to the type's allocation granularity for logging.
                // The config table retains the original HOB values. Alignment is only applied when
                // allocating the actual GCD bin region.
                let granularity = MemoryBinManager::granularity_for_type(entry.memory_type);
                let unaligned_size = uefi_pages_to_size!(entry.number_of_pages as usize);
                let aligned_size = align_up(unaligned_size, granularity).unwrap_or(unaligned_size);
                let aligned_pages = uefi_size_to_pages!(aligned_size);

                log::info!(
                    target: LOG_TARGET,
                    "  MemTypeInfo: {} pages={} (GCD alloc will use {})",
                    memory_type_name(entry.memory_type),
                    entry.number_of_pages,
                    aligned_pages,
                );

                entries.push(*entry);
            }

            Some(entries)
        } else {
            None
        }
    })
}

#[cfg(test)]
#[coverage(off)]
mod tests {
    use super::*;
    use patina::base::{SIZE_64KB, UEFI_PAGE_SIZE};

    const RT_GRAN_PAGES: u64 =
        (MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA) / UEFI_PAGE_SIZE) as u64;

    /// Returns the preferred allocation range for the given memory type.
    ///
    /// Returns `Some((base, max))` if a bin exists for this type with pages > 0.
    fn preferred_range(
        manager: &MemoryBinManager,
        memory_type: efi::MemoryType,
    ) -> Option<(efi::PhysicalAddress, efi::PhysicalAddress)> {
        manager.active_bins().find(|(mt, _, _, _)| *mt == memory_type).map(|(_, base, max, _)| (base, max))
    }

    /// Returns a range size large enough to hold `pages` of a runtime type including alignment padding.
    fn rt_range_size(pages: u32) -> u64 {
        let granularity = MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA);
        // Enough for the pages plus one unit of granularity for alignment padding.
        (pages as u64) * UEFI_PAGE_SIZE as u64 + granularity as u64
    }

    /// Initializes a `MemoryBinManager` from the given memory type info at the given base address.
    ///
    /// Uses `contiguous_alloc_size` to compute a range large enough for all bins.
    #[coverage(off)]
    fn init_bins(manager: &mut MemoryBinManager, base: u64, info: &[EFiMemoryTypeInformation]) {
        crate::test_support::init_test_logger();
        let range_size = MemoryBinManager::contiguous_alloc_size(info).unwrap() as u64;
        assert!(manager.initialize_from_range(base, range_size, info), "init_bins failed");
    }

    #[test]
    fn test_memory_bin_new_uninitialized() {
        let manager = MemoryBinManager::new();
        assert!(!manager.is_initialized());
        assert_eq!(preferred_range(&manager, efi::RUNTIME_SERVICES_DATA), None);
        assert_eq!(manager.max_additional_descriptors(), 0);
    }

    #[test]
    fn test_memory_bin_calculate_total_size_no_alignment() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 10 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 20 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let size = MemoryBinManager::calculate_total_bin_size(&info, 0);
        assert_eq!(size, (10 + 20) * UEFI_PAGE_SIZE as u64);
    }

    #[test]
    fn test_memory_bin_initialize_from_range() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 8 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_size = rt_range_size(4) + rt_range_size(8);
        let range_start = 0x1000_0000u64;

        let result = manager.initialize_from_range(range_start, range_size, &info);
        assert!(result);
        assert!(manager.is_initialized());

        // Bins should have been set up
        let rt_code_range = preferred_range(&manager, efi::RUNTIME_SERVICES_CODE);
        assert!(rt_code_range.is_some());
        let (base, max) = rt_code_range.unwrap();
        assert!(base >= range_start);
        assert!(max < range_start + range_size);

        let rt_data_range = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA);
        assert!(rt_data_range.is_some());

        // Non-bin types should return None
        assert_eq!(preferred_range(&manager, efi::BOOT_SERVICES_DATA), None);
    }

    #[test]
    fn test_memory_bin_initialize_from_range_too_small() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 100 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        // Range is too small for 100 pages
        let result = manager.initialize_from_range(0x1000_0000, UEFI_PAGE_SIZE as u64, &info);
        assert!(!result);
        assert!(!manager.is_initialized());
    }

    #[test]
    fn test_memory_bin_record_allocation_in_bin() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 64 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(64);
        manager.initialize_from_range(range_start, range_size, &info);

        // Record in-bin allocation. The page count is aligned up to granularity.
        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, 4);
        assert_eq!(
            manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages,
            align_pages_to_granularity(4, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA))
        );

        // Record another in-bin allocation
        let prev = manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages;
        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, 2);
        assert_eq!(
            manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages,
            prev + align_pages_to_granularity(2, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA))
        );
    }

    #[test]
    fn test_memory_bin_record_free() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 64 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(64);
        manager.initialize_from_range(range_start, range_size, &info);

        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, RT_GRAN_PAGES);
        assert_eq!(manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages, RT_GRAN_PAGES);

        manager.record_free(efi::RUNTIME_SERVICES_DATA, RT_GRAN_PAGES);
        assert_eq!(manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages, 0);

        // Free more than allocated. It should stop at 0.
        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, RT_GRAN_PAGES);
        manager.record_free(efi::RUNTIME_SERVICES_DATA, 100);
        assert_eq!(manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages, 0);
    }

    #[test]
    fn test_memory_bin_peak_tracking() {
        let bin_pages: u32 = 8;
        let alloc_pages = (bin_pages as u64).max(RT_GRAN_PAGES) + RT_GRAN_PAGES;

        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: bin_pages },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(bin_pages).max(rt_range_size(alloc_pages as u32));
        manager.initialize_from_range(range_start, range_size, &info);

        // Allocate enough to exceed the original bin size
        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, alloc_pages);

        // Peak should be updated in memory_type_information
        let expected =
            align_pages_to_granularity(alloc_pages, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA));
        assert_eq!(manager.memory_type_information()[0].number_of_pages, expected as u32);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_fully_within() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_pages = uefi_size_to_pages!((bin_max - bin_base + 1) as usize);

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: bin_base,
            virtual_start: 0,
            number_of_pages: bin_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_ne!(buffer[0].attribute & efi::MEMORY_RUNTIME, 0);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_starts_before() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_size = bin_max - bin_base + 1;

        // Entry starts 1 page before bin
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize);

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: entry_start,
            virtual_start: 0,
            number_of_pages: entry_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert!(count >= 2);

        // First entry should be the pre-bin conventional memory
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);

        // Second entry should be the bin type
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].physical_start, bin_base);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_ends_after() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_size = bin_max - bin_base + 1;

        // Entry starts at bin_base, ends 1 page after bin
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize);

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: bin_base,
            virtual_start: 0,
            number_of_pages: entry_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);

        // First entry should be the bin type
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[0].physical_start, bin_base);

        // Second entry should be conventional memory after bin
        assert_eq!(buffer[1].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[1].physical_start, bin_max + 1);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_spans_bin() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_size = bin_max - bin_base + 1;

        // Entry spans before and after bin
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + 2 * UEFI_PAGE_SIZE as u64) as usize);

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: entry_start,
            virtual_start: 0,
            number_of_pages: entry_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 3);

        // Pre-bin conventional memory
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);

        // Bin region
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].physical_start, bin_base);

        // Post-bin conventional memory
        assert_eq!(buffer[2].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[2].physical_start, bin_max + 1);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_no_overlap() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        // Entry far away from bin
        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: 0x8000_0000,
            virtual_start: 0,
            number_of_pages: 4,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
    }

    #[test]
    fn test_memory_bin_apply_descriptors_runtime_attribute() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_CODE).unwrap();
        let bin_pages = uefi_size_to_pages!((bin_max - bin_base + 1) as usize);

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: bin_base,
            virtual_start: 0,
            number_of_pages: bin_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_CODE);
        // Runtime services code is a runtime type
        assert_ne!(buffer[0].attribute & efi::MEMORY_RUNTIME, 0);
    }

    #[test]
    fn test_memory_bin_max_additional_descriptors() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 8 },
            EFiMemoryTypeInformation { memory_type: efi::ACPI_MEMORY_NVS, number_of_pages: 2 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        // RT Code (special+runtime), RT Data (special+runtime), ACPI NVS (special) = 3 (special) memory bins
        assert_eq!(manager.max_additional_descriptors(), 3 * 2);
    }

    #[test]
    fn test_memory_bin_seed_statistics_from_hob() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 64 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(64);
        manager.initialize_from_range(range_start, range_size, &info);

        manager.seed_statistics_from_hob(efi::RUNTIME_SERVICES_DATA, 3);
        assert_eq!(
            manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages,
            align_pages_to_granularity(3, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA))
        );
    }

    #[test]
    fn test_memory_bin_no_bins_when_not_initialized() {
        let manager = MemoryBinManager::new();

        // All operations should be no-ops when not initialized
        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: 0x1000_0000,
            virtual_start: 0,
            number_of_pages: 4,
            attribute: 0,
        }; 5];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1); // Unchanged
        assert_eq!(preferred_range(&manager, efi::RUNTIME_SERVICES_DATA), None);
        assert_eq!(manager.max_additional_descriptors(), 0);
    }

    #[test]
    fn test_memory_bin_double_initialization_rejected() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(4);

        assert!(manager.initialize_from_range(range_start, range_size, &info));
        // Second initialization should be rejected
        assert!(!manager.initialize_from_range(range_start + 0x100_0000, range_size, &info));
    }

    #[test]
    fn test_merge_descriptors() {
        let mut buffer = [
            efi::MemoryDescriptor {
                r#type: efi::CONVENTIONAL_MEMORY,
                physical_start: 0x1000,
                virtual_start: 0,
                number_of_pages: 1,
                attribute: efi::MEMORY_WB,
            },
            efi::MemoryDescriptor {
                r#type: efi::CONVENTIONAL_MEMORY,
                physical_start: 0x2000,
                virtual_start: 0,
                number_of_pages: 1,
                attribute: efi::MEMORY_WB,
            },
            efi::MemoryDescriptor {
                r#type: efi::RUNTIME_SERVICES_DATA,
                physical_start: 0x3000,
                virtual_start: 0,
                number_of_pages: 2,
                attribute: efi::MEMORY_WB | efi::MEMORY_RUNTIME,
            },
            efi::MemoryDescriptor { r#type: 0, physical_start: 0, virtual_start: 0, number_of_pages: 0, attribute: 0 },
            efi::MemoryDescriptor { r#type: 0, physical_start: 0, virtual_start: 0, number_of_pages: 0, attribute: 0 },
        ];

        let count = MemoryBinManager::merge_descriptors(&mut buffer, 3);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].number_of_pages, 2);
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
    }

    #[test]
    fn test_merge_descriptors_single_entry() {
        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: 0x1000,
            virtual_start: 0,
            number_of_pages: 4,
            attribute: efi::MEMORY_WB,
        }];
        let count = MemoryBinManager::merge_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
    }

    #[test]
    fn test_merge_descriptors_gap_prevents_merge() {
        let mut buffer = [
            efi::MemoryDescriptor {
                r#type: efi::CONVENTIONAL_MEMORY,
                physical_start: 0x1000,
                virtual_start: 0,
                number_of_pages: 1,
                attribute: efi::MEMORY_WB,
            },
            // Gap: 0x2000 is the end of the first, but second starts at 0x4000
            efi::MemoryDescriptor {
                r#type: efi::CONVENTIONAL_MEMORY,
                physical_start: 0x4000,
                virtual_start: 0,
                number_of_pages: 1,
                attribute: efi::MEMORY_WB,
            },
        ];
        let count = MemoryBinManager::merge_descriptors(&mut buffer, 2);
        assert_eq!(count, 2);
    }

    #[test]
    fn test_calculate_total_bin_size_with_alignment() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 1 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let entry_size = UEFI_PAGE_SIZE as u64;

        // With bin_top=0, no alignment padding
        let size_no_align = MemoryBinManager::calculate_total_bin_size(&info, 0);
        assert_eq!(size_no_align, entry_size);

        // With a non-zero bin_top that is already aligned to the type's granularity, no padding
        let granularity = MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA) as u64;
        let aligned_top = 0x1000_0000u64;
        assert_eq!(aligned_top % granularity, 0, "test precondition: top must be granularity-aligned");
        let size_aligned = MemoryBinManager::calculate_total_bin_size(&info, aligned_top);
        if entry_size.is_multiple_of(granularity) {
            assert_eq!(size_aligned, entry_size);
        } else {
            assert!(size_aligned >= entry_size);
        }

        // With an unaligned bin_top, alignment padding is required.
        let size_unaligned = MemoryBinManager::calculate_total_bin_size(&info, 0x1000_0001);
        assert!(size_unaligned > entry_size);
    }

    #[test]
    fn test_active_bins_returns_only_configured_types() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 0 },
            EFiMemoryTypeInformation { memory_type: efi::ACPI_MEMORY_NVS, number_of_pages: 2 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x3000_0000, &info);

        let bins: Vec<_> = manager.active_bins().collect();
        // RTCode (4 pages) and ACPI NVS (2 pages). RTData has 0 pages so excluded.
        assert_eq!(bins.len(), 2);
        assert_eq!(bins[0].0, efi::RUNTIME_SERVICES_CODE);
        assert_eq!(bins[1].0, efi::ACPI_MEMORY_NVS);
    }

    #[test]
    fn test_record_allocation_ignored_for_non_special_type() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::BOOT_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x1000_0000, &info);

        // BSData is not a special type, so record_allocation should be a no-op
        manager.record_allocation(efi::BOOT_SERVICES_DATA, 2);
        assert_eq!(manager.statistics[efi::BOOT_SERVICES_DATA as usize].current_number_of_pages, 0);
    }

    #[test]
    fn test_record_allocation_counts_outside_bin_range() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x1000_0000, &info);

        // Address outside the bin range is counted so BDS can see overflow.
        manager.record_allocation(efi::RUNTIME_SERVICES_DATA, 2);
        assert_eq!(
            manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages,
            align_pages_to_granularity(2, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA))
        );
    }

    #[test]
    fn test_seed_statistics_always_counted_for_special_types() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 16 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        let range_start = 0x1000_0000u64;
        let range_size = rt_range_size(16);
        manager.initialize_from_range(range_start, range_size, &info);

        // All memory bin-type HOB allocations are counted regardless of address
        manager.seed_statistics_from_hob(efi::RUNTIME_SERVICES_DATA, 5);
        assert_eq!(
            manager.statistics[efi::RUNTIME_SERVICES_DATA as usize].current_number_of_pages,
            align_pages_to_granularity(5, MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA))
        );

        // A non-memory bin type is not tracked
        manager.seed_statistics_from_hob(efi::BOOT_SERVICES_DATA, 3);
        assert_eq!(manager.statistics[efi::BOOT_SERVICES_DATA as usize].current_number_of_pages, 0);
    }

    #[test]
    fn test_memory_type_information_returned_after_init() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 8 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x1000_0000, &info);

        let mti = manager.memory_type_information();
        assert_eq!(mti.len(), 3);
        assert_eq!(mti[0].memory_type, efi::RUNTIME_SERVICES_CODE);
        assert_eq!(mti[0].number_of_pages, 4);
        assert_eq!(mti[1].memory_type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(mti[1].number_of_pages, 8);
    }

    #[test]
    fn test_apply_descriptors_skips_non_conventional() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];

        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);

        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_pages = uefi_size_to_pages!((bin_max - bin_base + 1) as usize);

        // Entry is BSCode within the bin range so it should not be converted
        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::BOOT_SERVICES_CODE,
            physical_start: bin_base,
            virtual_start: 0,
            number_of_pages: bin_pages as u64,
            attribute: efi::MEMORY_WB,
        }; 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::BOOT_SERVICES_CODE);
    }

    #[test]
    fn test_memory_type_name_known_and_unknown() {
        assert_eq!(memory_type_name(efi::RUNTIME_SERVICES_DATA), "RuntimeServicesData");
        assert_eq!(memory_type_name(efi::BOOT_SERVICES_CODE), "BootServicesCode");
        assert!(memory_type_name(0xFFFF).starts_with("Unknown"));
    }

    #[test]
    fn test_align_pages_to_granularity_equal_to_page_size() {
        // granularity == UEFI_PAGE_SIZE => granularity_pages == 1, pages returned unchanged
        assert_eq!(align_pages_to_granularity(0, UEFI_PAGE_SIZE), 0);
        assert_eq!(align_pages_to_granularity(1, UEFI_PAGE_SIZE), 1);
        assert_eq!(align_pages_to_granularity(7, UEFI_PAGE_SIZE), 7);
    }

    #[test]
    fn test_align_pages_to_granularity_smaller_than_page_size() {
        // granularity < UEFI_PAGE_SIZE => granularity_pages == 0 <= 1, pages returned unchanged
        assert_eq!(align_pages_to_granularity(5, UEFI_PAGE_SIZE / 2), 5);
    }

    #[test]
    fn test_align_pages_to_granularity_two_pages() {
        assert_eq!(align_pages_to_granularity(0, 2 * UEFI_PAGE_SIZE), 0);
        assert_eq!(align_pages_to_granularity(1, 2 * UEFI_PAGE_SIZE), 2);
        assert_eq!(align_pages_to_granularity(2, 2 * UEFI_PAGE_SIZE), 2);
        assert_eq!(align_pages_to_granularity(3, 2 * UEFI_PAGE_SIZE), 4);
        assert_eq!(align_pages_to_granularity(4, 2 * UEFI_PAGE_SIZE), 4);
    }

    #[test]
    fn test_align_pages_to_granularity_sixteen_pages() {
        assert_eq!(align_pages_to_granularity(0, SIZE_64KB), 0);
        assert_eq!(align_pages_to_granularity(1, SIZE_64KB), 16);
        assert_eq!(align_pages_to_granularity(15, SIZE_64KB), 16);
        assert_eq!(align_pages_to_granularity(16, SIZE_64KB), 16);
        assert_eq!(align_pages_to_granularity(17, SIZE_64KB), 32);
    }

    #[test]
    fn test_contiguous_alloc_size_single_entry() {
        let rt_data_pages = 10;

        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: rt_data_pages },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let size = MemoryBinManager::contiguous_alloc_size(&info).unwrap();
        let raw = rt_data_pages as usize * UEFI_PAGE_SIZE;
        let granularity = MemoryBinManager::granularity_for_type(efi::RUNTIME_SERVICES_DATA);
        // Must be at least raw + one granularity unit of padding, rounded up to granularity.
        assert!(size >= raw + granularity);
        assert_eq!(size % granularity, 0);
    }

    #[test]
    fn test_contiguous_alloc_size_multiple_entries() {
        let rt_code_pages = 4;
        let rt_data_pages = 8;
        let acpi_reclaim_pages = 2;
        let total_pages: usize = (rt_code_pages + rt_data_pages + acpi_reclaim_pages) as usize;

        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: rt_code_pages },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: rt_data_pages },
            EFiMemoryTypeInformation { memory_type: efi::ACPI_RECLAIM_MEMORY, number_of_pages: acpi_reclaim_pages },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let size = MemoryBinManager::contiguous_alloc_size(&info).unwrap();

        let raw = total_pages * UEFI_PAGE_SIZE;
        assert!(size >= raw, "size {:#X} must be >= raw {:#X}", size, raw);
    }

    #[test]
    fn test_contiguous_alloc_size_empty() {
        // Sentinel only, no pages.
        let info = [EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 }];
        assert_eq!(MemoryBinManager::contiguous_alloc_size(&info), None);
    }

    #[test]
    fn test_contiguous_alloc_size_all_zero_pages() {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: 0 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 0 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        assert_eq!(MemoryBinManager::contiguous_alloc_size(&info), None);
    }

    #[test]
    fn test_contiguous_alloc_size_skips_zero_page_entries() {
        let rt_data_pages = 4;

        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 0 },
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: rt_data_pages },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let size = MemoryBinManager::contiguous_alloc_size(&info).unwrap();
        // Only 1 entry with pages > 0, so padding = 1 * max_granularity.
        let raw = rt_data_pages as usize * UEFI_PAGE_SIZE;
        assert!(size >= raw);
    }

    /// Helper that builds a single-bin manager (RUNTIME_SERVICES_DATA) and returns the
    /// (bin_base, bin_max, bin_size) for tests that need to construct entries relative
    /// to the bin.
    fn single_bin_manager(pages: u32) -> (MemoryBinManager, efi::PhysicalAddress, efi::PhysicalAddress, u64) {
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_DATA, number_of_pages: pages },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x2000_0000, &info);
        let (bin_base, bin_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_DATA).unwrap();
        let bin_size = bin_max - bin_base + 1;
        (manager, bin_base, bin_max, bin_size)
    }

    // Helper to create a conventional memory descriptor for testing.
    fn conv_descriptor(physical_start: efi::PhysicalAddress, pages: u64) -> efi::MemoryDescriptor {
        efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start,
            virtual_start: 0,
            number_of_pages: pages,
            attribute: efi::MEMORY_WB,
        }
    }

    #[test]
    fn test_apply_descriptors_count_zero() {
        let (manager, _, _, _) = single_bin_manager(4);
        let mut buffer = [conv_descriptor(0x1000_0000, 4); 10];
        let count = manager.apply_bin_descriptors(&mut buffer, 0);
        assert_eq!(count, 0);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
    }

    #[test]
    fn test_apply_descriptors_entry_just_before_bin() {
        // Entry ends exactly at bin_start - 1 (no overlap).
        let (manager, bin_base, _, _) = single_bin_manager(4);
        let pages = 2u64;
        let entry_start = bin_base - uefi_pages_to_size!(pages as usize) as u64;
        let mut buffer = [conv_descriptor(entry_start, pages); 10];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);
        assert_eq!(buffer[0].number_of_pages, pages);
    }

    #[test]
    fn test_apply_descriptors_entry_just_after_bin() {
        // Entry starts exactly at bin_max + 1 (no overlap).
        let (manager, _, bin_max, _) = single_bin_manager(4);
        let mut buffer = [conv_descriptor(bin_max + 1, 2); 10];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, bin_max + 1);
    }

    #[test]
    fn test_apply_descriptors_entry_equals_bin_exactly() {
        // Case 1 boundary: entry covers exactly [bin_base, bin_max].
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!(bin_size as usize) as u64;
        let mut buffer = [conv_descriptor(bin_base, entry_pages); 10];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[0].physical_start, bin_base);
        let expected_end =
            buffer[0].physical_start + uefi_pages_to_size!(buffer[0].number_of_pages as usize) as u64 - 1;
        assert_eq!(expected_end, bin_max);
    }

    #[test]
    fn test_apply_descriptors_starts_before_ends_at_bin_end() {
        // Case 2 single split: pre-bin tail + in-bin portion ending exactly at bin_max.
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;
        let mut buffer = [conv_descriptor(entry_start, entry_pages); 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);
        assert_eq!(buffer[0].number_of_pages, 1);
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].physical_start, bin_base);
        let post_end = buffer[1].physical_start + uefi_pages_to_size!(buffer[1].number_of_pages as usize) as u64 - 1;
        assert_eq!(post_end, bin_max);
    }

    #[test]
    fn test_apply_descriptors_starts_at_bin_start_ends_after_bin() {
        // Case 3 boundary: entry begins exactly at bin_base and extends past bin_max.
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;
        let mut buffer = [conv_descriptor(bin_base, entry_pages); 10];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[0].physical_start, bin_base);
        assert_eq!(buffer[1].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[1].physical_start, bin_max + 1);
        assert_eq!(buffer[1].number_of_pages, 1);
    }

    #[test]
    fn test_apply_descriptors_multiple_bins() {
        // Two active bins. Each conventional entry lies entirely within one bin.
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::RUNTIME_SERVICES_CODE, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: efi::ACPI_MEMORY_NVS, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x3000_0000, &info);

        let (rt_base, rt_max) = preferred_range(&manager, efi::RUNTIME_SERVICES_CODE).unwrap();
        let (acpi_base, acpi_max) = preferred_range(&manager, efi::ACPI_MEMORY_NVS).unwrap();
        let rt_pages = uefi_size_to_pages!((rt_max - rt_base + 1) as usize) as u64;
        let acpi_pages = uefi_size_to_pages!((acpi_max - acpi_base + 1) as usize) as u64;

        // Order entries by ascending physical address.
        let (lo_base, lo_pages, lo_type, hi_base, hi_pages, hi_type) = if rt_base < acpi_base {
            (rt_base, rt_pages, efi::RUNTIME_SERVICES_CODE, acpi_base, acpi_pages, efi::ACPI_MEMORY_NVS)
        } else {
            (acpi_base, acpi_pages, efi::ACPI_MEMORY_NVS, rt_base, rt_pages, efi::RUNTIME_SERVICES_CODE)
        };

        let mut buffer = [conv_descriptor(0, 0); 10];
        buffer[0] = conv_descriptor(lo_base, lo_pages);
        buffer[1] = conv_descriptor(hi_base, hi_pages);

        let count = manager.apply_bin_descriptors(&mut buffer, 2);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, lo_type);
        assert_eq!(buffer[1].r#type, hi_type);
    }

    #[test]
    fn test_apply_descriptors_multiple_entries_one_overlapping() {
        // Three entries. Only the middle one overlaps the bin. Others must be unchanged.
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!(bin_size as usize) as u64;

        let before_pages = 2u64;
        let before_start = bin_base - 0x1_0000 - uefi_pages_to_size!(before_pages as usize) as u64;
        let after_start = bin_max + 1 + 0x1_0000;

        let mut buffer = [conv_descriptor(0, 0); 10];
        buffer[0] = conv_descriptor(before_start, before_pages);
        buffer[1] = conv_descriptor(bin_base, entry_pages);
        buffer[2] = conv_descriptor(after_start, 2);

        let count = manager.apply_bin_descriptors(&mut buffer, 3);
        assert_eq!(count, 3);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, before_start);
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].physical_start, bin_base);
        assert_eq!(buffer[2].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[2].physical_start, after_start);
    }

    #[test]
    fn test_apply_descriptors_exact_fit_buffer_case2_single() {
        // Buffer length is exactly count + 1 (the minimum slack for a Case 2 single split).
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;

        let mut buffer = [conv_descriptor(entry_start, entry_pages); 2];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        let post_end = buffer[1].physical_start + uefi_pages_to_size!(buffer[1].number_of_pages as usize) as u64 - 1;
        assert_eq!(post_end, bin_max);
    }

    #[test]
    fn test_apply_descriptors_exact_fit_buffer_case2_double() {
        // Buffer length is exactly count + 2 (the minimum slack for a Case 2 spans-bin split).
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + 2 * UEFI_PAGE_SIZE as u64) as usize) as u64;

        let mut buffer = [conv_descriptor(entry_start, entry_pages); 3];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 3);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].physical_start, bin_base);
        assert_eq!(buffer[2].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[2].physical_start, bin_max + 1);
    }

    #[test]
    fn test_apply_descriptors_exact_fit_buffer_case3() {
        // Buffer length is exactly count + 1 (the minimum slack for a Case 3 split).
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;

        let mut buffer = [conv_descriptor(bin_base, entry_pages); 2];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_eq!(buffer[1].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[1].physical_start, bin_max + 1);
    }

    #[test]
    fn test_apply_descriptors_buffer_too_small_case2_single_fallback() {
        // Case 2 single split needs count + 1, but buffer is sized exactly to count.
        // The function must not mutate the entry and must return the original count.
        let (manager, bin_base, _, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;
        let original = conv_descriptor(entry_start, entry_pages);

        let mut buffer = [original; 1];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);

        assert_eq!(count, 1);
        // Buffer should be unchanged (not partially mutated).
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);
        assert_eq!(buffer[0].number_of_pages, entry_pages);
    }

    #[test]
    fn test_apply_descriptors_buffer_too_small_case2_double_fallback() {
        // Case 2 spans-bin needs count + 2, but buffer only has count + 1.
        // The function must not mutate the entry and must return the original count.
        let (manager, bin_base, _, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + 2 * UEFI_PAGE_SIZE as u64) as usize) as u64;
        let original = conv_descriptor(entry_start, entry_pages);

        let mut buffer = [original; 2];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);

        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, entry_start);
        assert_eq!(buffer[0].number_of_pages, entry_pages);
    }

    #[test]
    fn test_apply_descriptors_buffer_too_small_case3_fallback() {
        // Case 3 needs count + 1, but buffer is sized exactly to count.
        // The function must not mutate the entry and must return the original count.
        let (manager, bin_base, _, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;
        let original = conv_descriptor(bin_base, entry_pages);

        let mut buffer = [original; 1];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);

        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, bin_base);
        assert_eq!(buffer[0].number_of_pages, entry_pages);
    }

    #[test]
    fn test_apply_descriptors_buffer_too_small_case1_unaffected() {
        // Case 1 (entry fully within bin) does not require any extra slots, so a buffer
        // sized exactly to count is fine and the conversion still happens in place.
        let (manager, bin_base, _, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!(bin_size as usize) as u64;
        let mut buffer = [conv_descriptor(bin_base, entry_pages); 1];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::RUNTIME_SERVICES_DATA);
    }

    #[test]
    fn test_apply_descriptors_initialized_no_special_bins() {
        // Initialize with only a non-special memory type (BOOT_SERVICES_DATA). The manager
        // is initialized but has no active special bins, so apply must be a no-op.
        let info = [
            EFiMemoryTypeInformation { memory_type: efi::BOOT_SERVICES_DATA, number_of_pages: 4 },
            EFiMemoryTypeInformation { memory_type: EFI_MAX_MEMORY_TYPE as u32, number_of_pages: 0 },
        ];
        let mut manager = MemoryBinManager::new();
        init_bins(&mut manager, 0x4000_0000, &info);
        assert_eq!(manager.max_additional_descriptors(), 0);

        let mut buffer = [conv_descriptor(0x4000_0000, 4); 4];
        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
    }

    #[test]
    fn test_apply_descriptors_preserves_attributes_on_pre_bin_split() {
        // The pre-bin conventional remainder retains the original entry's non-runtime
        // attributes; the in-bin portion picks up MEMORY_RUNTIME (runtime bin type).
        let (manager, bin_base, bin_max, bin_size) = single_bin_manager(4);
        let entry_start = bin_base - UEFI_PAGE_SIZE as u64;
        let entry_pages = uefi_size_to_pages!((bin_size + UEFI_PAGE_SIZE as u64) as usize) as u64;

        let mut buffer = [efi::MemoryDescriptor {
            r#type: efi::CONVENTIONAL_MEMORY,
            physical_start: entry_start,
            virtual_start: 0,
            number_of_pages: entry_pages,
            attribute: efi::MEMORY_WB | efi::MEMORY_WT,
        }; 4];

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 2);

        // Pre-bin conventional keeps original (non-runtime) attributes.
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].attribute & (efi::MEMORY_WB | efi::MEMORY_WT), efi::MEMORY_WB | efi::MEMORY_WT);
        assert_eq!(buffer[0].attribute & efi::MEMORY_RUNTIME, 0);

        // In-bin portion has the runtime attribute set.
        assert_eq!(buffer[1].r#type, efi::RUNTIME_SERVICES_DATA);
        assert_ne!(buffer[1].attribute & efi::MEMORY_RUNTIME, 0);
        assert_eq!(buffer[1].attribute & (efi::MEMORY_WB | efi::MEMORY_WT), efi::MEMORY_WB | efi::MEMORY_WT);
        let in_bin_end = buffer[1].physical_start + uefi_pages_to_size!(buffer[1].number_of_pages as usize) as u64 - 1;
        assert_eq!(in_bin_end, bin_max);
    }

    #[test]
    fn test_apply_descriptors_ignores_entries_beyond_count() {
        // Entries past `count` must be ignored even if they look like overlaps.
        let (manager, bin_base, _, bin_size) = single_bin_manager(4);
        let entry_pages = uefi_size_to_pages!(bin_size as usize) as u64;

        let mut buffer = [conv_descriptor(0, 0); 4];
        // Real entry: far from bin.
        buffer[0] = conv_descriptor(0x8000_0000, 2);
        // Stale data past count: would otherwise overlap the bin.
        buffer[1] = conv_descriptor(bin_base, entry_pages);

        let count = manager.apply_bin_descriptors(&mut buffer, 1);
        assert_eq!(count, 1);
        assert_eq!(buffer[0].r#type, efi::CONVENTIONAL_MEMORY);
        assert_eq!(buffer[0].physical_start, 0x8000_0000);
        // The stale entry at index 1 was never considered.
        assert_eq!(buffer[1].physical_start, bin_base);
        assert_eq!(buffer[1].r#type, efi::CONVENTIONAL_MEMORY);
    }
}