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
//! CPU Frequency Scaling and Governor Control
//!
//! This module provides comprehensive CPU frequency management including:
//! - Frequency governor control (performance, powersave, ondemand, schedutil, etc.)
//! - Min/max frequency limits
//! - CPU online/offline control
//! - Per-core frequency monitoring
//! - C-state (CPU idle) monitoring
//! - Turbo boost control
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::cpufreq::{CpuFreqMonitor, Governor};
//!
//! let mut monitor = CpuFreqMonitor::new().unwrap();
//!
//! // Show current governor
//! println!("Governor: {:?}", monitor.current_governor());
//!
//! // Set performance mode
//! monitor.set_governor(Governor::Performance).unwrap();
//!
//! // Get CPU frequencies
//! for cpu in monitor.cpus() {
//! match cpu.current_freq_mhz {
//! Some(mhz) => println!("CPU{}: {} MHz", cpu.id, mhz),
//! None => println!("CPU{}: frequency not readable here", cpu.id),
//! }
//! }
//! ```
use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Instant;
/// CPU frequency governor types
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Governor {
/// Maximum performance, highest frequency
Performance,
/// Minimum power, lowest frequency
Powersave,
/// Dynamic scaling based on load (legacy)
Ondemand,
/// Conservative scaling with gradual changes
Conservative,
/// Userspace control (manual)
Userspace,
/// Scheduler-driven frequency scaling (modern)
Schedutil,
/// Intel P-state driver
IntelPstate,
/// AMD P-state driver
AmdPstate,
/// Interactive governor (Android/embedded)
Interactive,
/// Unknown governor
Unknown(String),
}
impl std::fmt::Display for Governor {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Governor::Performance => write!(f, "performance"),
Governor::Powersave => write!(f, "powersave"),
Governor::Ondemand => write!(f, "ondemand"),
Governor::Conservative => write!(f, "conservative"),
Governor::Userspace => write!(f, "userspace"),
Governor::Schedutil => write!(f, "schedutil"),
Governor::IntelPstate => write!(f, "intel_pstate"),
Governor::AmdPstate => write!(f, "amd_pstate"),
Governor::Interactive => write!(f, "interactive"),
Governor::Unknown(s) => write!(f, "{}", s),
}
}
}
impl std::str::FromStr for Governor {
type Err = IronError;
fn from_str(s: &str) -> Result<Self> {
match s.to_lowercase().as_str() {
"performance" => Ok(Governor::Performance),
"powersave" => Ok(Governor::Powersave),
"ondemand" => Ok(Governor::Ondemand),
"conservative" => Ok(Governor::Conservative),
"userspace" => Ok(Governor::Userspace),
"schedutil" => Ok(Governor::Schedutil),
"intel_pstate" => Ok(Governor::IntelPstate),
"amd_pstate" | "amd-pstate" | "amd-pstate-epp" => Ok(Governor::AmdPstate),
"interactive" => Ok(Governor::Interactive),
other => Ok(Governor::Unknown(other.to_string())),
}
}
}
/// Energy Performance Preference (EPP) values for Intel/AMD P-state
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum EnergyPreference {
/// Maximum performance (0)
Performance,
/// Balance performance (128)
BalancePerformance,
/// Balance power (192)
BalancePower,
/// Maximum power saving (255)
Power,
}
impl std::fmt::Display for EnergyPreference {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EnergyPreference::Performance => write!(f, "performance"),
EnergyPreference::BalancePerformance => write!(f, "balance_performance"),
EnergyPreference::BalancePower => write!(f, "balance_power"),
EnergyPreference::Power => write!(f, "power"),
}
}
}
impl std::str::FromStr for EnergyPreference {
type Err = IronError;
fn from_str(s: &str) -> Result<Self> {
match s.to_lowercase().replace('-', "_").as_str() {
"performance" | "default" => Ok(EnergyPreference::Performance),
"balance_performance" => Ok(EnergyPreference::BalancePerformance),
"balance_power" | "normal" => Ok(EnergyPreference::BalancePower),
"power" | "powersave" => Ok(EnergyPreference::Power),
_ => Err(IronError::InvalidValue(format!(
"Unknown energy preference: {}",
s
))),
}
}
}
/// CPU idle state (C-state)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuIdleState {
/// State name (e.g., "POLL", "C1", "C6")
pub name: String,
/// State description
pub desc: Option<String>,
/// Latency to exit state (microseconds), `None` when sysfs did not give it
pub latency_us: Option<u32>,
/// Residency requirement (microseconds)
pub residency_us: Option<u32>,
/// Is state enabled, `None` when sysfs `disable` was not readable
pub enabled: Option<bool>,
/// Times this state was entered, `None` when sysfs did not give it
pub usage: Option<u64>,
/// Time spent in this state (microseconds), `None` when sysfs did not give it
pub time_us: Option<u64>,
/// Is state disabled by admin, `None` when sysfs `disable` was not readable
pub disable: Option<bool>,
}
/// Per-CPU frequency information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuFreqInfo {
/// CPU ID (0, 1, 2, ...)
pub id: u32,
/// Is CPU online, or `None` where its state was not read.
///
/// Linux reads `cpuN/online`. A CPU with no `online` file (cpu0, and CPUs
/// the kernel cannot hot-unplug) is `Some(true)`: the file is absent
/// because there is no way to take it offline. A file that exists but
/// cannot be read is `None`, not online. Windows and macOS do not report a
/// per-CPU online state here, so it is `None` there.
pub online: Option<bool>,
/// Current frequency (kHz), or `None` where it was not read.
///
/// **The last bare frequency field, and the one every helper below
/// divides by.** `CpuFreqInfo::new` set it to `0`, so a core whose
/// `scaling_cur_freq` could not be read reported `freq_percent() ==
/// Some(0.0)` -- an idle core -- and `is_min_freq() == Some(true)`, since
/// `0 <= min` for every minimum there is. Neither was observed.
///
/// macOS is the reason this could not simply be left alone: that reader
/// has no per-core current frequency at all and was assigning the
/// *maximum* to it under a comment reading `// Approximation`. An
/// approximation that cannot be told apart from a measurement is not an
/// approximation, it is a fabrication with a comment.
pub current_freq_khz: Option<u64>,
/// Current frequency (MHz) for convenience, or `None` where unread.
pub current_freq_mhz: Option<u32>,
/// Minimum allowed frequency (kHz), or `None` where it was not read.
///
/// **Optional because `0` was answering a question nobody asked.** With a
/// fabricated maximum of zero, [`Self::is_max_freq`] compared
/// `current >= 0` and reported every core as running flat out. The
/// `base_freq_khz` beside this was already `Option` for the same reason.
pub min_freq_khz: Option<u64>,
/// Maximum allowed frequency (kHz), or `None` where it was not read.
pub max_freq_khz: Option<u64>,
/// Hardware minimum frequency (kHz)
pub cpuinfo_min_freq_khz: Option<u64>,
/// Hardware maximum frequency (kHz)
pub cpuinfo_max_freq_khz: Option<u64>,
/// Base frequency (kHz) - non-turbo max
pub base_freq_khz: Option<u64>,
/// Current governor
pub governor: Governor,
/// Available governors
pub available_governors: Vec<Governor>,
/// Available frequencies (kHz)
pub available_frequencies: Vec<u64>,
/// CPU model name
pub model: Option<String>,
/// CPU idle states
pub idle_states: Vec<CpuIdleState>,
/// Energy Performance Preference (Intel/AMD P-state)
pub energy_preference: Option<EnergyPreference>,
/// Available energy preferences
pub available_energy_preferences: Vec<EnergyPreference>,
/// Scaling driver in use
pub scaling_driver: Option<String>,
/// Sysfs path
#[serde(skip)]
pub sysfs_path: Option<PathBuf>,
}
impl CpuFreqInfo {
/// Create new CpuFreqInfo for given CPU ID
pub fn new(id: u32) -> Self {
Self {
id,
online: None,
current_freq_khz: None,
current_freq_mhz: None,
min_freq_khz: None,
max_freq_khz: None,
cpuinfo_min_freq_khz: None,
cpuinfo_max_freq_khz: None,
base_freq_khz: None,
governor: Governor::Unknown("unknown".to_string()),
available_governors: Vec::new(),
available_frequencies: Vec::new(),
model: None,
idle_states: Vec::new(),
energy_preference: None,
available_energy_preferences: Vec::new(),
scaling_driver: None,
sysfs_path: None,
}
}
/// Frequency as a percentage of maximum, or `None` without a maximum.
///
/// Returned `0.0` when the maximum was unknown — a core at 0% of an unread
/// ceiling, which reads as an idle processor.
pub fn freq_percent(&self) -> Option<f32> {
let max = self.max_freq_khz?;
let current = self.current_freq_khz?;
if max == 0 {
return None;
}
Some((current as f32 / max as f32) * 100.0)
}
/// Whether the CPU is at its maximum frequency, or `None` without one.
///
/// **This returned `true` for every core when the maximum was unread**,
/// because a fabricated `0` made `current >= 0` trivially true.
pub fn is_max_freq(&self) -> Option<bool> {
Some(self.current_freq_khz? >= self.max_freq_khz?)
}
/// Whether the CPU is at its minimum frequency, or `None` without one.
/// This one was the worse of the pair: with an unread current frequency
/// of `0`, `0 <= min` held for every minimum, so every core read as parked.
pub fn is_min_freq(&self) -> Option<bool> {
Some(self.current_freq_khz? <= self.min_freq_khz?)
}
/// Whether the core is above its base frequency, or `None` when the base
/// frequency is not known.
///
/// This returned `bool`, so "cannot tell" and "not boosting" were the same
/// answer — and the middle branch made a third case look like the first two:
///
/// ```text
/// } else if let Some(max) = self.cpuinfo_max_freq_khz {
/// // Assume turbo if current > 95% of max
/// ```
///
/// 95% of the maximum is not a test for turbo. A part whose non-turbo
/// ceiling *is* its `cpuinfo_max_freq` reads as boosting whenever it is
/// busy, and one boosting to 96% of max reads as boosting for a reason
/// that has nothing to do with the base clock. Turbo means "above base",
/// and without a base there is no answer to give.
///
/// `scaling_cur_freq` above `base_frequency` is the real test, and
/// `base_freq_khz` comes from `cpufreq/base_frequency`, which
/// intel_pstate exposes and other governors do not.
pub fn is_turbo(&self) -> Option<bool> {
Some(self.current_freq_khz? > self.base_freq_khz?)
}
}
/// System-wide CPU frequency policy
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuFreqPolicy {
/// Policy ID
pub id: u32,
/// CPUs covered by this policy
pub affected_cpus: Vec<u32>,
/// Related CPUs
pub related_cpus: Vec<u32>,
/// Current governor
pub governor: Governor,
/// Minimum frequency (kHz), or `None` where it was not read.
pub min_freq_khz: Option<u64>,
/// Maximum frequency (kHz), or `None` where it was not read.
pub max_freq_khz: Option<u64>,
/// Scaling driver
pub scaling_driver: Option<String>,
}
/// Turbo boost status
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub struct TurboStatus {
/// Whether a turbo or boost control exists. Linux: `Some(true)` where one of
/// the kernel's boost files exists, `Some(false)` where none does. `None` on
/// Windows and macOS: this reader never inferred availability there. It used
/// to be a `bool` set to `true` on Windows whenever the WMI maximum clock
/// exceeded the registry's boot-time clock, which is two nominal figures
/// compared, not a boost control.
pub available: Option<bool>,
/// Whether turbo is enabled. Linux: the kernel's current state. Windows:
/// whether the active power scheme permits boost (the processor performance
/// boost mode is not 0), which is not the same as boost running now. `None`
/// when the state was not read. It used to be a `bool` set to `true`
/// unconditionally on Windows, which reported boost as on whatever the
/// power scheme said.
pub enabled: Option<bool>,
/// Can turbo be controlled
pub controllable: bool,
/// Turbo frequency boost (MHz above base). Always `None` on every platform.
/// Windows used to report the WMI `MaxClockSpeed` minus the registry's
/// boot-time `~MHz`. Both are nominal clocks, so this was 8 MHz on a Ryzen 9
/// 9900X whose boost ceiling is about 5.6 GHz. No reader here reads a turbo
/// ceiling, so none is reported.
pub boost_mhz: Option<u32>,
}
/// CPU frequency monitor and controller
pub struct CpuFreqMonitor {
/// Per-CPU information
cpus: Vec<CpuFreqInfo>,
/// System policies
policies: Vec<CpuFreqPolicy>,
/// Turbo status
turbo: TurboStatus,
/// Last update time
last_update: Instant,
/// P-state driver type
#[allow(dead_code)]
pstate_driver: Option<String>,
}
impl CpuFreqMonitor {
/// Create a new CPU frequency monitor
pub fn new() -> Result<Self> {
let mut monitor = Self {
cpus: Vec::new(),
policies: Vec::new(),
turbo: TurboStatus {
available: None,
enabled: None,
controllable: false,
boost_mhz: None,
},
last_update: Instant::now(),
pstate_driver: None,
};
monitor.discover()?;
Ok(monitor)
}
/// Get all CPUs
pub fn cpus(&self) -> &[CpuFreqInfo] {
&self.cpus
}
/// Get CPU by ID
pub fn get_cpu(&self, id: u32) -> Option<&CpuFreqInfo> {
self.cpus.iter().find(|c| c.id == id)
}
/// Get CPUs known to be online. A CPU whose state was not read is in
/// neither this list nor [`Self::offline_cpus`].
pub fn online_cpus(&self) -> Vec<&CpuFreqInfo> {
self.cpus
.iter()
.filter(|c| c.online == Some(true))
.collect()
}
/// Get CPUs known to be offline. A CPU whose state was not read is in
/// neither this list nor [`Self::online_cpus`].
pub fn offline_cpus(&self) -> Vec<&CpuFreqInfo> {
self.cpus
.iter()
.filter(|c| c.online == Some(false))
.collect()
}
/// Get policies
pub fn policies(&self) -> &[CpuFreqPolicy] {
&self.policies
}
/// Get turbo status
pub fn turbo_status(&self) -> &TurboStatus {
&self.turbo
}
/// Get current governor (from the first CPU not known to be offline, or
/// policy)
pub fn current_governor(&self) -> Option<Governor> {
self.cpus
.iter()
.find(|c| c.online != Some(false))
.map(|c| c.governor.clone())
// The `unknown` placeholder is what an unread governor holds; it is
// no governor, so it is not returned as one.
.filter(|g| !matches!(g, Governor::Unknown(name) if name == "unknown"))
}
/// Get available governors (from the first CPU not known to be offline)
pub fn available_governors(&self) -> Vec<Governor> {
self.cpus
.iter()
.find(|c| c.online != Some(false))
.map(|c| c.available_governors.clone())
.unwrap_or_default()
}
/// Refresh CPU frequency data
pub fn refresh(&mut self) -> Result<()> {
self.discover()?;
self.last_update = Instant::now();
Ok(())
}
/// Set governor for all CPUs
pub fn set_governor(&mut self, governor: Governor) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_governor(governor)
}
#[cfg(target_os = "windows")]
{
self.windows_set_governor(governor)
}
#[cfg(not(any(target_os = "linux", target_os = "windows")))]
{
let _ = governor;
Err(IronError::UnsupportedPlatform(
"CPU governor control not supported on this platform".to_string(),
))
}
}
/// Set governor for specific CPU
pub fn set_cpu_governor(&mut self, cpu_id: u32, governor: Governor) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_cpu_governor(cpu_id, governor)
}
#[cfg(not(target_os = "linux"))]
{
let _ = (cpu_id, governor);
Err(IronError::UnsupportedPlatform(
"Per-CPU governor control not supported on this platform".to_string(),
))
}
}
/// Set minimum frequency (kHz) for all CPUs
pub fn set_min_freq(&mut self, freq_khz: u64) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_min_freq(freq_khz)
}
#[cfg(not(target_os = "linux"))]
{
let _ = freq_khz;
Err(IronError::UnsupportedPlatform(
"Frequency control not supported on this platform".to_string(),
))
}
}
/// Set maximum frequency (kHz) for all CPUs
pub fn set_max_freq(&mut self, freq_khz: u64) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_max_freq(freq_khz)
}
#[cfg(not(target_os = "linux"))]
{
let _ = freq_khz;
Err(IronError::UnsupportedPlatform(
"Frequency control not supported on this platform".to_string(),
))
}
}
/// Set CPU online/offline
pub fn set_cpu_online(&mut self, cpu_id: u32, online: bool) -> Result<()> {
if cpu_id == 0 {
return Err(IronError::InvalidValue(
"Cannot take CPU0 offline".to_string(),
));
}
#[cfg(target_os = "linux")]
{
self.linux_set_cpu_online(cpu_id, online)
}
#[cfg(not(target_os = "linux"))]
{
let _ = (cpu_id, online);
Err(IronError::UnsupportedPlatform(
"CPU hotplug not supported on this platform".to_string(),
))
}
}
/// Enable/disable turbo boost
pub fn set_turbo(&mut self, enabled: bool) -> Result<()> {
if !self.turbo.controllable {
return Err(IronError::UnsupportedPlatform(
"Turbo boost control not available".to_string(),
));
}
#[cfg(target_os = "linux")]
{
self.linux_set_turbo(enabled)
}
#[cfg(not(target_os = "linux"))]
{
let _ = enabled;
Err(IronError::UnsupportedPlatform(
"Turbo boost control not supported on this platform".to_string(),
))
}
}
/// Set energy preference (Intel/AMD P-state)
pub fn set_energy_preference(&mut self, pref: EnergyPreference) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_energy_preference(pref)
}
#[cfg(not(target_os = "linux"))]
{
let _ = pref;
Err(IronError::UnsupportedPlatform(
"Energy preference control not supported on this platform".to_string(),
))
}
}
/// Enable/disable CPU idle state
pub fn set_idle_state(&mut self, cpu_id: u32, state_idx: usize, enabled: bool) -> Result<()> {
#[cfg(target_os = "linux")]
{
self.linux_set_idle_state(cpu_id, state_idx, enabled)
}
#[cfg(not(target_os = "linux"))]
{
let _ = (cpu_id, state_idx, enabled);
Err(IronError::UnsupportedPlatform(
"CPU idle state control not supported on this platform".to_string(),
))
}
}
/// Discover CPU frequency capabilities
fn discover(&mut self) -> Result<()> {
self.cpus.clear();
self.policies.clear();
#[cfg(target_os = "linux")]
{
self.linux_discover()?;
}
#[cfg(target_os = "windows")]
{
self.windows_discover()?;
}
#[cfg(target_os = "macos")]
{
self.macos_discover()?;
}
Ok(())
}
// ==================== Linux Implementation ====================
#[cfg(target_os = "linux")]
fn linux_discover(&mut self) -> Result<()> {
use std::fs;
let cpu_path = std::path::Path::new("/sys/devices/system/cpu");
if !cpu_path.exists() {
return Err(IronError::UnsupportedPlatform(
"No CPU sysfs interface found".to_string(),
));
}
// Detect P-state driver
let driver_path = cpu_path.join("cpu0/cpufreq/scaling_driver");
self.pstate_driver = fs::read_to_string(&driver_path)
.map(|s| s.trim().to_string())
.ok();
// Discover turbo boost
self.linux_discover_turbo()?;
// Read CPU model from /proc/cpuinfo
let cpu_model = self.read_cpu_model();
// Enumerate CPUs
for entry in fs::read_dir(cpu_path)
.map_err(|e| IronError::System(format!("Failed to read CPU sysfs: {}", e)))?
{
let entry =
entry.map_err(|e| IronError::System(format!("Failed to read entry: {}", e)))?;
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("cpu") {
continue;
}
// Parse CPU ID
let id_str = name.strip_prefix("cpu").unwrap_or("");
let id: u32 = match id_str.parse() {
Ok(id) => id,
Err(_) => continue,
};
let cpu_dir = entry.path();
let mut cpu = CpuFreqInfo::new(id);
cpu.sysfs_path = Some(cpu_dir.clone());
cpu.model = cpu_model.clone();
// Check online status. cpu0 and CPUs the kernel cannot hot-unplug
// have no `online` file, and are always online: the file's absence
// is a reading, not a gap. A file that exists but cannot be read is
// unknown (None), not online.
let online_file = cpu_dir.join("online");
if online_file.exists() {
cpu.online = fs::read_to_string(&online_file)
.ok()
.map(|s| s.trim() == "1");
} else {
cpu.online = Some(true);
}
if cpu.online == Some(false) {
self.cpus.push(cpu);
continue;
}
let cpufreq_dir = cpu_dir.join("cpufreq");
if !cpufreq_dir.exists() {
self.cpus.push(cpu);
continue;
}
// Read scaling driver
cpu.scaling_driver = fs::read_to_string(cpufreq_dir.join("scaling_driver"))
.map(|s| s.trim().to_string())
.ok();
// Read current frequency
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("scaling_cur_freq")) {
if let Ok(freq) = freq_str.trim().parse::<u64>() {
cpu.current_freq_khz = Some(freq);
cpu.current_freq_mhz = Some((freq / 1000) as u32);
}
}
// Read min/max scaling frequencies
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("scaling_min_freq")) {
cpu.min_freq_khz = freq_str.trim().parse().ok();
}
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("scaling_max_freq")) {
cpu.max_freq_khz = freq_str.trim().parse().ok();
}
// Read hardware min/max frequencies
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("cpuinfo_min_freq")) {
cpu.cpuinfo_min_freq_khz = freq_str.trim().parse().ok();
}
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("cpuinfo_max_freq")) {
cpu.cpuinfo_max_freq_khz = freq_str.trim().parse().ok();
}
// Read base frequency (non-turbo)
if let Ok(freq_str) = fs::read_to_string(cpufreq_dir.join("base_frequency")) {
cpu.base_freq_khz = freq_str.trim().parse().ok();
}
// Read current governor
if let Ok(gov_str) = fs::read_to_string(cpufreq_dir.join("scaling_governor")) {
cpu.governor = gov_str
.trim()
.parse()
.unwrap_or(Governor::Unknown("unknown".to_string()));
}
// Read available governors
if let Ok(govs_str) =
fs::read_to_string(cpufreq_dir.join("scaling_available_governors"))
{
cpu.available_governors = govs_str
.split_whitespace()
.filter_map(|s| s.parse().ok())
.collect();
}
// Read available frequencies
if let Ok(freqs_str) =
fs::read_to_string(cpufreq_dir.join("scaling_available_frequencies"))
{
cpu.available_frequencies = freqs_str
.split_whitespace()
.filter_map(|s| s.parse().ok())
.collect();
}
// Read energy preference (Intel/AMD P-state)
if let Ok(epp_str) =
fs::read_to_string(cpufreq_dir.join("energy_performance_preference"))
{
cpu.energy_preference = epp_str.trim().parse().ok();
}
if let Ok(epp_avail) =
fs::read_to_string(cpufreq_dir.join("energy_performance_available_preferences"))
{
cpu.available_energy_preferences = epp_avail
.split_whitespace()
.filter_map(|s| s.parse().ok())
.collect();
}
// Read idle states
let cpuidle_dir = cpu_dir.join("cpuidle");
if cpuidle_dir.exists() {
self.linux_read_idle_states(&cpuidle_dir, &mut cpu)?;
}
self.cpus.push(cpu);
}
// Sort CPUs by ID
self.cpus.sort_by_key(|c| c.id);
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_read_idle_states(
&self,
cpuidle_dir: &std::path::Path,
cpu: &mut CpuFreqInfo,
) -> Result<()> {
use std::fs;
for entry in fs::read_dir(cpuidle_dir)
.map_err(|e| IronError::System(format!("Failed to read cpuidle: {}", e)))?
{
let entry =
entry.map_err(|e| IronError::System(format!("Failed to read entry: {}", e)))?;
let name = entry.file_name().to_string_lossy().to_string();
if !name.starts_with("state") {
continue;
}
let state_dir = entry.path();
let mut state = CpuIdleState {
name: String::new(),
desc: None,
latency_us: None,
residency_us: None,
enabled: None,
usage: None,
time_us: None,
disable: None,
};
// Read state name
state.name = fs::read_to_string(state_dir.join("name"))
.map(|s| s.trim().to_string())
.unwrap_or_else(|_| name.clone());
// Read description
state.desc = fs::read_to_string(state_dir.join("desc"))
.map(|s| s.trim().to_string())
.ok();
// Read latency
state.latency_us = fs::read_to_string(state_dir.join("latency"))
.ok()
.and_then(|s| s.trim().parse().ok());
// Read residency
state.residency_us = fs::read_to_string(state_dir.join("residency"))
.ok()
.and_then(|s| s.trim().parse().ok());
// Read disable status. An unreadable file is `None`, not "not
// disabled": the old `unwrap_or(false)` made an unreadable state
// read as enabled, and `enabled` was derived from that guess.
state.disable = fs::read_to_string(state_dir.join("disable"))
.ok()
.map(|s| s.trim() == "1");
state.enabled = state.disable.map(|d| !d);
// Read usage count
state.usage = fs::read_to_string(state_dir.join("usage"))
.ok()
.and_then(|s| s.trim().parse().ok());
// Read time in state
state.time_us = fs::read_to_string(state_dir.join("time"))
.ok()
.and_then(|s| s.trim().parse().ok());
cpu.idle_states.push(state);
}
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_discover_turbo(&mut self) -> Result<()> {
use std::fs;
// Intel P-state no_turbo
let intel_turbo = std::path::Path::new("/sys/devices/system/cpu/intel_pstate/no_turbo");
if intel_turbo.exists() {
self.turbo.available = Some(true);
self.turbo.controllable = true;
if let Ok(val) = fs::read_to_string(intel_turbo) {
self.turbo.enabled = Some(val.trim() == "0"); // no_turbo=0 means turbo enabled
}
return Ok(());
}
// AMD P-state boost
let amd_boost = std::path::Path::new("/sys/devices/system/cpu/amd_pstate/cpufreq/boost");
if amd_boost.exists() {
self.turbo.available = Some(true);
self.turbo.controllable = true;
if let Ok(val) = fs::read_to_string(amd_boost) {
self.turbo.enabled = Some(val.trim() == "1");
}
return Ok(());
}
// Generic cpufreq boost
let generic_boost = std::path::Path::new("/sys/devices/system/cpu/cpufreq/boost");
if generic_boost.exists() {
self.turbo.available = Some(true);
self.turbo.controllable = true;
if let Ok(val) = fs::read_to_string(generic_boost) {
self.turbo.enabled = Some(val.trim() == "1");
}
} else {
// None of the three control files exists: a checked absence on Linux.
self.turbo.available = Some(false);
}
Ok(())
}
#[cfg(target_os = "linux")]
fn read_cpu_model(&self) -> Option<String> {
use std::fs;
if let Ok(cpuinfo) = fs::read_to_string("/proc/cpuinfo") {
for line in cpuinfo.lines() {
if line.starts_with("model name") {
if let Some(model) = line.split(':').nth(1) {
return Some(model.trim().to_string());
}
}
}
}
None
}
#[cfg(target_os = "linux")]
fn linux_set_governor(&mut self, governor: Governor) -> Result<()> {
use std::fs;
let gov_str = governor.to_string();
for cpu in &self.cpus {
if cpu.online == Some(false) {
continue;
}
if let Some(ref path) = cpu.sysfs_path {
let gov_file = path.join("cpufreq/scaling_governor");
if gov_file.exists() {
fs::write(&gov_file, &gov_str).map_err(|e| {
IronError::System(format!(
"Failed to set governor for CPU{} (need root?): {}",
cpu.id, e
))
})?;
}
}
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_cpu_governor(&mut self, cpu_id: u32, governor: Governor) -> Result<()> {
use std::fs;
let cpu = self
.cpus
.iter()
.find(|c| c.id == cpu_id)
.ok_or_else(|| IronError::DeviceNotFound(format!("CPU{} not found", cpu_id)))?;
if cpu.online == Some(false) {
return Err(IronError::InvalidValue(format!("CPU{} is offline", cpu_id)));
}
if let Some(ref path) = cpu.sysfs_path {
let gov_file = path.join("cpufreq/scaling_governor");
fs::write(&gov_file, governor.to_string()).map_err(|e| {
IronError::System(format!("Failed to set governor for CPU{}: {}", cpu_id, e))
})?;
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_min_freq(&mut self, freq_khz: u64) -> Result<()> {
use std::fs;
for cpu in &self.cpus {
if cpu.online == Some(false) {
continue;
}
if let Some(ref path) = cpu.sysfs_path {
let freq_file = path.join("cpufreq/scaling_min_freq");
if freq_file.exists() {
fs::write(&freq_file, freq_khz.to_string()).map_err(|e| {
IronError::System(format!(
"Failed to set min freq for CPU{}: {}",
cpu.id, e
))
})?;
}
}
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_max_freq(&mut self, freq_khz: u64) -> Result<()> {
use std::fs;
for cpu in &self.cpus {
if cpu.online == Some(false) {
continue;
}
if let Some(ref path) = cpu.sysfs_path {
let freq_file = path.join("cpufreq/scaling_max_freq");
if freq_file.exists() {
fs::write(&freq_file, freq_khz.to_string()).map_err(|e| {
IronError::System(format!(
"Failed to set max freq for CPU{}: {}",
cpu.id, e
))
})?;
}
}
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_cpu_online(&mut self, cpu_id: u32, online: bool) -> Result<()> {
use std::fs;
let online_file = format!("/sys/devices/system/cpu/cpu{}/online", cpu_id);
let value = if online { "1" } else { "0" };
fs::write(&online_file, value).map_err(|e| {
IronError::System(format!("Failed to set CPU{} online status: {}", cpu_id, e))
})?;
// The write succeeded, so the CPU is in the state asked for. The
// refresh below re-reads sysfs and replaces this with what the kernel
// reports.
if let Some(cpu) = self.cpus.iter_mut().find(|c| c.id == cpu_id) {
cpu.online = Some(online);
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_turbo(&mut self, enabled: bool) -> Result<()> {
use std::fs;
// Intel P-state
let intel_turbo = std::path::Path::new("/sys/devices/system/cpu/intel_pstate/no_turbo");
if intel_turbo.exists() {
let value = if enabled { "0" } else { "1" }; // no_turbo is inverted
fs::write(intel_turbo, value)
.map_err(|e| IronError::System(format!("Failed to set turbo: {}", e)))?;
self.turbo.enabled = Some(enabled);
return Ok(());
}
// Generic boost
let generic_boost = std::path::Path::new("/sys/devices/system/cpu/cpufreq/boost");
if generic_boost.exists() {
let value = if enabled { "1" } else { "0" };
fs::write(generic_boost, value)
.map_err(|e| IronError::System(format!("Failed to set turbo: {}", e)))?;
self.turbo.enabled = Some(enabled);
return Ok(());
}
Err(IronError::UnsupportedPlatform(
"No turbo control interface found".to_string(),
))
}
#[cfg(target_os = "linux")]
fn linux_set_energy_preference(&mut self, pref: EnergyPreference) -> Result<()> {
use std::fs;
let pref_str = pref.to_string();
for cpu in &self.cpus {
if cpu.online == Some(false) {
continue;
}
if let Some(ref path) = cpu.sysfs_path {
let epp_file = path.join("cpufreq/energy_performance_preference");
if epp_file.exists() {
fs::write(&epp_file, &pref_str).map_err(|e| {
IronError::System(format!("Failed to set EPP for CPU{}: {}", cpu.id, e))
})?;
}
}
}
self.refresh()?;
Ok(())
}
#[cfg(target_os = "linux")]
fn linux_set_idle_state(&mut self, cpu_id: u32, state_idx: usize, enabled: bool) -> Result<()> {
use std::fs;
let disable_file = format!(
"/sys/devices/system/cpu/cpu{}/cpuidle/state{}/disable",
cpu_id, state_idx
);
let value = if enabled { "0" } else { "1" };
fs::write(&disable_file, value).map_err(|e| {
IronError::System(format!(
"Failed to set idle state{} for CPU{}: {}",
state_idx, cpu_id, e
))
})?;
self.refresh()?;
Ok(())
}
// ==================== Windows Implementation ====================
#[cfg(target_os = "windows")]
fn windows_discover(&mut self) -> Result<()> {
use windows::Win32::System::SystemInformation::*;
// Get processor count
let mut sys_info = SYSTEM_INFO::default();
unsafe {
GetSystemInfo(&mut sys_info);
}
let num_cpus = sys_info.dwNumberOfProcessors;
// Try WMI for detailed CPU info
let (name, current_mhz, max_mhz) = windows_query_wmi_cpu();
// Get base frequency from registry
let base_freq_mhz = windows_get_base_frequency();
// Create CPU entries
for id in 0..num_cpus {
let mut cpu = CpuFreqInfo::new(id);
// GetSystemInfo gives a processor count, not the online state of
// each processor, so `online` stays `None` (from `CpuFreqInfo::new`).
// The governor stays unread too. Windows has no cpufreq governor: the
// active power plan used to be mapped onto one (`Balanced` became
// schedutil, and that became the only "available" governor), which
// was a table, not a reading. The plan name is not a governor either.
// Apply WMI info if available
if let Some(current) = current_mhz {
cpu.model = name.clone();
// Win32_Processor is one instance per processor package, and
// the first one is all `windows_query_wmi_cpu` reads. Its
// clocks describe CPU 0 alone. Copying them to every core
// gave each core a reading that was not its own.
if id == 0 {
cpu.current_freq_mhz = Some(current);
// `max_mhz.unwrap_or(current)` reported the current frequency
// as the maximum whenever WMI gave no maximum — which makes
// `freq_percent` read 100% and `is_max_freq` read true, for a
// ceiling nobody reported.
cpu.max_freq_khz = max_mhz.map(|m| (m as u64) * 1000);
cpu.current_freq_khz = Some((current as u64) * 1000);
}
// Windows exposes no minimum core frequency here. This was
// `max_freq_khz / 4`, which is not a property of any CPU — it
// just produced a plausible-looking number, then `0` standing in
// for "not read" because the field could not say so. It can now.
cpu.min_freq_khz = None;
cpu.scaling_driver = Some("windows-wmi".to_string());
} else if id == 0 && base_freq_mhz > 0 {
// Registry `~MHz` under `CentralProcessor\0` is the boot-time
// nominal clock of CPU 0. It is not a current reading, so
// `current_freq_mhz` stays `None` here; the registry value
// belongs in the field that means base.
cpu.base_freq_khz = Some((base_freq_mhz as u64) * 1000);
cpu.max_freq_khz = None;
cpu.min_freq_khz = None;
}
self.cpus.push(cpu);
}
// Boost mode is a setting of the active power scheme, not a clock, so it
// is read on its own. Windows exposes no turbo ceiling or control here,
// so `available`, `controllable` and `boost_mhz` stay unread.
self.turbo.enabled = windows_boost_permitted();
Ok(())
}
#[cfg(target_os = "windows")]
#[allow(dead_code)]
fn windows_read_power_scheme(&mut self) -> Result<()> {
// Power scheme already read in windows_discover
Ok(())
}
#[cfg(target_os = "windows")]
fn windows_set_governor(&mut self, governor: Governor) -> Result<()> {
// On Windows, this would set the power plan
// High Performance = Performance governor equivalent
// Balanced = Schedutil/Ondemand equivalent
// Power Saver = Powersave equivalent
let _ = governor;
Err(IronError::UnsupportedPlatform(
"Use Windows Power Options to change power plan".to_string(),
))
}
// ==================== macOS Implementation ====================
#[cfg(target_os = "macos")]
fn macos_discover(&mut self) -> Result<()> {
use std::process::Command;
// Get CPU count
let output = Command::new("sysctl").args(["-n", "hw.ncpu"]).output();
if let Ok(output) = output {
if let Ok(count_str) = String::from_utf8(output.stdout) {
if let Ok(count) = count_str.trim().parse::<u32>() {
for id in 0..count {
// hw.ncpu counts every CPU, not the online ones, and
// hw.activecpu is not read here, so `online` stays `None`.
let cpu = CpuFreqInfo::new(id);
self.cpus.push(cpu);
}
}
}
}
// Get CPU frequency (limited on modern Macs)
let output = Command::new("sysctl")
.args(["-n", "hw.cpufrequency_max"])
.output();
if let Ok(output) = output {
if let Ok(freq_str) = String::from_utf8(output.stdout) {
if let Ok(freq) = freq_str.trim().parse::<u64>() {
for cpu in &mut self.cpus {
// A real reading: `hw.cpufrequency_max` answered.
cpu.max_freq_khz = Some(freq / 1000);
// The current frequency is **not** set here, and that
// is the fix. This used to assign the maximum to it
// under a `// Approximation` comment, so every core on
// every Mac read as pinned at its ceiling: `is_max_freq`
// true, `freq_percent` 100%, for a number that came from
// `hw.cpufrequency_max` and described nothing happening
// now.
//
// macOS exposes no per-core current frequency through
// sysctl. `hw.cpufrequency` is a fixed nominal value on
// Apple silicon rather than a live reading, and the real
// per-cluster residencies live behind IOReport, which
// this module does not use. Until it does, this is
// genuinely unknown and now says so.
}
}
}
}
Ok(())
}
}
// ==================== Windows Helper Functions ====================
/// Query WMI for CPU information (name, current/max MHz)
#[cfg(target_os = "windows")]
fn windows_query_wmi_cpu() -> (Option<String>, Option<u32>, Option<u32>) {
use wmi::{COMLibrary, WMIConnection};
#[derive(serde::Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct Win32Processor {
name: Option<String>,
current_clock_speed: Option<u32>,
max_clock_speed: Option<u32>,
}
if let Ok(com) = COMLibrary::new() {
if let Ok(wmi) = WMIConnection::new(com) {
if let Ok(processors) = wmi.query::<Win32Processor>() {
if let Some(p) = processors.first() {
return (p.name.clone(), p.current_clock_speed, p.max_clock_speed);
}
}
}
}
(None, None, None)
}
/// Get base CPU frequency from Windows registry
#[cfg(target_os = "windows")]
fn windows_get_base_frequency() -> u32 {
use winreg::enums::*;
use winreg::RegKey;
let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
if let Ok(cpu_key) = hklm.open_subkey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0") {
if let Ok(mhz) = cpu_key.get_value::<u32, _>("~MHz") {
return mhz;
}
}
0
}
/// Whether the active power scheme permits processor boost, from the AC value
/// of its "Processor performance boost mode" setting. `None` if `powercfg`
/// cannot be run or its output has no such value. A failed query is not read
/// as "permitted".
///
/// `/qh` (show hidden) and not `/query`: `powercfg /query` omits
/// PERFBOOSTMODE from its output on current Windows builds, so a plain query
/// returns the scheme header with no setting in it. `/qh` lists it, with its
/// `Current AC Power Setting Index` line.
#[cfg(target_os = "windows")]
fn windows_boost_permitted() -> Option<bool> {
let text = crate::core::command::capture(
"powercfg",
&["/qh", "SCHEME_CURRENT", "SUB_PROCESSOR", "PERFBOOSTMODE"],
)
.ok()?;
parse_boost_mode_ac(&text)
}
/// Parse the `Current AC Power Setting Index` line of
/// `powercfg /query SCHEME_CURRENT SUB_PROCESSOR PERFBOOSTMODE`.
///
/// Index 0 is "Disabled". Every other index (1 "Enabled", 2 "Aggressive", and
/// any later value) permits boost. The DC line is ignored: the reading is the
/// AC setting, as the machine is on mains power when it is read.
#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
fn parse_boost_mode_ac(text: &str) -> Option<bool> {
let index = text.lines().find_map(|line| {
let rest = line
.trim()
.strip_prefix("Current AC Power Setting Index:")?
.trim();
let hex = rest.strip_prefix("0x")?;
u32::from_str_radix(hex, 16).ok()
})?;
Some(index != 0)
}
/// Summary of CPU frequency status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuFreqSummary {
/// Total CPUs
pub total_cpus: usize,
/// Online CPUs, or `None` while any CPU's online state was not read
/// (Windows and macOS do not report it per CPU).
pub online_cpus: Option<usize>,
/// Current governor
pub governor: Option<String>,
/// Average frequency (MHz) over the cores that reported one, or `None`
/// if no core did.
pub avg_freq_mhz: Option<u32>,
/// Highest frequency seen (MHz), or `None` if no core reported one.
pub max_freq_mhz: Option<u32>,
/// Lowest frequency seen (MHz), or `None` if no core reported one.
pub min_freq_mhz: Option<u32>,
/// Turbo enabled: on Windows, whether the active power scheme permits
/// boost. `None` when it was not read.
pub turbo_enabled: Option<bool>,
/// CPU model
pub cpu_model: Option<String>,
/// Scaling driver
pub scaling_driver: Option<String>,
}
/// Get a summary of CPU frequency status
pub fn cpufreq_summary() -> Result<CpuFreqSummary> {
let monitor = CpuFreqMonitor::new()?;
let cpus = monitor.cpus();
// CPUs not known to be offline. A CPU whose state was not read still has
// frequency readings of its own, so it stays in the aggregates below.
let usable: Vec<_> = cpus.iter().filter(|c| c.online != Some(false)).collect();
// Averaged over the cores that reported a frequency, and `None` if none
// did. Summing `0` for an unread core and dividing by the full core count
// produced an average that was neither the mean of what was read nor a
// statement that nothing was -- it just dropped with each unreadable core.
let read: Vec<u64> = usable.iter().filter_map(|c| c.current_freq_khz).collect();
let avg_freq = if read.is_empty() {
None
} else {
Some((read.iter().sum::<u64>() / read.len() as u64 / 1000) as u32)
};
// `max`/`min` over an `Option`-yielding iterator: absent cores are skipped
// rather than contributing a `0` that wins every `min` comparison. The
// `unwrap_or(0)` here meant one unreadable core made the reported fleet
// minimum zero.
let max_freq = usable.iter().filter_map(|c| c.current_freq_mhz).max();
let min_freq = usable.iter().filter_map(|c| c.current_freq_mhz).min();
// `None` while any CPU's state is unknown. Counting only the CPUs read as
// online would present "not read" as "offline" in the total.
let online_cpus = if cpus.iter().any(|c| c.online.is_none()) {
None
} else {
Some(cpus.iter().filter(|c| c.online == Some(true)).count())
};
Ok(CpuFreqSummary {
total_cpus: cpus.len(),
online_cpus,
governor: monitor.current_governor().map(|g| g.to_string()),
avg_freq_mhz: avg_freq,
max_freq_mhz: max_freq,
min_freq_mhz: min_freq,
turbo_enabled: monitor.turbo_status().enabled,
cpu_model: usable.first().and_then(|c| c.model.clone()),
scaling_driver: usable.first().and_then(|c| c.scaling_driver.clone()),
})
}
/// Get list of all CPU frequency info
pub fn list_cpus() -> Result<Vec<CpuFreqInfo>> {
let monitor = CpuFreqMonitor::new()?;
Ok(monitor.cpus.clone())
}
/// Get available governors
pub fn available_governors() -> Result<Vec<Governor>> {
let monitor = CpuFreqMonitor::new()?;
Ok(monitor.available_governors())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_governor_display_roundtrip() {
let governors = vec![
Governor::Performance,
Governor::Powersave,
Governor::Ondemand,
Governor::Conservative,
Governor::Userspace,
Governor::Schedutil,
Governor::IntelPstate,
Governor::AmdPstate,
Governor::Interactive,
];
for gov in governors {
let s = gov.to_string();
let parsed: Governor = s.parse().unwrap();
assert_eq!(parsed, gov);
}
}
#[test]
fn test_governor_unknown_variant() {
let gov: Governor = "custom_gov".parse().unwrap();
assert_eq!(gov, Governor::Unknown("custom_gov".to_string()));
assert_eq!(gov.to_string(), "custom_gov");
}
#[test]
fn test_energy_preference_display() {
assert_eq!(EnergyPreference::Performance.to_string(), "performance");
assert_eq!(
EnergyPreference::BalancePerformance.to_string(),
"balance_performance"
);
assert_eq!(EnergyPreference::BalancePower.to_string(), "balance_power");
assert_eq!(EnergyPreference::Power.to_string(), "power");
}
#[test]
fn test_governor_serde_roundtrip() {
let gov = Governor::Schedutil;
let json = serde_json::to_string(&gov).unwrap();
let parsed: Governor = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, gov);
let gov_unk = Governor::Unknown("turbo".into());
let json = serde_json::to_string(&gov_unk).unwrap();
let parsed: Governor = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, gov_unk);
}
/// Output of `powercfg /qh SCHEME_CURRENT SUB_PROCESSOR PERFBOOSTMODE`
/// captured on Windows 11 with the Balanced scheme, boost mode "Aggressive"
/// on AC and on DC.
const BOOST_QUERY_AGGRESSIVE_AC: &str = r#"
Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)
GUID Alias: SCHEME_BALANCED
Subgroup GUID: 54533251-82be-4824-96c1-47b60b740d00 (Processor power management)
GUID Alias: SUB_PROCESSOR
Power Setting GUID: be337238-0d82-4146-a960-4f3749d470c7 (Processor performance boost mode)
GUID Alias: PERFBOOSTMODE
Possible Setting Index: 000
Possible Setting Friendly Name: Disabled
Possible Setting Index: 001
Possible Setting Friendly Name: Enabled
Possible Setting Index: 002
Possible Setting Friendly Name: Aggressive
Possible Setting Index: 003
Possible Setting Friendly Name: Efficient Enabled
Possible Setting Index: 004
Possible Setting Friendly Name: Efficient Aggressive
Possible Setting Index: 005
Possible Setting Friendly Name: Aggressive At Guaranteed
Possible Setting Index: 006
Possible Setting Friendly Name: Efficient Aggressive At Guaranteed
Current AC Power Setting Index: 0x00000002
Current DC Power Setting Index: 0x00000002
"#;
#[test]
fn boost_mode_ac_nonzero_permits_boost() {
assert_eq!(parse_boost_mode_ac(BOOST_QUERY_AGGRESSIVE_AC), Some(true));
}
#[test]
fn boost_mode_ac_zero_forbids_boost_even_when_dc_allows_it() {
let text = BOOST_QUERY_AGGRESSIVE_AC
.replace(
"Current AC Power Setting Index: 0x00000002",
"Current AC Power Setting Index: 0x00000000",
)
.replace(
"Current DC Power Setting Index: 0x00000002",
"Current DC Power Setting Index: 0x00000001",
);
assert_eq!(parse_boost_mode_ac(&text), Some(false));
}
#[test]
fn boost_mode_without_an_ac_value_is_unknown() {
// A query that names no AC index, or one that is not hex, is not a
// reading. Neither is an empty output.
let no_ac = "Current DC Power Setting Index: 0x00000001\n";
let not_hex = "Current AC Power Setting Index: two\n";
assert_eq!(parse_boost_mode_ac(no_ac), None);
assert_eq!(parse_boost_mode_ac(not_hex), None);
assert_eq!(parse_boost_mode_ac(""), None);
}
#[test]
fn test_energy_preference_serde_roundtrip() {
for pref in &[
EnergyPreference::Performance,
EnergyPreference::BalancePerformance,
EnergyPreference::BalancePower,
EnergyPreference::Power,
] {
let json = serde_json::to_string(pref).unwrap();
let parsed: EnergyPreference = serde_json::from_str(&json).unwrap();
assert_eq!(&parsed, pref);
}
}
/// "Cannot tell" and "not boosting" must not be the same answer.
///
/// `is_turbo` returned `bool`. With no `base_frequency` it returned
/// `false`, and with a maximum but no base it guessed from ">95% of max",
/// which is not a test for turbo: a part whose non-turbo ceiling *is* its
/// `cpuinfo_max_freq` reads as boosting whenever it is busy.
#[test]
fn turbo_is_unknown_without_a_base_frequency() {
let mut cpu = CpuFreqInfo::new(0);
cpu.current_freq_khz = Some(4_400_000);
cpu.cpuinfo_max_freq_khz = Some(4_400_000);
cpu.base_freq_khz = None;
assert_eq!(
cpu.is_turbo(),
None,
"at 100% of max with no base frequency, turbo is unknowable"
);
// Above base is boosting.
cpu.base_freq_khz = Some(3_700_000);
assert_eq!(cpu.is_turbo(), Some(true));
// At or below base is not.
cpu.current_freq_khz = Some(3_700_000);
assert_eq!(cpu.is_turbo(), Some(false));
}
/// A core whose current frequency was never read answers nothing, rather
/// than answering as though it were parked at 0 kHz.
///
/// Every one of these returned a confident wrong answer before: `0%` of
/// the ceiling, not at maximum, **at minimum**, not boosting. The last two
/// are the dangerous ones, because `false` and `true` are what a working
/// reading looks like.
#[test]
fn an_unread_current_frequency_answers_nothing() {
let mut cpu = CpuFreqInfo::new(0);
cpu.min_freq_khz = Some(800_000);
cpu.max_freq_khz = Some(4_400_000);
cpu.base_freq_khz = Some(3_700_000);
assert_eq!(cpu.current_freq_khz, None, "new() must not invent one");
assert_eq!(cpu.freq_percent(), None, "0% of the ceiling is a reading");
assert_eq!(cpu.is_max_freq(), None);
assert_eq!(
cpu.is_min_freq(),
None,
"0 <= min held for every minimum, so every unread core read as parked"
);
assert_eq!(cpu.is_turbo(), None);
// With a reading, all four answer again.
cpu.current_freq_khz = Some(4_400_000);
assert_eq!(cpu.freq_percent(), Some(100.0));
assert_eq!(cpu.is_max_freq(), Some(true));
assert_eq!(cpu.is_min_freq(), Some(false));
assert_eq!(cpu.is_turbo(), Some(true));
}
#[test]
fn an_unread_governor_is_not_reported_as_one() {
// Windows and macOS leave the governor unread. The placeholder must not
// come back from `current_governor` as though a governor had been read.
let monitor = CpuFreqMonitor {
cpus: vec![CpuFreqInfo::new(0)],
policies: Vec::new(),
turbo: TurboStatus {
available: None,
enabled: None,
controllable: false,
boost_mhz: None,
},
last_update: Instant::now(),
pstate_driver: None,
};
assert_eq!(monitor.current_governor(), None);
let mut read = CpuFreqInfo::new(0);
read.governor = Governor::Performance;
let monitor = CpuFreqMonitor {
cpus: vec![read],
..monitor
};
assert_eq!(monitor.current_governor(), Some(Governor::Performance));
}
}