ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
//! Windows platform implementation
//!
//! Provides CPU, memory, and system monitoring for Windows using Windows APIs.

use crate::core::{
    cpu::{CpuCore, CpuFrequency, CpuStats, CpuTotal},
    gpu::GpuStats,
    memory::{MemoryStats, RamInfo, SwapInfo},
    platform_info::{BoardInfo, HardwareInfo, LibraryVersions, PlatformInfo},
    power::PowerStats,
    temperature::TemperatureStats,
};
use crate::error::{IronError, Result};
use std::collections::HashMap;
use std::mem;
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use windows::Win32::System::ProcessStatus::{GetPerformanceInfo, PERFORMANCE_INFORMATION};
use windows::Win32::System::SystemInformation::{
    GetSystemInfo, GlobalMemoryStatusEx, MEMORYSTATUSEX, SYSTEM_INFO,
};

/// The previous collection's raw counters, kept whole.
///
/// The whole-CPU and per-processor readings are stored together under one lock. Stored
/// as separate atomics, two threads could interleave their loads and stores and pair
/// one call's idle with another's kernel, producing a split that no single reading
/// ever showed.
static PREV_CPU_COUNTERS: Mutex<Option<CpuCounters>> = Mutex::new(None);

/// How long a first call waits between its two readings.
///
/// Long enough that `GetSystemTimes` (which advances in scheduler ticks of roughly
/// 10-16 ms) has moved on, so the difference is a real interval, and short enough
/// that the one-shot `ironmon get` and `ironmon snapshot` commands stay responsive.
const PRIME_INTERVAL: Duration = Duration::from_millis(200);

/// One `GetSystemTimes` reading, in 100 ns ticks summed across all processors.
/// `kernel` includes `idle`, as the API reports it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct SystemTimesSample {
    idle: u64,
    kernel: u64,
    user: u64,
}

/// The raw counters of one collection: the whole-CPU reading and the per-processor
/// records, read back to back so that both describe the same interval.
#[derive(Clone)]
struct CpuCounters {
    system: SystemTimesSample,
    /// `None` if the per-processor query failed.
    cores: Option<Vec<SystemProcessorPerformanceInformation>>,
}

/// A `(user, system, idle)` split, in percent of one interval.
type Percent3 = (f32, f32, f32);

/// One split per processor, `None` where no figure was read.
type CoreSplits = Vec<Option<Percent3>>;

/// The split of one interval, for the whole CPU and for each processor separately.
#[derive(Default)]
struct CpuSplit {
    system: Option<Percent3>,
    /// `None` as a whole if the processor counts did not match.
    cores: Option<CoreSplits>,
}

/// Read CPU statistics on Windows
pub fn read_cpu_stats() -> Result<CpuStats> {
    let mut stats = CpuStats::empty();

    // Get number of processors
    let mut sys_info: SYSTEM_INFO = unsafe { mem::zeroed() };
    unsafe { GetSystemInfo(&mut sys_info) };
    let cpu_count = sys_info.dwNumberOfProcessors as usize;

    // The whole-CPU split and the per-processor split come from one sampling pass, so
    // a first call pays for one priming interval, not one per figure.
    let ((user_percent, system_percent, idle_percent), per_core) = sample_cpu_split(cpu_count)?;

    // Model name is fixed for the life of the process and cached behind a OnceLock.
    // Clocks are not: each core boosts and parks independently, so they are sampled
    // per call and assigned per core rather than broadcast from core 0.
    let model = get_cpu_model_name();
    let power = query_processor_power(cpu_count);
    // Delivered performance per core, for the machines where `CurrentMhz` is
    // the nominal clock -- which is all of them on Windows 10 and later. `None`
    // on the first call of the process: a rate needs two collections.
    let delivered = crate::platform::windows_pdh::processor_performance_percent();

    // Real per-processor times, sampled above alongside the whole-CPU split. Each core
    // with no figure is `None`, which consumers render as "unavailable" — deliberately
    // not the system average.
    //
    // Until this existed, every core was assigned the *system-wide* figure from
    // GetSystemTimes, so a 24-core machine showed 24 identical bars that looked like
    // per-core measurements but were one number repeated.
    for cpu_id in 0..cpu_count {
        let (core_user, core_system, core_idle) = match per_core
            .as_ref()
            .and_then(|cores| cores.get(cpu_id))
            .copied()
            .flatten()
        {
            Some((u, s, i)) => (Some(u), Some(s), Some(i)),
            None => (None, None, None),
        };

        let core = CpuCore {
            id: cpu_id,
            // No Windows reader fills this. It was a literal `true` for every
            // logical processor, which reported them online without checking.
            online: None,
            // Windows has no cpufreq governor. This was the literal "windows".
            governor: None,
            frequency: get_cpu_frequency(power.as_ref(), cpu_id, delivered.as_ref()),
            user: core_user,
            // Windows has no nice time. This was `Some(0.0)`.
            nice: None,
            system: core_system,
            idle: core_idle,
            model: model.clone(),
        };
        stats.cores.push(core);
    }

    // Set totals
    stats.total = CpuTotal {
        user: user_percent,
        // Windows has no nice time. This was a literal 0.0.
        nice: None,
        system: system_percent,
        idle: idle_percent,
    };

    Ok(stats)
}

// ============================================================================
// Per-processor CPU times
// ============================================================================

/// Per-processor timing record returned by `NtQuerySystemInformation`.
///
/// Mirrors `SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION`. Times are in 100ns units, and
/// `kernel_time` *includes* `idle_time`, matching `GetSystemTimes`.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct SystemProcessorPerformanceInformation {
    idle_time: i64,
    kernel_time: i64,
    user_time: i64,
    dpc_time: i64,
    interrupt_time: i64,
    interrupt_count: u32,
    // Explicit tail padding so the struct stride matches what the kernel writes;
    // the array is indexed by stride, so getting this wrong misaligns every core
    // after the first.
    _reserved: u32,
}

/// `SystemProcessorPerformanceInformation` information class.
const SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_CLASS: u32 = 8;

#[link(name = "ntdll")]
extern "system" {
    /// Queries kernel performance data.
    ///
    /// Used because Win32 exposes no per-processor time API: `GetSystemTimes` is
    /// system-wide, and the documented alternative (PDH `\Processor(N)\% Processor
    /// Time`) requires a persistent query handle and two sampling passes. This call
    /// is what Task Manager and every mainstream monitor rely on.
    fn NtQuerySystemInformation(
        system_information_class: u32,
        system_information: *mut core::ffi::c_void,
        system_information_length: u32,
        return_length: *mut u32,
    ) -> i32;
}

/// Read raw per-processor times.
fn query_per_core_times(cpu_count: usize) -> Option<Vec<SystemProcessorPerformanceInformation>> {
    if cpu_count == 0 {
        return None;
    }

    let mut buffer: Vec<SystemProcessorPerformanceInformation> =
        vec![SystemProcessorPerformanceInformation::default(); cpu_count];
    let byte_len = std::mem::size_of_val(buffer.as_slice()) as u32;
    let mut returned: u32 = 0;

    // SAFETY: the buffer is sized for exactly `cpu_count` records and its length in
    // bytes is passed alongside it, so the kernel cannot write past the end. Both
    // out-pointers reference live local storage for the duration of the call.
    let status = unsafe {
        NtQuerySystemInformation(
            SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION_CLASS,
            buffer.as_mut_ptr() as *mut core::ffi::c_void,
            byte_len,
            &mut returned,
        )
    };

    // NTSTATUS: negative values are failures.
    if status < 0 {
        return None;
    }

    // Trust the kernel's reported count over our assumption: a machine with more than
    // 64 logical processors splits into processor groups, and GetSystemInfo reports
    // only the calling group.
    let record_size = std::mem::size_of::<SystemProcessorPerformanceInformation>();
    let returned_records = (returned as usize) / record_size;
    if returned_records == 0 {
        return None;
    }
    buffer.truncate(returned_records.min(cpu_count));

    Some(buffer)
}

/// One process's entry in the system process table.
///
/// The layout is `SYSTEM_PROCESS_INFORMATION` as the `windows` crate generates
/// it from Microsoft's metadata (`Win32::System::WindowsProgramming`), copied
/// here so the existing `ntdll` binding can use it without another crate
/// feature. Every field named below is documented in `winternl.h` except the
/// three times, which sit in the first `Reserved1` block; their offsets are
/// checked against `GetProcessTimes` in this module's tests rather than
/// trusted.
#[repr(C)]
struct SystemProcessInformation {
    next_entry_offset: u32,
    number_of_threads: u32,
    /// `WorkingSetPrivateSize`, `HardFaultCount`, `NumberOfThreadsHighWatermark`
    /// and `CycleTime` (bytes 0..24), then `CreateTime`, `UserTime` and
    /// `KernelTime` (24..48), each a 64-bit count of 100 ns units.
    reserved1: [u8; 48],
    image_name_length: u16,
    image_name_maximum_length: u16,
    image_name_buffer: *mut u16,
    base_priority: i32,
    unique_process_id: usize,
    reserved2: *mut core::ffi::c_void,
    handle_count: u32,
    session_id: u32,
    reserved3: *mut core::ffi::c_void,
    peak_virtual_size: usize,
    virtual_size: usize,
    reserved4: u32,
    peak_working_set_size: usize,
    working_set_size: usize,
    reserved5: *mut core::ffi::c_void,
    quota_paged_pool_usage: usize,
    reserved6: *mut core::ffi::c_void,
    quota_non_paged_pool_usage: usize,
    pagefile_usage: usize,
    peak_pagefile_usage: usize,
    private_page_count: usize,
    reserved7: [i64; 6],
}

/// `SystemProcessInformation` information class.
const SYSTEM_PROCESS_INFORMATION_CLASS: u32 = 5;

/// What the system process table reports for one process, without opening it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ProcessTableEntry {
    pub working_set_bytes: u64,
    /// Commit charge, which `GetProcessMemoryInfo` calls `PagefileUsage` and
    /// `PrivateUsage`.
    pub pagefile_usage_bytes: u64,
    pub private_bytes: u64,
    pub handle_count: u32,
    pub thread_count: u32,
    pub create_time_100ns: u64,
    pub user_time_100ns: u64,
    pub kernel_time_100ns: u64,
    pub io_read_bytes: u64,
    pub io_write_bytes: u64,
}

/// Every process's memory, handle and CPU-time figures, keyed by PID.
///
/// **Why this exists.** An unelevated process cannot open most SYSTEM and
/// protected processes, so `GetProcessMemoryInfo` and `GetProcessTimes` are
/// unavailable for them. The enumeration used to emit those rows with memory
/// and CPU at zero -- on the machine this was found on, 167 of 515 processes,
/// `dwm.exe`, `lsass.exe` and `Registry` among them, each reported as using no
/// memory at all, which also reordered every "largest by memory" list. The
/// kernel's process table carries the same figures for every process and needs
/// no handle; it is what Task Manager reads.
pub(crate) fn system_process_table() -> Option<std::collections::HashMap<u32, ProcessTableEntry>> {
    let mut size: u32 = 1 << 20;
    let mut buffer: Vec<u64>;
    loop {
        // `u64` elements keep the buffer 8-byte aligned, which the records need.
        buffer = vec![0u64; (size as usize).div_ceil(8)];
        let mut returned: u32 = 0;
        // SAFETY: the buffer is `size` bytes long and its length is passed with
        // it; the kernel writes at most that many bytes and reports how many.
        let status = unsafe {
            NtQuerySystemInformation(
                SYSTEM_PROCESS_INFORMATION_CLASS,
                buffer.as_mut_ptr() as *mut core::ffi::c_void,
                size,
                &mut returned,
            )
        };
        // STATUS_INFO_LENGTH_MISMATCH: the table grew past the buffer.
        const STATUS_INFO_LENGTH_MISMATCH: i32 = 0xC000_0004_u32 as i32;
        if status == STATUS_INFO_LENGTH_MISMATCH && size < (64 << 20) {
            size = returned.max(size) * 2;
            continue;
        }
        if status < 0 {
            return None;
        }
        break;
    }

    let bytes =
        unsafe { std::slice::from_raw_parts(buffer.as_ptr() as *const u8, buffer.len() * 8) };
    let record = std::mem::size_of::<SystemProcessInformation>();
    let read_u64 = |b: &[u8], at: usize| u64::from_le_bytes(b[at..at + 8].try_into().unwrap());

    let mut table = std::collections::HashMap::new();
    let mut offset = 0usize;
    while offset + record <= bytes.len() {
        // SAFETY: bounds checked above; the kernel places each record at an
        // 8-byte-aligned offset within the buffer.
        let entry = unsafe { &*(bytes.as_ptr().add(offset) as *const SystemProcessInformation) };
        let pid = entry.unique_process_id as u32;
        table.insert(
            pid,
            ProcessTableEntry {
                working_set_bytes: entry.working_set_size as u64,
                pagefile_usage_bytes: entry.pagefile_usage as u64,
                private_bytes: entry.private_page_count as u64,
                handle_count: entry.handle_count,
                thread_count: entry.number_of_threads,
                create_time_100ns: read_u64(&entry.reserved1, 24),
                user_time_100ns: read_u64(&entry.reserved1, 32),
                kernel_time_100ns: read_u64(&entry.reserved1, 40),
                // `Reserved7` is an `IO_COUNTERS`: three operation counts, then
                // read, write and other transfer counts.
                io_read_bytes: entry.reserved7[3] as u64,
                io_write_bytes: entry.reserved7[4] as u64,
            },
        );
        if entry.next_entry_offset == 0 {
            break;
        }
        offset += entry.next_entry_offset as usize;
    }
    (!table.is_empty()).then_some(table)
}

/// Rows of a WMI query, run in-process.
///
/// A PowerShell `Get-CimInstance` answering the same query costs a process and
/// a CIM session -- a quarter of a second at best, several at worst -- and
/// several readers ran one per property group on every snapshot. COM may
/// already be initialised on the calling thread in another mode (a GUI thread
/// is), so this falls back as `disk::windows` does.
pub(crate) fn wmi_query(
    namespace: &str,
    query: &str,
) -> std::result::Result<
    Vec<std::collections::HashMap<String, wmi::Variant>>,
    crate::error::IronError,
> {
    use wmi::{COMLibrary, WMIConnection};
    let com = COMLibrary::new()
        .or_else(|_| COMLibrary::without_security())
        .unwrap_or_else(|_| unsafe { COMLibrary::assume_initialized() });
    let conn = WMIConnection::with_namespace_path(namespace, com)
        .map_err(|e| crate::error::IronError::System(format!("WMI {namespace}: {e}")))?;
    conn.raw_query(query)
        .map_err(|e| crate::error::IronError::System(format!("WMI query `{query}`: {e}")))
}

/// A string property of a WMI row, or `""` where it is absent or not a string.
pub(crate) fn wmi_str<'a>(
    row: &'a std::collections::HashMap<String, wmi::Variant>,
    key: &str,
) -> &'a str {
    match row.get(key) {
        Some(wmi::Variant::String(s)) => s.as_str(),
        _ => "",
    }
}

/// Whether this process runs elevated, from its token's `TokenElevation`.
///
/// `None` when the token cannot be read. Used to avoid asking questions whose
/// answer is already known to be "access denied": an unelevated query of the
/// Administrators-only `root/cimv2/Security/MicrosoftTpm` namespace took 6.6 s
/// to be refused on the machine this was measured on.
pub(crate) fn is_elevated() -> Option<bool> {
    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::Security::{
        GetTokenInformation, TokenElevation, TOKEN_ELEVATION, TOKEN_QUERY,
    };
    use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};

    let mut token = HANDLE::default();
    // SAFETY: the pseudo-handle from `GetCurrentProcess` needs no closing; the
    // token handle is closed below on every path that opened it.
    unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) }.ok()?;
    let mut elevation = TOKEN_ELEVATION::default();
    let mut returned = 0u32;
    let read = unsafe {
        GetTokenInformation(
            token,
            TokenElevation,
            Some(std::ptr::addr_of_mut!(elevation) as *mut core::ffi::c_void),
            std::mem::size_of::<TOKEN_ELEVATION>() as u32,
            &mut returned,
        )
    };
    let _ = unsafe { CloseHandle(token) };
    read.ok()?;
    Some(elevation.TokenIsElevated != 0)
}

/// Samples the whole-CPU and per-processor split together.
///
/// A percentage is the share of the interval between two samples. A call with an
/// earlier sample in the process differences against it. The first call has none, so it
/// primes: it takes a second pair after `PRIME_INTERVAL` and differences that. This
/// used to report the since-boot average in its place, which every one-shot command
/// showed as current load. A per-processor entry whose counters did not move has no
/// interval to share out, and is `None` rather than the fully idle `(0, 0, 100)` it
/// used to be.
///
/// Returns the whole-CPU split, which is an error if it could not be read, and the
/// per-processor entries, which are `None` where no figure was read.
fn sample_cpu_split(cpu_count: usize) -> Result<(Percent3, Option<CoreSplits>)> {
    let now = read_cpu_counters(cpu_count)?;

    // Store this sample and difference against the one it replaces.
    let mut split = match replace_previous_counters(now.clone()) {
        Some(before) => counter_split(&before, &now),
        None => CpuSplit::default(),
    };

    // Retry once if the interval was too short for the counters to move. Each pass
    // stores its later sample, so the next pass differences against it.
    let mut earlier = now;
    for _ in 0..2 {
        if split.system.is_some() {
            break;
        }
        std::thread::sleep(PRIME_INTERVAL);
        let later = read_cpu_counters(cpu_count)?;
        replace_previous_counters(later.clone());
        split = counter_split(&earlier, &later);
        earlier = later;
    }

    // Still no movement after two intervals: report no reading rather than the
    // since-boot split.
    match split.system {
        Some(system) => Ok((system, split.cores)),
        None => Err(IronError::Parse(
            "GetSystemTimes reported no CPU time over the sampling interval".to_string(),
        )),
    }
}

/// Reads the whole-CPU and per-processor counters back to back.
fn read_cpu_counters(cpu_count: usize) -> Result<CpuCounters> {
    Ok(CpuCounters {
        system: read_system_times()?,
        cores: query_per_core_times(cpu_count),
    })
}

/// The split of the interval between two collections, for each figure.
fn counter_split(before: &CpuCounters, now: &CpuCounters) -> CpuSplit {
    CpuSplit {
        system: split_system_times(before.system, now.system),
        cores: match (&before.cores, &now.cores) {
            (Some(before), Some(now)) => split_processor_times(before, now),
            _ => None,
        },
    }
}

/// Reads `GetSystemTimes` once.
fn read_system_times() -> Result<SystemTimesSample> {
    use windows::Win32::Foundation::FILETIME;

    // GetSystemTimes is in kernel32.dll - use raw FFI call
    #[link(name = "kernel32")]
    extern "system" {
        fn GetSystemTimes(
            lpIdleTime: *mut FILETIME,
            lpKernelTime: *mut FILETIME,
            lpUserTime: *mut FILETIME,
        ) -> i32;
    }

    let mut idle_time: FILETIME = unsafe { mem::zeroed() };
    let mut kernel_time: FILETIME = unsafe { mem::zeroed() };
    let mut user_time: FILETIME = unsafe { mem::zeroed() };

    let result = unsafe { GetSystemTimes(&mut idle_time, &mut kernel_time, &mut user_time) };

    if result == 0 {
        return Err(IronError::System("GetSystemTimes failed".to_string()));
    }

    Ok(SystemTimesSample {
        idle: filetime_to_u64(&idle_time),
        kernel: filetime_to_u64(&kernel_time),
        user: filetime_to_u64(&user_time),
    })
}

/// Stores `now` as the previous collection and returns the one it replaces.
fn replace_previous_counters(now: CpuCounters) -> Option<CpuCounters> {
    let mut previous = PREV_CPU_COUNTERS
        .lock()
        .unwrap_or_else(PoisonError::into_inner);
    previous.replace(now)
}

/// The `(user, system, idle)` percentages of the interval between two readings.
///
/// `None` when no interval can be read from them: a counter that went backwards, or
/// no ticks elapsed between the readings. Neither is a split, and neither is replaced
/// by a since-boot figure.
fn split_system_times(
    before: SystemTimesSample,
    now: SystemTimesSample,
) -> Option<(f32, f32, f32)> {
    let idle = now.idle.checked_sub(before.idle)?;
    let kernel = now.kernel.checked_sub(before.kernel)?;
    let user = now.user.checked_sub(before.user)?;
    percentages(user, kernel, idle)
}

/// The per-processor split of the interval between two collections, one entry per
/// processor. `None` if the processor counts differ, since the entries cannot be paired.
fn split_processor_times(
    before: &[SystemProcessorPerformanceInformation],
    now: &[SystemProcessorPerformanceInformation],
) -> Option<Vec<Option<(f32, f32, f32)>>> {
    if before.len() != now.len() {
        return None;
    }
    // The counters are signed in the record. A delta that is negative, or does not fit,
    // is a counter that went backwards and yields no reading for that processor.
    let delta = |now: i64, before: i64| u64::try_from(now.checked_sub(before)?).ok();
    Some(
        before
            .iter()
            .zip(now)
            .map(|(before, now)| {
                percentages(
                    delta(now.user_time, before.user_time)?,
                    delta(now.kernel_time, before.kernel_time)?,
                    delta(now.idle_time, before.idle_time)?,
                )
            })
            .collect(),
    )
}

/// The `(user, system, idle)` percentages from the tick deltas of one interval.
///
/// `kernel` is the kernel time as the API reports it, which includes `idle`, so the
/// system time is the remainder. `None` when no ticks elapsed.
fn percentages(user: u64, kernel: u64, idle: u64) -> Option<(f32, f32, f32)> {
    let system = kernel.checked_sub(idle)?;
    let total = idle.checked_add(system)?.checked_add(user)?;
    if total == 0 {
        return None;
    }

    let basis = total as f64;
    let percent = |ticks: u64| (ticks as f64 / basis * 100.0) as f32;
    Some((percent(user), percent(system), percent(idle)))
}

fn filetime_to_u64(ft: &windows::Win32::Foundation::FILETIME) -> u64 {
    ((ft.dwHighDateTime as u64) << 32) | (ft.dwLowDateTime as u64)
}

/// One entry of the array `CallNtPowerInformation(ProcessorInformation)` writes.
///
/// Mirrors `PROCESSOR_POWER_INFORMATION`. `CurrentMhz` is the live clock, which is
/// the only reason this call is worth making — the registry's `~MHz` is the boot-time
/// nominal and never moves.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct ProcessorPowerInformation {
    number: u32,
    max_mhz: u32,
    current_mhz: u32,
    mhz_limit: u32,
    max_idle_state: u32,
    current_idle_state: u32,
}

/// `ProcessorInformation` power information level.
const PROCESSOR_INFORMATION_LEVEL: i32 = 11;

/// Read per-processor clocks.
///
/// Returns one entry per logical processor, or `None` if the query fails — callers
/// render that as "unavailable" rather than substituting a nominal figure.
fn query_processor_power(cpu_count: usize) -> Option<Vec<ProcessorPowerInformation>> {
    use windows::Win32::System::Power::CallNtPowerInformation;

    if cpu_count == 0 {
        return None;
    }

    let mut buffer: Vec<ProcessorPowerInformation> =
        vec![ProcessorPowerInformation::default(); cpu_count];
    let bytes = std::mem::size_of_val(buffer.as_slice()) as u32;

    let status = unsafe {
        CallNtPowerInformation(
            windows::Win32::System::Power::POWER_INFORMATION_LEVEL(PROCESSOR_INFORMATION_LEVEL),
            None,
            0,
            Some(buffer.as_mut_ptr() as *mut core::ffi::c_void),
            bytes,
        )
    };

    status.ok().ok().map(|_| buffer)
}

/// Get CPU frequency for a specific logical processor.
///
/// Reads `CallNtPowerInformation` rather than shelling out to `wmic`, which Microsoft
/// removed in Windows 11 24H2 — on any current build the subprocess simply failed to
/// spawn, so this returned `None` and the frontends printed "0 MHz" as if measured.
///
/// **`CurrentMhz` is not a current frequency on Windows 10 or later.** It is the
/// nominal clock, and it is returned unchanged whatever the cores are doing. On
/// the 9900X this was found on it read 4400 for all 24 logical processors, idle
/// and under load, across repeated samples — while
/// `\Processor Information(*)\% Processor Performance` showed those same cores
/// at 105–119% of nominal, boosting past 5GHz and differing from each other.
/// WMI agrees with the wrong answer: `CurrentClockSpeed` and `MaxClockSpeed` are
/// both 4400. This is why Task Manager reads the performance counter instead.
///
/// So a `CurrentMhz` equal to `MaxMhz` is reported as no current reading rather
/// than as a measurement. `cpu.core.{n}.frequency` is declared `Measured` and
/// described as "current core clock"; publishing the nominal figure there put a
/// specification behind a measurement's provenance on every core of every
/// Windows machine, and it passed every conformance test because nothing checks
/// whether a value that claims to be current ever changes.
///
/// That suppression is no longer the end of it. `% Processor Performance` is
/// what Task Manager reads, the kernel derives it from APERF and MPERF, and it
/// does vary per core -- 60% to 124% of nominal on this machine, a real
/// 2.6-5.4 GHz spread. [`crate::platform::windows_pdh`] keeps a PDH query open
/// so the two samples a rate needs are consecutive *calls* rather than a sleep
/// inside one, and the nominal maximum times that percentage is reported as the
/// current clock -- flagged `current_is_derived`, because a specification
/// multiplied by a measurement is not a measurement.
fn get_cpu_frequency(
    power: Option<&Vec<ProcessorPowerInformation>>,
    index: usize,
    delivered: Option<&Vec<Option<f64>>>,
) -> Option<CpuFrequency> {
    let entry = power?.get(index)?;
    if entry.current_mhz == 0 && entry.max_mhz == 0 {
        return None;
    }

    // The nominal maximum scaled by delivered performance. Only used when
    // `CurrentMhz` gave nothing, so a platform that does report a real current
    // clock keeps it.
    let derived = delivered
        .and_then(|d| d.get(index).copied().flatten())
        .filter(|pct| *pct > 0.0)
        .map(|pct| (f64::from(entry.max_mhz) * pct / 100.0).round() as u32);

    let measured = (entry.current_mhz != entry.max_mhz).then_some(entry.current_mhz);
    let current_is_derived = measured.is_none() && derived.is_some();

    Some(CpuFrequency {
        current_is_derived,
        // CallNtPowerInformation returns the nominal clock, not the current
        // one: when it equals the maximum for every core, nothing was measured.
        // This used to say `0` and rely on each consumer reading that as an
        // absence. Only the ontology resolver did.
        current: measured.or(derived),
        // No Win32 API reports a minimum operating frequency; leaving it at the
        // measured current would claim a floor that was never read.
        min: None,
        max: (entry.max_mhz > 0).then_some(entry.max_mhz),
    })
}

/// Get CPU model name from the registry.
///
/// `HKLM\HARDWARE\DESCRIPTION\System\CentralProcessor\0\ProcessorNameString` is what
/// the firmware published at boot — the same string WMI reports, without the COM
/// connection or the (now absent) `wmic` subprocess.
///
/// `None` when the value is missing or empty. It used to be `""`, which the
/// resolver published as unavailable and the displays turned into "unknown".
fn get_cpu_model_name() -> Option<String> {
    static MODEL: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
    MODEL
        .get_or_init(|| {
            read_registry_string(
                r"HARDWARE\DESCRIPTION\System\CentralProcessor\0",
                "ProcessorNameString",
            )
        })
        .clone()
}

/// Read one `REG_SZ` value from `HKEY_LOCAL_MACHINE`, trimmed.
///
/// Returns `None` when the key, the value, or a non-empty string is missing, so
/// callers can distinguish "not published by this firmware" from an empty reading.
pub(crate) fn read_registry_string(subkey: &str, value: &str) -> Option<String> {
    use winreg::enums::HKEY_LOCAL_MACHINE;
    use winreg::RegKey;

    let key = RegKey::predef(HKEY_LOCAL_MACHINE)
        .open_subkey(subkey)
        .ok()?;
    let raw: String = key.get_value(value).ok()?;
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        None
    } else {
        Some(trimmed.to_string())
    }
}

/// Read one `REG_DWORD` value from `HKEY_LOCAL_MACHINE`.
///
/// `None` means the key or value is absent, which is not the same as a value of 0 —
/// a distinction that matters for flags like `UEFISecureBootEnabled`, where "no such
/// setting" and "the setting is off" have different causes.
pub(crate) fn read_registry_u32(subkey: &str, value: &str) -> Option<u32> {
    use winreg::enums::HKEY_LOCAL_MACHINE;
    use winreg::RegKey;

    let key = RegKey::predef(HKEY_LOCAL_MACHINE)
        .open_subkey(subkey)
        .ok()?;
    key.get_value(value).ok()
}

/// True VRAM in bytes for each display adapter, from the driver's own registry
/// key, paired with the `DriverDesc` it belongs to.
///
/// `Win32_VideoController.AdapterRAM` is a 32-bit field. An RTX 3090 Ti with 24GB
/// reports 4293918720 through it — just under 4GiB — and every card above 4GB
/// reports something similarly wrong. `hardware_ai` divided that by 2^30, got
/// 4.0, and concluded "Insufficient VRAM for ML training" about a card that has
/// 24GB of it.
///
/// The display-adapter class key carries `HardwareInformation.qwMemorySize`, a
/// `REG_QWORD` with the real figure: 25757220864 on the same machine. It needs no
/// elevation. The 32-bit `HardwareInformation.MemorySize` sits beside it holding
/// the same wrong number as WMI, which is a useful reminder that the overflow is
/// in the field width and not in the query.
///
/// Adapters whose key carries no `qwMemorySize` are omitted rather than reported
/// at whatever the 32-bit value says. A caller that cannot find its adapter here
/// has not learnt that the card has 4GB; it has learnt nothing, which is the
/// truth.
pub(crate) fn adapter_vram_bytes() -> Vec<(String, u64)> {
    use winreg::enums::HKEY_LOCAL_MACHINE;
    use winreg::RegKey;

    // The GUID_DEVCLASS_DISPLAY class key. Subkeys are `0000`, `0001`, ... one
    // per adapter the driver stack knows about.
    const DISPLAY_CLASS: &str =
        r"SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}";

    let Ok(class_key) = RegKey::predef(HKEY_LOCAL_MACHINE).open_subkey(DISPLAY_CLASS) else {
        return Vec::new();
    };

    let names: Vec<String> = class_key.enum_keys().flatten().collect();

    names
        .into_iter()
        .filter_map(|name| {
            let key = class_key.open_subkey(&name).ok()?;
            let desc: String = key.get_value("DriverDesc").ok()?;
            let bytes: u64 = key.get_value("HardwareInformation.qwMemorySize").ok()?;
            (bytes > 0).then(|| (desc.trim().to_string(), bytes))
        })
        .collect()
}

/// Whether the machine booted via UEFI, legacy BIOS, or something unreported.
///
/// `GetFirmwareType` is the documented Win32 answer. The alternative in use before
/// this — testing `$env:firmware_type` from a spawned PowerShell — reads an
/// environment variable that Windows does not set for a non-interactive child, so it
/// was empty on every call and every machine fell through to "Legacy".
pub(crate) fn firmware_type() -> Option<crate::boot_config::BootType> {
    use windows::Win32::System::SystemInformation::{
        FirmwareTypeBios, FirmwareTypeUefi, GetFirmwareType, FIRMWARE_TYPE,
    };

    let mut kind = FIRMWARE_TYPE::default();
    unsafe { GetFirmwareType(&mut kind) }.ok()?;

    // Compared rather than matched: these are lowercase constants, and a `match` arm
    // naming one that failed to resolve would become an irrefutable binding that
    // silently swallows every other value.
    if kind == FirmwareTypeUefi {
        Some(crate::boot_config::BootType::Uefi)
    } else if kind == FirmwareTypeBios {
        Some(crate::boot_config::BootType::Legacy)
    } else {
        None
    }
}

/// Whether UEFI Secure Boot is currently enforcing.
///
/// Reads `UEFISecureBootEnabled` rather than testing for the key that contains it:
/// `SecureBoot\State` exists on every UEFI machine, enabled or not, so its presence
/// says only that the firmware is UEFI. Callers that tested existence reported Secure
/// Boot as on for every UEFI system.
pub(crate) fn secure_boot_enabled() -> Option<bool> {
    read_registry_u32(
        r"SYSTEM\CurrentControlSet\Control\SecureBoot\State",
        "UEFISecureBootEnabled",
    )
    .map(|v| v == 1)
}

/// Pagefile capacity and usage, from `Win32_PageFileUsage`.
///
/// `AllocatedBaseSize` and `CurrentUsage` are both in megabytes and describe
/// the pagefile itself -- not the commit limit, which is what every native API
/// on this platform offers and what this reader used to publish.
///
/// A machine can have several pagefiles, so the rows are summed. No pagefile at
/// all is a real reading of zero; a query that fails is `None`.
#[cfg(target_os = "windows")]
fn read_pagefile_usage() -> Option<SwapInfo> {
    use serde::Deserialize;
    use wmi::{COMLibrary, WMIConnection};

    #[derive(Deserialize)]
    #[serde(rename_all = "PascalCase")]
    struct PageFileUsage {
        allocated_base_size: u32,
        current_usage: u32,
    }

    let com = COMLibrary::new().ok()?;
    let conn = WMIConnection::new(com).ok()?;
    let rows: Vec<PageFileUsage> = conn
        .raw_query("SELECT AllocatedBaseSize, CurrentUsage FROM Win32_PageFileUsage")
        .ok()?;

    let mb_to_kb = |mb: u32| u64::from(mb) * 1024;
    Some(SwapInfo {
        total: Some(rows.iter().map(|r| mb_to_kb(r.allocated_base_size)).sum()),
        used: Some(rows.iter().map(|r| mb_to_kb(r.current_usage)).sum()),
        cached: None,
    })
}

/// Read memory statistics on Windows
pub fn read_memory_stats() -> Result<MemoryStats> {
    let mut mem_status: MEMORYSTATUSEX = unsafe { mem::zeroed() };
    mem_status.dwLength = mem::size_of::<MEMORYSTATUSEX>() as u32;

    unsafe {
        GlobalMemoryStatusEx(&mut mem_status)
            .map_err(|e| IronError::System(format!("GlobalMemoryStatusEx failed: {}", e)))?;
    }

    // Pagefile usage.
    //
    // This used to come from `GetPerformanceInfo`:
    //
    // ```ignore
    // let total_pages = perf_info.CommitLimit as u64;
    // let used_pages  = perf_info.CommitTotal as u64;
    // ```
    //
    // Those are **commit accounting**, not pagefile accounting. The commit
    // limit is RAM plus pagefile, and the commit charge is every byte of
    // private memory the system has promised -- most of which is resident in
    // RAM and has never been written to disk. Renaming them `total_pages` and
    // `used_pages` and storing them in `SwapInfo` made the numbers say
    // something they do not mean. On the development machine:
    //
    // ```text
    // reported:  swap total 154 GB   swap used 97 GB
    // actual:    pagefile   50 GB    in use    3.4 GB
    // ```
    //
    // 97 GB of swap in use on a host with 93.6 GB of RAM, 52.8 GB of it used,
    // is not a plausible reading, and an agent asked whether the machine is
    // thrashing would have said yes. The `MEMORYSTATUSEX` fallback below it
    // had the same defect wearing a more convincing name:
    // `ullTotalPageFile` is documented as the commit limit, not the pagefile.
    //
    // `Win32_PageFileUsage` reports the real figures and needs no elevation.
    // It is a WMI round trip, which is why the physical-memory numbers above
    // still come from the native call.
    let swap_info = read_pagefile_usage().unwrap_or(SwapInfo {
        // Not read. Better nothing than the commit charge wearing this name.
        total: None,
        used: None,
        // Windows exposes no cached-swap figure. `None`, not zero: the
        // quantity is unreported, not measured at nothing.
        cached: None,
    });

    // The system file cache, in KB. `GetPerformanceInfo` reports it in pages.
    //
    // This call used to sit here computing swap from `CommitLimit` and
    // `CommitTotal`, which are commit accounting and not pagefile accounting;
    // that reading was wrong and was removed. `SystemCache` is a different
    // field of the same struct and is exactly what it says, so the call comes
    // back for the one quantity it does answer.
    let system_cache_kb = {
        let mut perf: PERFORMANCE_INFORMATION = unsafe { mem::zeroed() };
        perf.cb = mem::size_of::<PERFORMANCE_INFORMATION>() as u32;
        if unsafe { GetPerformanceInfo(&mut perf, perf.cb) }.is_ok() {
            Some((perf.SystemCache as u64).saturating_mul(perf.PageSize as u64) / 1024)
        } else {
            None
        }
    };

    let total_kb = mem_status.ullTotalPhys / 1024;
    let avail_kb = mem_status.ullAvailPhys / 1024;
    let used_kb = total_kb - avail_kb;

    Ok(MemoryStats {
        ram: RamInfo {
            total: total_kb,
            used: used_kb,
            // Not `avail_kb`: that is the available figure, standby list
            // included, and it was published here as "free" -- nearly twice
            // the real figure on the machine it was found on. See
            // `windows_pdh::free_and_zero_page_list_bytes`.
            free: crate::platform::windows_pdh::free_and_zero_page_list_bytes()
                .map(|bytes| bytes / 1024),
            // Windows has no "buffers" figure at all -- it is a Linux
            // `/proc/meminfo` line -- so this is an absence, not a zero.
            buffers: None,
            // The system file cache, in pages, which is where Task Manager's
            // "Cached" figure comes from.
            //
            // Do not "correct" this to perfmon's `\Memory\Cache Bytes`. They
            // are different quantities and differ by fifty-fold: on this host
            // `SystemCache` reads 52.1 GB while `Cache Bytes` reads 1.0 GB,
            // because the first counts every cached page (standby 48.5 GB plus
            // modified 0.4 GB plus resident 1.0 GB) and the second counts only
            // the cache's own resident working set. The 52 GB figure is the one
            // that corresponds to Linux's `Cached` line, which is what this
            // field means.
            cached: system_cache_kb,
            // Not read on Windows. `None` rather than a zero that reads like a
            // measurement of no shared memory.
            shared: None,
            lfb: None,
        },
        swap: swap_info,
        emc: None,  // Not applicable to Windows
        iram: None, // Not applicable to Windows
    })
}

/// Get system uptime on Windows
pub fn get_system_uptime() -> std::time::Duration {
    use windows::Win32::System::SystemInformation::GetTickCount64;

    let ticks = unsafe { GetTickCount64() };
    std::time::Duration::from_millis(ticks)
}

/// Detected GPUs, kept alive across calls.
///
/// Enumeration opens vendor libraries (NVML, DXGI/WMI) and costs tens to hundreds
/// of milliseconds; [`read_gpu_stats`] is called once per tick by the interactive
/// monitor, so re-enumerating every time would dominate the tick. `Gpu` is
/// `Send + Sync`, so the collection can live in a static behind a mutex.
static GPU_COLLECTION: std::sync::OnceLock<std::sync::Mutex<crate::gpu::GpuCollection>> =
    std::sync::OnceLock::new();

/// Read GPU stats via the `gpu` module's vendor adapters.
///
/// This used to return `GpuStats::new()` unconditionally, so every consumer of
/// `IronMonitor::snapshot()` on Windows — including `ironmon cli monitor` — reported
/// "No GPUs detected" on machines where `ironmon cli gpu`, in the same binary,
/// listed every device.
///
/// A device whose per-tick query fails is omitted rather than emitted with zeroed
/// fields: a GPU reported at 0% load and 0°C is worse than a GPU not reported.
pub fn read_gpu_stats() -> Result<GpuStats> {
    use crate::core::gpu::{GpuFrequency, GpuInfo, GpuStatus, GpuType};

    let mut stats = GpuStats::new();

    let collection = GPU_COLLECTION.get_or_init(|| {
        std::sync::Mutex::new(crate::gpu::GpuCollection::auto_detect().unwrap_or_default())
    });
    let collection = collection
        .lock()
        .map_err(|_| IronError::HardwareError("GPU collection mutex poisoned".to_string()))?;

    let snapshots = collection.snapshot_all_partial();
    let gpus = stats.gpus_mut();

    for info in snapshots.into_iter().flatten() {
        let si = &info.static_info;
        let di = &info.dynamic_info;

        let status = GpuStatus {
            load: di.utilization.map(f32::from),
            railgate: None,
            tpc_pg_mask: None,
            scaling_3d: None,
            // This already treated a zero total as an absence and wrapped the
            // three figures in `Some` only when it was non-zero. The type says
            // it now, so the guard is gone rather than duplicated.
            memory_used: di.memory.used,
            memory_total: di.memory.total,
            memory_free: di.memory.free,
            // `GpuThermal::temperature` is already degrees Celsius.
            temperature: di.thermal.temperature.map(|t| t as f32),
            // `GpuPower` is milliwatts; `GpuStatus` is watts.
            power_draw: di.power.draw.map(|mw| mw as f32 / 1000.0),
            power_limit: di.power.limit.map(|mw| mw as f32 / 1000.0),
        };

        let frequency = GpuFrequency {
            // Carried through, not flattened. `GpuClocks::graphics` is
            // `Option` precisely so an unreadable clock is not 0 MHz, and
            // `.unwrap_or(0)` here undid that for every Windows GPU.
            current: di.clocks.graphics.or(di.clocks.sm),
            // No vendor adapter reports a minimum clock.
            min: None,
            max: di.clocks.graphics_max,
            // `governor` is a Linux DVFS concept; Windows has no equivalent, and
            // naming the vendor here would present it as one.
            governor: None,
            gpc: None,
        };

        let gpu = GpuInfo {
            gpu_type: match si.integrated {
                Some(true) => GpuType::Integrated,
                Some(false) => GpuType::Discrete,
                None => GpuType::Unknown,
            },
            status,
            frequency,
            // Not read. This was the vendor name, which identifies the adapter and
            // does not name a power-control method.
            power_control: None,
        };

        // `GpuStats` is keyed by name, and identical cards are common (two
        // RTX 3090s report the same string). Disambiguate by index so a
        // second card cannot silently overwrite the first.
        let key = if gpus.contains_key(&si.name) {
            format!("{} #{}", si.name, si.index)
        } else {
            si.name.clone()
        };
        gpus.insert(key, gpu);
    }

    Ok(stats)
}

/// Read power rails on Windows.
///
/// Windows exposes no general system power telemetry, so the only rail available is
/// a battery or UPS, and only when its driver publishes a real charge or discharge
/// rate through `root\WMI\BatteryStatus`.
///
/// This previously derived "power" from `Win32_Battery` as
/// `full_charge_capacity * design_voltage / 1000 / 3` — the pack's total energy
/// spread over an assumed three-hour discharge. That is not a measurement of
/// anything: it is a constant for a given battery, unchanged by what the machine is
/// doing, and it was reported as a live power rail. When those fields were absent (a
/// USB-attached UPS reports neither) it collapsed to 0, so `ironmon cli monitor`
/// displayed "Total Power: 0.00W" on a desktop drawing hundreds of watts.
///
/// A rail is now emitted only when a rate was actually read. A machine with no
/// battery, or a UPS whose driver publishes no rate, reports no rails at all, and
/// callers should say "not measured" rather than "0 W".
pub fn read_power_stats() -> Result<PowerStats> {
    use serde::Deserialize;
    use wmi::{COMLibrary, WMIConnection};

    /// `root\WMI` battery telemetry. Rates are milliwatts, voltage millivolts.
    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    struct BatteryStatus {
        instance_name: Option<String>,
        voltage: Option<u32>,
        discharge_rate: Option<u32>,
        charge_rate: Option<u32>,
        discharging: Option<bool>,
    }

    let mut power_stats = PowerStats::default();

    let Ok(com_con) = COMLibrary::new() else {
        return Ok(power_stats);
    };
    // `BatteryStatus` lives in root\WMI, not root\CIMV2, and is absent entirely on
    // desktops and on UPS units attached over USB HID.
    let Ok(wmi_con) = WMIConnection::with_namespace_path("root\\WMI", com_con) else {
        return Ok(power_stats);
    };

    let batteries: Vec<BatteryStatus> = wmi_con
        .raw_query(
            "SELECT InstanceName, Voltage, DischargeRate, ChargeRate, Discharging \
             FROM BatteryStatus",
        )
        .unwrap_or_default();

    for (idx, battery) in batteries.iter().enumerate() {
        // At most one rate is non-zero at a time; whichever it is, it is measured.
        // Both present and zero means idle on AC, which is also a real reading.
        let (rate_mw, sensor_type) = match (battery.discharge_rate, battery.charge_rate) {
            (Some(d), _) if d > 0 => (d, "Battery (discharging)"),
            (_, Some(c)) if c > 0 => (c, "Battery (charging)"),
            // Zero rates with an unread `Discharging` flag: the state is not known,
            // so the label says only "Battery". It used to fall back to "idle", which
            // was a guess taken from a missing flag.
            (Some(_), _) | (_, Some(_)) => (
                0,
                match battery.discharging {
                    Some(true) => "Battery (discharging)",
                    Some(false) => "Battery (idle)",
                    None => "Battery",
                },
            ),
            // Neither rate was reported: nothing was measured, so emit nothing.
            (None, None) => continue,
        };

        let name = battery
            .instance_name
            .clone()
            .unwrap_or_else(|| format!("Battery{}", idx));

        power_stats.rails.insert(
            name,
            crate::core::power::PowerRail {
                online: true,
                sensor_type: sensor_type.to_string(),
                voltage: battery.voltage,
                // Not exposed by this class. This was `0`, with that sentence
                // as a comment beside it -- the comment was right and the
                // field said 0 mA.
                current: None,
                power: Some(rate_mw),
                // Not read: the battery class reports only the instantaneous
                // rate. This was `Some(rate_mw)`, one sample passed off as an
                // average.
                average: None,
                warn: None,
                crit: None,
            },
        );

        // Accumulated across batteries; `empty()` starts at `None`, and the
        // first battery with a reading establishes the total.
        power_stats.total.power = Some(power_stats.total.power.unwrap_or(0) + rate_mw);
        // No total average either: the sum above is instantaneous.
    }

    Ok(power_stats)
}

/// Read temperature stats from WMI thermal zones and optionally Open Hardware Monitor
pub fn read_temperature_stats() -> Result<TemperatureStats> {
    use serde::Deserialize;
    use std::collections::HashMap;
    use wmi::{COMLibrary, WMIConnection};

    // WMI thermal zone structure (in tenths of Kelvin)
    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    struct ThermalZone {
        instance_name: String,
        current_temperature: u32, // In tenths of Kelvin
        // The zone's own shutdown threshold, in tenths of Kelvin; 0 or absent
        // where the firmware declares none.
        critical_trip_point: Option<u32>,
    }

    // Performance counter thermal zone (Kelvin)
    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    struct PerfThermalZone {
        name: String,
        temperature: u32, // In Kelvin (not tenths!)
    }

    // Open Hardware Monitor sensor structure (if OHM is installed)
    #[derive(Deserialize, Debug)]
    #[serde(rename_all = "PascalCase")]
    #[allow(dead_code)]
    struct OhmSensor {
        name: String,
        sensor_type: String,
        value: f32,
        parent: String,
    }

    let mut sensors = HashMap::new();

    // Initialize COM library
    let com_con = COMLibrary::new()
        .map_err(|e| IronError::System(format!("Failed to initialize COM: {}", e)))?;

    // Try to get CPU temperature from Open Hardware Monitor if available
    // OHM exposes sensors via WMI in root\OpenHardwareMonitor namespace
    if let Ok(ohm_con) = WMIConnection::with_namespace_path("root\\OpenHardwareMonitor", com_con) {
        let ohm_sensors: Vec<OhmSensor> = ohm_con
            .raw_query("SELECT Name, SensorType, Value, Parent FROM Sensor WHERE SensorType = 'Temperature'")
            .unwrap_or_default();

        for sensor in ohm_sensors {
            // Filter to CPU and motherboard temperatures
            let sensor_name = if sensor.parent.contains("CPU") || sensor.name.contains("CPU") {
                format!("CPU-{}", sensor.name.replace(' ', "_"))
            } else if sensor.parent.contains("Motherboard") {
                format!("MB-{}", sensor.name.replace(' ', "_"))
            } else {
                continue; // Skip other sensors (GPU temps come from NVML)
            };

            sensors.insert(
                sensor_name,
                crate::core::temperature::TemperatureSensor {
                    online: true,
                    temp: sensor.value,
                    // The Sensor class reports a value and no threshold. These
                    // were 95 and 105 for every CPU and motherboard sensor,
                    // whatever the part.
                    max: None,
                    crit: None,
                },
            );
        }
    }

    // Try LibreHardwareMonitor as well (fork of OHM with better modern hardware support)
    if let Ok(lhm_con) = WMIConnection::with_namespace_path("root\\LibreHardwareMonitor", com_con) {
        let lhm_sensors: Vec<OhmSensor> = lhm_con
            .raw_query("SELECT Name, SensorType, Value, Parent FROM Sensor WHERE SensorType = 'Temperature'")
            .unwrap_or_default();

        for sensor in lhm_sensors {
            // Filter to CPU and motherboard temperatures
            let sensor_name = if sensor.parent.contains("CPU") || sensor.name.contains("CPU") {
                format!("CPU-{}", sensor.name.replace(' ', "_"))
            } else if sensor.parent.contains("Motherboard") {
                format!("MB-{}", sensor.name.replace(' ', "_"))
            } else {
                continue;
            };

            // Only add if not already present from OHM
            if let std::collections::hash_map::Entry::Vacant(e) = sensors.entry(sensor_name) {
                e.insert(crate::core::temperature::TemperatureSensor {
                    online: true,
                    temp: sensor.value,
                    // The Sensor class reports a value and no threshold. These
                    // were 95 and 105 for every CPU and motherboard sensor,
                    // whatever the part.
                    max: None,
                    crit: None,
                });
            }
        }
    }

    // Try CIMV2 performance counters for thermal zone info (more widely available)
    if let Ok(cimv2_con) = WMIConnection::with_namespace_path("root\\CIMV2", com_con) {
        let perf_zones: Vec<PerfThermalZone> = cimv2_con
            .raw_query("SELECT Name, Temperature FROM Win32_PerfFormattedData_Counters_ThermalZoneInformation")
            .unwrap_or_default();

        for zone in perf_zones {
            // Temperature is in Kelvin, convert to Celsius
            let temp_celsius = zone.temperature as f32 - 273.15;

            // Only add valid temperatures
            if temp_celsius > 0.0 && temp_celsius < 150.0 {
                let sensor_name = format!("TZ-{}", zone.name.replace("\\_TZ.", ""));
                sensors
                    .entry(sensor_name)
                    .or_insert(crate::core::temperature::TemperatureSensor {
                        online: true,
                        temp: temp_celsius,
                        // The performance counter carries no trip points.
                        max: None,
                        crit: None,
                    });
            }
        }
    }

    // Try ACPI thermal zones in root\WMI (requires admin, but try anyway)
    if let Ok(wmi_con) = WMIConnection::with_namespace_path("root\\WMI", com_con) {
        let thermal_zones: Vec<ThermalZone> = wmi_con
            .raw_query(
                "SELECT InstanceName, CurrentTemperature, CriticalTripPoint \
                 FROM MSAcpi_ThermalZoneTemperature",
            )
            .unwrap_or_default();

        for zone in thermal_zones {
            // Convert from tenths of Kelvin to Celsius
            let temp_celsius = (zone.current_temperature as f32 / 10.0) - 273.15;

            // Only add valid temperatures (ignore invalid readings)
            if temp_celsius > 0.0 && temp_celsius < 150.0 {
                let sensor_name = zone
                    .instance_name
                    .replace("ACPI\\ThermalZone\\", "")
                    .replace("_0", "");
                if !sensors.contains_key(&format!("TZ-{}", sensor_name)) {
                    sensors.insert(
                        format!("ACPI-{}", sensor_name),
                        crate::core::temperature::TemperatureSensor {
                            online: true,
                            temp: temp_celsius,
                            // ACPI declares the passive and active trip points
                            // as cooling policy, not as a maximum; none of them
                            // is this field.
                            max: None,
                            // The firmware's own critical trip point, where it
                            // declares one. This was 105 for every zone.
                            crit: zone
                                .critical_trip_point
                                .filter(|&t| t > 0)
                                .map(|t| t as f32 / 10.0 - 273.15),
                        },
                    );
                }
            }
        }
    }

    Ok(TemperatureStats { sensors })
}

pub fn detect_platform() -> Result<BoardInfo> {
    // SMBIOS baseboard fields, as the firmware published them at boot. Formerly read
    // by shelling out to `wmic baseboard`, which no longer exists on Windows 11 24H2
    // and later — every board there reported itself as "Unknown".
    const BIOS_KEY: &str = r"HARDWARE\DESCRIPTION\System\BIOS";
    let manufacturer = read_registry_string(BIOS_KEY, "BaseBoardManufacturer");
    let model = read_registry_string(BIOS_KEY, "BaseBoardProduct");

    const CURRENT_VERSION: &str = r"SOFTWARE\Microsoft\Windows NT\CurrentVersion";

    // `release` is the OS release — the analogue of `uname -r`. It was the constant
    // "NT", which names the kernel lineage and is the same string on every Windows
    // since 1993, so `ironmon cli board` printed "Kernel: NT" as though it had read
    // something. `distribution` was left empty despite the edition being published
    // right next to the build number.
    let build = read_registry_string(CURRENT_VERSION, "CurrentBuildNumber");
    let release = match (&build, read_registry_u32(CURRENT_VERSION, "UBR")) {
        (Some(build), Some(ubr)) => format!("{build}.{ubr}"),
        (Some(build), None) => build.clone(),
        // Nothing was read, so nothing is claimed.
        (None, _) => String::new(),
    };

    let distribution = read_registry_string(CURRENT_VERSION, "ProductName").map(|product| {
        // The registry still says "Windows 10" on Windows 11; build 22000 is the
        // documented dividing line.
        let build: u32 = build.as_deref().and_then(|b| b.parse().ok()).unwrap_or(0);
        if build >= 22000 {
            product.replace("Windows 10", "Windows 11")
        } else {
            product
        }
    });

    Ok(BoardInfo {
        platform: PlatformInfo {
            machine: std::env::consts::ARCH.to_string(),
            system: "Windows".to_string(),
            distribution,
            release,
        },
        hardware: HardwareInfo {
            // Empty, not "Unknown": the resolver publishes an empty model as
            // unavailable. This used to name the board "Unknown".
            model: model.unwrap_or_default(),
            p_number: None,
            module: manufacturer,
            soc: None,
            cuda_arch: None,
            codename: None,
            serial_number: None,
            l4t: None,
            jetpack: None,
        },
        libraries: LibraryVersions {
            cuda: None,
            cudnn: None,
            tensorrt: None,
            other: HashMap::new(),
        },
    })
}

/// Read process statistics on Windows using CreateToolhelp32Snapshot
pub fn read_process_stats() -> Result<crate::core::process::ProcessStats> {
    use crate::core::process::{ProcessInfo, ProcessStats};
    use std::mem;
    use windows::Win32::Foundation::CloseHandle;
    use windows::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
        TH32CS_SNAPPROCESS,
    };
    use windows::Win32::System::ProcessStatus::{GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS};
    use windows::Win32::System::Threading::{
        OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_VM_READ,
    };

    let mut stats = ProcessStats::empty();

    unsafe {
        // Create snapshot of all processes
        let snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
            .map_err(|e| IronError::System(format!("Failed to create process snapshot: {}", e)))?;

        let mut entry: PROCESSENTRY32W = mem::zeroed();
        entry.dwSize = mem::size_of::<PROCESSENTRY32W>() as u32;

        // Iterate through processes
        if Process32FirstW(snapshot, &mut entry).is_ok() {
            loop {
                let pid = entry.th32ProcessID;

                // Get process name from entry
                let name_len = entry
                    .szExeFile
                    .iter()
                    .position(|&c| c == 0)
                    .unwrap_or(entry.szExeFile.len());
                let name = String::from_utf16_lossy(&entry.szExeFile[..name_len]);

                // Try to open process for more info
                let mut memory_kb = 0u64;

                if let Ok(process_handle) =
                    OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)
                {
                    // Get memory info
                    let mut mem_counters: PROCESS_MEMORY_COUNTERS = mem::zeroed();
                    mem_counters.cb = mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32;

                    if GetProcessMemoryInfo(
                        process_handle,
                        &mut mem_counters,
                        mem::size_of::<PROCESS_MEMORY_COUNTERS>() as u32,
                    )
                    .is_ok()
                    {
                        memory_kb = mem_counters.WorkingSetSize as u64 / 1024;
                    }

                    let _ = CloseHandle(process_handle);
                }

                // Not read. This was (kernel + user time) / system uptime, clamped
                // to 100. That is neither current load nor a lifetime average: the
                // denominator was the machine's uptime rather than the process's
                // lifetime, and the clamp hid every multi-core value above 100.
                // A CPU share is a rate, and a rate needs two samples; this
                // snapshot reader keeps no previous sample per pid. The ontology's
                // `process.{pid}.cpu` is differenced over an interval by the
                // process monitor.
                let cpu_percent: Option<f32> = None;

                // Not read. This was `R` whenever the process had a thread, which
                // is every process, so the R/S split it produced was a constant.
                // Toolhelp does not report a run state, and the thread count is
                // not one.
                let state = None;

                // Only include processes with significant memory usage (> 1MB)
                if memory_kb > 1024 {
                    stats.processes.push(ProcessInfo {
                        pid,
                        user: String::new(), // Would need additional API calls
                        gpu: String::new(),
                        // Not read. This was "System" on every process, which
                        // is not a classification the process table carries.
                        process_type: None,
                        priority: entry.pcPriClassBase as i32,
                        state,
                        cpu_percent,
                        memory_kb,
                        // Not read here, and no GPU module fills it in. This was
                        // `0`, which reads as "no GPU memory in use".
                        gpu_memory_kb: None,
                        name,
                    });
                }

                // Move to next process
                if Process32NextW(snapshot, &mut entry).is_err() {
                    break;
                }
            }
        }

        let _ = CloseHandle(snapshot);
    }

    // Sort by memory usage (descending)
    stats
        .processes
        .sort_by_key(|p| std::cmp::Reverse(p.memory_kb));

    // Keep top 50 processes
    stats.processes.truncate(50);

    Ok(stats)
}

// ============================================================================
// Logical drive enumeration
// ============================================================================

/// A mounted logical drive with capacity and filesystem information.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LogicalDrive {
    /// Drive root, e.g. `C:\`.
    pub name: String,
    /// Total capacity in bytes.
    pub total: u64,
    /// Used bytes (total minus free).
    pub used: u64,
    /// Free bytes available to the caller.
    pub free: u64,
    /// Filesystem name as reported by the volume, e.g. `NTFS`, `exFAT`.
    pub filesystem: String,
}

/// Enumerate mounted logical drives.
///
/// This is deliberately cheaper and safer than probing `A:`..`Z:` with
/// `fs::metadata`:
///
/// - `GetLogicalDrives` returns the present-drive bitmask in a single call rather
///   than 26 filesystem round-trips.
/// - Network (`DRIVE_REMOTE`) and optical (`DRIVE_CDROM`) volumes are skipped.
///   A disconnected mapped network drive can block for seconds on capacity queries,
///   which would stall the collector tick.
/// - The filesystem name comes from `GetVolumeInformationW` instead of being
///   hardcoded to `"NTFS"`.
pub fn logical_drives() -> Result<Vec<LogicalDrive>> {
    use windows::core::PCWSTR;
    use windows::Win32::Storage::FileSystem::{
        GetDiskFreeSpaceExW, GetDriveTypeW, GetLogicalDrives, GetVolumeInformationW,
    };

    const DRIVE_REMOTE: u32 = 4;
    const DRIVE_CDROM: u32 = 5;

    let mask = unsafe { GetLogicalDrives() };
    if mask == 0 {
        return Err(IronError::Other(
            "GetLogicalDrives returned no drives".to_string(),
        ));
    }

    let mut drives = Vec::new();

    for bit in 0..26u32 {
        if mask & (1 << bit) == 0 {
            continue;
        }

        let letter = b'A' + bit as u8;
        // Drive roots are pure ASCII, so build the wide string directly rather than
        // allocating through OsStr.
        let root_wide: [u16; 4] = [letter as u16, b':' as u16, b'\\' as u16, 0];
        let root = PCWSTR(root_wide.as_ptr());

        // Skip volumes whose capacity queries can block.
        let drive_type = unsafe { GetDriveTypeW(root) };
        if drive_type == DRIVE_REMOTE || drive_type == DRIVE_CDROM {
            continue;
        }

        let mut free_to_caller: u64 = 0;
        let mut total: u64 = 0;
        let mut total_free: u64 = 0;

        let has_space = unsafe {
            GetDiskFreeSpaceExW(
                root,
                Some(&mut free_to_caller),
                Some(&mut total),
                Some(&mut total_free),
            )
            .is_ok()
        };

        // An empty card reader reports as present but has no media.
        if !has_space || total == 0 {
            continue;
        }

        let mut fs_buf = [0u16; 32];
        let filesystem = unsafe {
            if GetVolumeInformationW(root, None, None, None, None, Some(&mut fs_buf)).is_ok() {
                let len = fs_buf.iter().position(|&c| c == 0).unwrap_or(fs_buf.len());
                String::from_utf16_lossy(&fs_buf[..len])
            } else {
                "Unknown".to_string()
            }
        };

        drives.push(LogicalDrive {
            name: format!("{}:\\", letter as char),
            total,
            used: total.saturating_sub(total_free),
            free: free_to_caller,
            filesystem,
        });
    }

    Ok(drives)
}

#[cfg(test)]
mod tests {

    /// Counters of a 4-processor machine, in 100 ns ticks. One second of wall time
    /// is 10_000_000 ticks per processor, so 40_000_000 across all four.
    fn system_sample(idle: u64, kernel: u64, user: u64) -> super::SystemTimesSample {
        super::SystemTimesSample { idle, kernel, user }
    }

    #[test]
    fn system_times_split_is_the_interval_between_two_readings() {
        // Since boot the machine is mostly idle, so the cumulative figures would say
        // 90%+ idle. The second reading is one second later, with the machine 75%
        // idle over that second: the split must follow the interval, not the totals.
        let before = system_sample(900_000_000_000, 960_000_000_000, 40_000_000_000);
        let now = system_sample(
            before.idle + 30_000_000,   // 75% of the 40M ticks
            before.kernel + 35_000_000, // kernel includes idle: 5M system ticks
            before.user + 5_000_000,
        );

        let (user, system, idle) = super::split_system_times(before, now).expect("split");
        assert!((user - 12.5).abs() < 0.01, "user {user}");
        assert!((system - 12.5).abs() < 0.01, "system {system}");
        assert!((idle - 75.0).abs() < 0.01, "idle {idle}");
    }

    #[test]
    fn system_times_zero_delta_is_no_reading() {
        // Two reads inside one scheduler tick: nothing moved, so there is no split.
        // The old code answered the since-boot split here instead.
        let sample = system_sample(900_000_000_000, 960_000_000_000, 40_000_000_000);
        assert_eq!(super::split_system_times(sample, sample), None);
    }

    #[test]
    fn system_times_counter_going_backwards_is_no_reading() {
        // A counter that decreases cannot be differenced. Treating it as zero would
        // skew the split, so it yields no reading.
        let before = system_sample(900_000_000_000, 960_000_000_000, 40_000_000_000);
        let now = system_sample(
            before.idle - 1,
            before.kernel + 35_000_000,
            before.user + 5_000_000,
        );
        assert_eq!(super::split_system_times(before, now), None);
    }

    #[test]
    fn system_times_kernel_below_idle_is_no_reading() {
        // Kernel time includes idle, so it cannot have grown by less than idle did.
        let before = system_sample(900_000_000_000, 960_000_000_000, 40_000_000_000);
        let now = system_sample(
            before.idle + 30_000_000,
            before.kernel + 20_000_000,
            before.user + 5_000_000,
        );
        assert_eq!(super::split_system_times(before, now), None);
    }

    /// A per-processor record with the given cumulative counters.
    fn processor(
        idle: i64,
        kernel: i64,
        user: i64,
    ) -> super::SystemProcessorPerformanceInformation {
        super::SystemProcessorPerformanceInformation {
            idle_time: idle,
            kernel_time: kernel,
            user_time: user,
            ..Default::default()
        }
    }

    #[test]
    fn processor_times_split_is_the_interval_between_two_readings() {
        // One second is 10_000_000 ticks. Over the second the processor was idle for
        // 7_500_000 ticks and in the kernel for 8_000_000 ticks (kernel includes idle, so
        // 500_000 of system work), and in user mode for 2_000_000. Kernel plus user is the
        // whole second: 75% idle, 5% system, 20% user.
        let before = processor(500_000_000, 600_000_000, 100_000_000);
        let now = processor(
            before.idle_time + 7_500_000,
            before.kernel_time + 8_000_000,
            before.user_time + 2_000_000,
        );

        let splits = super::split_processor_times(&[before], &[now]).expect("split");
        let (user, system, idle) = splits[0].expect("a core that moved has a split");
        assert!((user - 20.0).abs() < 0.01, "user {user}");
        assert!((system - 5.0).abs() < 0.01, "system {system}");
        assert!((idle - 75.0).abs() < 0.01, "idle {idle}");
    }

    #[test]
    fn processor_with_no_movement_is_no_reading_for_that_core_only() {
        // Core 0 did not move between the two collections; core 1 did. Core 0 must be
        // `None`, not the fully idle split, and core 1 must still be reported.
        let still = processor(500_000_000, 600_000_000, 100_000_000);
        let moved_before = processor(400_000_000, 300_000_000, 50_000_000);
        let moved_now = processor(
            moved_before.idle_time + 5_000_000,
            moved_before.kernel_time + 5_000_000,
            moved_before.user_time + 5_000_000,
        );

        let splits = super::split_processor_times(&[still, moved_before], &[still, moved_now])
            .expect("split");
        assert_eq!(splits[0], None);
        let (user, system, idle) = splits[1].expect("core 1 moved");
        assert!((user - 50.0).abs() < 0.01, "user {user}");
        assert!(system.abs() < 0.01, "system {system}");
        assert!((idle - 50.0).abs() < 0.01, "idle {idle}");
    }

    #[test]
    fn processor_counter_going_backwards_is_no_reading() {
        let before = processor(500_000_000, 600_000_000, 100_000_000);
        let now = processor(
            before.idle_time - 1,
            before.kernel_time + 8_000_000,
            before.user_time,
        );
        let splits = super::split_processor_times(&[before], &[now]).expect("split");
        assert_eq!(splits[0], None);
    }

    #[test]
    fn processor_counts_that_differ_give_no_per_core_split() {
        // A changed processor count cannot be paired entry by entry.
        let one = processor(500_000_000, 600_000_000, 100_000_000);
        assert_eq!(super::split_processor_times(&[one], &[one, one]), None);
    }

    #[test]
    fn percentages_of_no_elapsed_ticks_is_no_reading() {
        assert_eq!(super::percentages(0, 0, 0), None);
    }

    /// The process table's reserved-field offsets are checked, not trusted:
    /// for this process, which can be opened, the table must agree with
    /// `GetProcessTimes` and `GetProcessMemoryInfo`.
    #[test]
    fn the_process_table_agrees_with_the_handle_based_calls() {
        use windows::Win32::Foundation::FILETIME;
        use windows::Win32::System::ProcessStatus::{
            GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS_EX,
        };
        use windows::Win32::System::Threading::{GetCurrentProcess, GetProcessTimes};

        // Burn a little CPU so the times are not trivially zero.
        let mut x = 0u64;
        for i in 0..20_000_000u64 {
            x = x.wrapping_add(i * i);
        }
        std::hint::black_box(x);

        let pid = std::process::id();
        let (mut c, mut e, mut k, mut u) = (
            FILETIME::default(),
            FILETIME::default(),
            FILETIME::default(),
            FILETIME::default(),
        );
        let mut mem = PROCESS_MEMORY_COUNTERS_EX::default();
        let table = super::system_process_table().expect("process table");
        unsafe {
            GetProcessTimes(GetCurrentProcess(), &mut c, &mut e, &mut k, &mut u).unwrap();
            GetProcessMemoryInfo(
                GetCurrentProcess(),
                std::ptr::addr_of_mut!(mem) as *mut _,
                std::mem::size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,
            )
            .unwrap();
        }
        let ft = |f: FILETIME| (f.dwHighDateTime as u64) << 32 | f.dwLowDateTime as u64;
        let row = table.get(&pid).expect("this process is in the table");

        assert_eq!(row.create_time_100ns, ft(c), "create time offset");
        // Times are read a moment apart, so the table may trail by a little.
        let near = |a: u64, b: u64| a.abs_diff(b) <= 2_000_000; // 200 ms
        assert!(
            near(row.user_time_100ns, ft(u)),
            "user {} vs {}",
            row.user_time_100ns,
            ft(u)
        );
        assert!(
            near(row.kernel_time_100ns, ft(k)),
            "kernel {} vs {}",
            row.kernel_time_100ns,
            ft(k)
        );
        assert!(row.user_time_100ns > 0, "user time read as zero");
        // Working set moves with every allocation; within 16 MiB is agreement.
        let ws = mem.WorkingSetSize as u64;
        assert!(
            row.working_set_bytes.abs_diff(ws) < 16 << 20,
            "working set {} vs {}",
            row.working_set_bytes,
            ws
        );
        assert!(row.working_set_bytes > 0);
        assert!(
            table.len() > 50,
            "only {} processes in the table",
            table.len()
        );

        // And the I/O counters, whose offsets are also inside a reserved block.
        // Read a file first: an offset check against two zeros passes whatever
        // the offset is, and a test process is not guaranteed to have read
        // anything yet -- this assertion failed once on exactly that.
        let manifest = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml"))
            .expect("read Cargo.toml");
        assert!(!manifest.is_empty());
        let mut io = windows::Win32::System::Threading::IO_COUNTERS::default();
        unsafe {
            windows::Win32::System::Threading::GetProcessIoCounters(GetCurrentProcess(), &mut io)
                .unwrap();
        }
        let row = super::system_process_table().unwrap()[&pid];
        assert!(
            row.io_read_bytes.abs_diff(io.ReadTransferCount) < 1 << 20,
            "read {} vs {}",
            row.io_read_bytes,
            io.ReadTransferCount
        );
        assert!(row.io_read_bytes > 0, "read transfer count read as zero");
    }

    /// `free` is free memory, not available memory.
    ///
    /// It was `ullAvailPhys`, the same figure `used` is derived from, so
    /// `free == total - used` held to the kilobyte on every Windows machine.
    /// The standby list is never empty on a running system, so a true free
    /// figure is below available, and reading both through different APIs makes
    /// an exact match between them a sign of the old assignment.
    #[test]
    fn free_memory_is_not_the_available_figure() {
        let stats = super::read_memory_stats().expect("memory stats");
        let available = stats.ram.total - stats.ram.used;
        let free = stats
            .ram
            .free
            .expect("the free-page counter is readable on Windows");
        assert_ne!(free, available, "free is the available figure again");
        assert!(
            free <= available + available / 10,
            "free ({free} KB) exceeds available ({available} KB)"
        );
    }

    /// The nominal clock must not be reported as the current one.
    ///
    /// `CallNtPowerInformation` returns `CurrentMhz == MaxMhz` on Windows 10 and
    /// later whatever the cores are doing, so publishing it put a specification
    /// behind `cpu.core.{n}.frequency`, which is declared `Measured` and
    /// described as the current clock. Every conformance test passed, because
    /// none of them ask whether a value claiming to be current ever changes.
    #[test]
    fn a_nominal_clock_is_not_reported_as_the_current_one() {
        let entry = |current_mhz, max_mhz| ProcessorPowerInformation {
            number: 0,
            max_mhz,
            current_mhz,
            mhz_limit: 0,
            max_idle_state: 0,
            current_idle_state: 0,
        };

        // The case this fixes: 4400/4400 on all 24 cores of a 9900X that was
        // actually boosting past 5GHz.
        let power = vec![entry(4400, 4400)];
        let f =
            get_cpu_frequency(Some(&power), 0, None).expect("max is known, so a row is returned");
        assert_eq!(
            f.current, None,
            "the nominal clock reported as current is not a reading"
        );
        assert_eq!(f.max, Some(4400), "the maximum is still known");

        // A genuine current reading below the maximum survives untouched.
        let power = vec![entry(3200, 4400)];
        let f = get_cpu_frequency(Some(&power), 0, None).expect("a real reading");
        assert_eq!(f.current, Some(3200));

        // Nothing known at all stays absent rather than becoming a zero.
        let power = vec![entry(0, 0)];
        assert!(get_cpu_frequency(Some(&power), 0, None).is_none());
    }
    use super::*;

    /// Per-core figures must be genuinely per-core, not one number replicated.
    ///
    /// This is the regression that motivated the NtQuerySystemInformation path:
    /// `GetSystemTimes` is system-wide, so every core previously reported the same
    /// value and a 24-core box drew 24 identical bars that looked measured.
    /// The aggregate figure must not contradict the per-core breakdown.
    ///
    /// The whole-CPU split used to return a hardcoded (0, 0, 100) on its first call, so
    /// any one-shot invocation reported the machine as completely idle while the
    /// per-core rows directly beneath it showed real load. The aggregate and the
    /// per-core figures now share one two-reading sample on their first call, so both
    /// describe the same interval and agree.
    #[test]
    fn aggregate_cpu_agrees_with_per_core() {
        let stats = read_cpu_stats().expect("cpu stats");
        assert!(!stats.cores.is_empty(), "no cores reported");

        let aggregate_busy = 100.0 - stats.total.idle;

        let per_core: Vec<f32> = stats
            .cores
            .iter()
            .filter_map(|c| c.idle.map(|idle| 100.0 - idle))
            .collect();

        // Cores may report None if the per-processor query failed; nothing to compare
        // against in that case.
        if per_core.is_empty() {
            eprintln!("skipping: per-core data unavailable");
            return;
        }

        let mean_busy = per_core.iter().sum::<f32>() / per_core.len() as f32;
        eprintln!("aggregate busy {aggregate_busy:.1}%, per-core mean {mean_busy:.1}%");

        // The two use different sampling bases, so they will not match exactly. What
        // must not happen is one claiming idle while the other reports load.
        assert!(
            !(aggregate_busy < 1.0 && mean_busy > 10.0),
            "aggregate reports {aggregate_busy:.1}% busy while cores average \
             {mean_busy:.1}% — the aggregate is a placeholder, not a measurement"
        );
    }

    #[test]
    fn per_core_utilization_is_not_the_system_average() {
        // `available_parallelism` rather than `num_cpus::get`: num_cpus is an
        // optional dependency enabled by `cli`, so naming it here made the library's
        // own test target fail to build on any feature set without the CLI.
        let cpu_count = std::thread::available_parallelism()
            .map(|n| n.get())
            .unwrap_or(1);

        // Assert on the *cumulative* counters rather than instantaneous percentages.
        //
        // An earlier version of this test loaded one thread and asserted the busiest
        // and least-busy cores differed. That is flaky by construction: run under a
        // saturated machine (the full test suite, or CI) every core legitimately
        // reads 100% busy, and the test fails on correct data.
        //
        // Idle time accumulated since boot, by contrast, differs per core on any real
        // system regardless of present load — and is exactly what would be identical
        // if the values were the system aggregate replicated, which was the bug.
        let raw = query_per_core_times(cpu_count)
            .expect("NtQuerySystemInformation returned no per-processor data");
        assert!(!raw.is_empty(), "no per-processor records returned");

        if raw.len() > 1 {
            let distinct = raw
                .iter()
                .map(|r| r.idle_time)
                .collect::<std::collections::HashSet<_>>()
                .len();
            eprintln!(
                "{} distinct cumulative idle times across {} cores",
                distinct,
                raw.len()
            );
            assert!(
                distinct > 1,
                "all {} cores report identical cumulative idle time — the values are \
                 a single system-wide figure replicated, not per-core data",
                raw.len()
            );
        }

        // A percentage is a share of the interval between two samples. This is the
        // first call of the test process's sampling, so it primes with its own second
        // reading. It must still yield per-core figures, not `None` for every core, and
        // each figure it yields must be well-formed.
        let (_, cores) = sample_cpu_split(cpu_count).expect("cpu split");
        let cores = cores.expect("per-core utilization");
        assert!(
            cores.iter().any(Option::is_some),
            "first call reported no per-core figure for any core"
        );
        for (i, entry) in cores.iter().enumerate() {
            // An entry is `None` where no time elapsed on that core; nothing to check.
            let Some((user, system, idle)) = *entry else {
                continue;
            };
            let total = user + system + idle;
            assert!(
                (total - 100.0).abs() < 1.0,
                "core {i} percentages sum to {total}, expected ~100"
            );
            assert!(
                (0.0..=100.0).contains(&idle),
                "core {i} idle {idle} out of range"
            );
        }
    }

    #[test]
    fn test_logical_drives() {
        let drives = logical_drives().expect("enumeration should succeed");
        assert!(
            !drives.is_empty(),
            "a Windows host always has at least one fixed drive"
        );
        for drive in &drives {
            assert!(drive.total > 0, "{} reported zero capacity", drive.name);
            assert!(
                drive.used <= drive.total,
                "{} used {} exceeds total {}",
                drive.name,
                drive.used,
                drive.total
            );
            assert!(
                drive.name.ends_with(":\\"),
                "{} is not a drive root",
                drive.name
            );
            assert!(!drive.filesystem.is_empty());
        }
    }

    #[test]
    fn test_read_cpu_stats() {
        let stats = read_cpu_stats();
        assert!(stats.is_ok());
        let stats = stats.unwrap();
        assert!(!stats.cores.is_empty());
    }

    #[test]
    fn test_read_memory_stats() {
        let stats = read_memory_stats();
        assert!(stats.is_ok());
        let stats = stats.unwrap();
        assert!(stats.ram.total > 0);
    }

    #[test]
    fn test_get_system_uptime() {
        let uptime = get_system_uptime();
        assert!(uptime.as_secs() > 0);
    }
}