-
-
Notifications
You must be signed in to change notification settings - Fork 987
Expand file tree
/
Copy pathbtop_collect.cpp
More file actions
2004 lines (1748 loc) · 70.6 KB
/
btop_collect.cpp
File metadata and controls
2004 lines (1748 loc) · 70.6 KB
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
/* Copyright 2021 Aristocratos (jakob@qvantnet.com)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
indent = tab
tab-size = 4
*/
#include <Availability.h>
#include <CoreFoundation/CoreFoundation.h>
#include <IOKit/IOKitLib.h>
#include <arpa/inet.h>
#include <libproc.h>
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/mach_init.h>
#include <mach/mach_types.h>
#include <mach/processor_info.h>
#include <mach/vm_statistics.h>
#include <mach/mach_time.h>
// BUGS
// If both <net/if.h> and <ifaddrs.h> are being included, <net/if.h> must be
// included before <ifaddrs.h>.
// from: https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/getifaddrs.3.html
#include <net/if.h>
#include <ifaddrs.h>
#include <net/if_dl.h>
#include <netdb.h>
#include <netinet/tcp_fsm.h>
#include <pwd.h>
#include <sys/socket.h>
#include <sys/statvfs.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <netinet/in.h> // for inet_ntop
#include <unistd.h>
#include <stdexcept>
#include <utility>
#include <cmath>
#include <fstream>
#include <mutex>
#include <numeric>
#include <ranges>
#include <regex>
#include <string>
#include <unordered_set>
#include <fmt/format.h>
#include "../btop_config.hpp"
#include "../btop_log.hpp"
#include "../btop_shared.hpp"
#include "../btop_tools.hpp"
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504
#include "sensors.hpp"
#endif
#include "smc.hpp"
#if defined(GPU_SUPPORT)
#include <dlfcn.h>
#include <mach/mach_time.h>
//? IOReport C function declarations for Apple Silicon GPU metrics
extern "C" {
typedef struct IOReportSubscription* IOReportSubscriptionRef;
CFDictionaryRef IOReportCopyChannelsInGroup(CFStringRef group, CFStringRef subgroup,
uint64_t a, uint64_t b, uint64_t c);
void IOReportMergeChannels(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull);
IOReportSubscriptionRef IOReportCreateSubscription(void* a, CFMutableDictionaryRef b,
CFMutableDictionaryRef* c, uint64_t d, CFTypeRef cfnull);
CFDictionaryRef IOReportCreateSamples(IOReportSubscriptionRef sub,
CFMutableDictionaryRef chan, CFTypeRef cfnull);
CFDictionaryRef IOReportCreateSamplesDelta(CFDictionaryRef a, CFDictionaryRef b, CFTypeRef cfnull);
CFStringRef IOReportChannelGetGroup(CFDictionaryRef item);
CFStringRef IOReportChannelGetSubGroup(CFDictionaryRef item);
CFStringRef IOReportChannelGetChannelName(CFDictionaryRef item);
int64_t IOReportSimpleGetIntegerValue(CFDictionaryRef item, int32_t idx);
CFStringRef IOReportChannelGetUnitLabel(CFDictionaryRef item);
int32_t IOReportStateGetCount(CFDictionaryRef item);
CFStringRef IOReportStateGetNameForIndex(CFDictionaryRef item, int32_t idx);
int64_t IOReportStateGetResidency(CFDictionaryRef item, int32_t idx);
//? IOHIDEvent declarations for GPU temperature
typedef struct __IOHIDEvent* IOHIDEventRef;
typedef struct __IOHIDServiceClient* IOHIDServiceClientRef;
typedef struct __IOHIDEventSystemClient* IOHIDEventSystemClientRef;
#ifdef __LP64__
typedef double IOHIDFloat;
#else
typedef float IOHIDFloat;
#endif
IOHIDEventSystemClientRef IOHIDEventSystemClientCreate(CFAllocatorRef allocator);
int IOHIDEventSystemClientSetMatching(IOHIDEventSystemClientRef client, CFDictionaryRef match);
CFArrayRef IOHIDEventSystemClientCopyServices(IOHIDEventSystemClientRef client);
IOHIDEventRef IOHIDServiceClientCopyEvent(IOHIDServiceClientRef sc, int64_t type, int32_t a, int64_t b);
CFStringRef IOHIDServiceClientCopyProperty(IOHIDServiceClientRef service, CFStringRef property);
IOHIDFloat IOHIDEventGetFloatValue(IOHIDEventRef event, int32_t field);
}
#endif // GPU_SUPPORT
#if __MAC_OS_X_VERSION_MIN_REQUIRED < 120000
#define kIOMainPortDefault kIOMasterPortDefault
#endif
using std::clamp, std::string_literals::operator""s, std::cmp_equal, std::cmp_less, std::cmp_greater;
using std::ifstream, std::numeric_limits, std::streamsize, std::round, std::max, std::min;
namespace fs = std::filesystem;
namespace rng = std::ranges;
using namespace Tools;
//? RAII wrapper for CoreFoundation types — releases via CFRelease() on destruction
template <typename T>
struct CFRef {
T ref;
CFRef() : ref(nullptr) {}
CFRef(T ref) : ref(ref) {}
~CFRef() { if (ref) CFRelease((CFTypeRef)ref); }
CFRef(const CFRef&) = delete;
CFRef& operator=(const CFRef&) = delete;
CFRef(CFRef&& other) noexcept : ref(other.ref) { other.ref = nullptr; }
CFRef& operator=(CFRef&& other) noexcept {
if (this != &other) { reset(); ref = other.ref; other.ref = nullptr; }
return *this;
}
operator T() const { return ref; }
T get() const { return ref; }
T* ptr() { return &ref; }
void reset(T new_ref = nullptr) {
if (ref) CFRelease((CFTypeRef)ref);
ref = new_ref;
}
T release() { T r = ref; ref = nullptr; return r; }
};
//? RAII wrapper for IOKit object types — releases via IOObjectRelease() on destruction
struct IORef {
io_object_t ref;
IORef() : ref(0) {}
IORef(io_object_t ref) : ref(ref) {}
~IORef() { if (ref) IOObjectRelease(ref); }
IORef(const IORef&) = delete;
IORef& operator=(const IORef&) = delete;
operator io_object_t() const { return ref; }
io_object_t get() const { return ref; }
io_object_t* ptr() { return &ref; }
};
//? --------------------------------------------------- FUNCTIONS -----------------------------------------------------
namespace Cpu {
vector<long long> core_old_totals;
vector<long long> core_old_idles;
vector<string> available_fields = {"Auto", "total"};
vector<string> available_sensors = {"Auto"};
cpu_info current_cpu;
bool got_sensors = false, cpu_temp_only = false, supports_watts = false;
int core_offset = 0;
//* Populate found_sensors map
bool get_sensors();
//* Get current cpu clock speed
string get_cpuHz();
//* Search /proc/cpuinfo for a cpu name
string get_cpuName();
struct Sensor {
fs::path path;
string label;
int64_t temp = 0;
int64_t high = 0;
int64_t crit = 0;
};
string cpu_sensor;
vector<string> core_sensors;
std::unordered_map<int, int> core_mapping;
} // namespace Cpu
namespace Mem {
double old_uptime;
}
#if defined(GPU_SUPPORT)
namespace Gpu {
vector<gpu_info> gpus;
//? Stub shutdown for backends not available on macOS
namespace Nvml { bool shutdown() { return false; } }
namespace Rsmi { bool shutdown() { return false; } }
//? Apple Silicon GPU data collection via IOReport
namespace AppleSilicon {
bool initialized = false;
unsigned int device_count = 0;
//? Forward declaration
template <bool is_init>
bool collect(gpu_info* gpus_slice);
//? IOReport subscription state
IOReportSubscriptionRef ior_sub = nullptr;
CFMutableDictionaryRef ior_chan = nullptr;
CFDictionaryRef prev_sample = nullptr;
uint64_t prev_sample_time = 0;
//? GPU frequency table from DVFS
vector<uint32_t> gpu_freqs;
static string cfstring_to_string(CFStringRef cfstr) {
if (not cfstr) return "";
char buf[256];
if (CFStringGetCString(cfstr, buf, sizeof(buf), kCFStringEncodingUTF8))
return string(buf);
return "";
}
static string get_chip_name() {
char buf[256];
size_t size = sizeof(buf);
if (sysctlbyname("machdep.cpu.brand_string", buf, &size, nullptr, 0) == 0)
return string(buf);
return "Apple Silicon GPU";
}
static uint64_t get_mach_time_ms() {
static mach_timebase_info_data_t timebase = {0, 0};
if (timebase.denom == 0) mach_timebase_info(&timebase);
return (mach_absolute_time() * timebase.numer / timebase.denom) / 1000000;
}
//? Read GPU DVFS frequency table from IORegistry pmgr node
static void get_gpu_freqs_from_pmgr() {
io_iterator_t iter_raw;
//? matchDict ownership is consumed by IOServiceGetMatchingServices
CFMutableDictionaryRef matchDict = IOServiceMatching("AppleARMIODevice");
if (IOServiceGetMatchingServices(kIOMainPortDefault, matchDict, &iter_raw) != kIOReturnSuccess)
return;
IORef iter(iter_raw);
io_object_t entry_raw;
while ((entry_raw = IOIteratorNext(iter)) != 0) {
IORef entry(entry_raw);
char name[128];
if (IORegistryEntryGetName(entry, name) == kIOReturnSuccess and string(name) == "pmgr") {
CFMutableDictionaryRef props_raw = nullptr;
if (IORegistryEntryCreateCFProperties(entry, &props_raw, kCFAllocatorDefault, 0) == kIOReturnSuccess and props_raw) {
CFRef<CFMutableDictionaryRef> props(props_raw);
CFDataRef dvfs_data = (CFDataRef)CFDictionaryGetValue(props, CFSTR("voltage-states9"));
if (dvfs_data) {
auto len = CFDataGetLength(dvfs_data);
auto ptr = CFDataGetBytePtr(dvfs_data);
//? Pairs of (freq, voltage), 4 bytes each
for (CFIndex i = 0; i + 7 < len; i += 8) {
uint32_t freq = 0;
memcpy(&freq, ptr + i, 4);
if (freq > 0) gpu_freqs.push_back(freq / (1000 * 1000)); // Hz -> MHz
}
}
}
}
}
}
bool init() {
if (initialized) return false;
//? Get GPU frequency table
get_gpu_freqs_from_pmgr();
//? Set up IOReport channels for GPU Stats and Energy Model
CFRef<CFStringRef> gpu_stats_group(CFStringCreateWithCString(kCFAllocatorDefault, "GPU Stats", kCFStringEncodingUTF8));
CFRef<CFStringRef> gpu_perf_subgroup(CFStringCreateWithCString(kCFAllocatorDefault, "GPU Performance States", kCFStringEncodingUTF8));
CFRef<CFStringRef> energy_group(CFStringCreateWithCString(kCFAllocatorDefault, "Energy Model", kCFStringEncodingUTF8));
CFRef<CFDictionaryRef> gpu_chan(IOReportCopyChannelsInGroup(gpu_stats_group, gpu_perf_subgroup, 0, 0, 0));
CFRef<CFDictionaryRef> energy_chan(IOReportCopyChannelsInGroup(energy_group, nullptr, 0, 0, 0));
if (not gpu_chan.get() and not energy_chan.get()) {
Logger::info("Apple Silicon GPU: No IOReport channels found, GPU monitoring unavailable");
return false;
}
//? Merge channels into a single subscription
if (gpu_chan.get() and energy_chan.get()) {
IOReportMergeChannels(gpu_chan, energy_chan, nullptr);
}
CFDictionaryRef base_chan = gpu_chan.get() ? gpu_chan.get() : energy_chan.get();
auto size = CFDictionaryGetCount(base_chan);
ior_chan = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, size, base_chan);
//? Create IOReport subscription
CFMutableDictionaryRef sub_dict = nullptr;
ior_sub = IOReportCreateSubscription(nullptr, ior_chan, &sub_dict, 0, nullptr);
if (not ior_sub) {
Logger::warning("Apple Silicon GPU: Failed to create IOReport subscription");
CFRelease(ior_chan);
ior_chan = nullptr;
return false;
}
device_count = 1; //? Apple Silicon has one integrated GPU
gpus.resize(gpus.size() + device_count);
gpu_names.resize(gpu_names.size() + device_count);
initialized = true;
//? Take initial sample for delta computation
prev_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr);
prev_sample_time = get_mach_time_ms();
//? Run init collect to populate names and supported functions
collect<1>(gpus.data());
return true;
}
bool shutdown() {
if (not initialized) return false;
if (prev_sample) { CFRelease(prev_sample); prev_sample = nullptr; }
if (ior_chan) { CFRelease(ior_chan); ior_chan = nullptr; }
if (ior_sub) { CFRelease((CFTypeRef)ior_sub); ior_sub = nullptr; }
initialized = false;
return true;
}
//? Read GPU temperature via IOHIDEventSystem thermal sensors
static long long get_gpu_temp_iohid() {
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504
constexpr int kHIDPage_AppleVendor = 0xff00;
constexpr int kHIDUsage_TemperatureSensor = 5;
constexpr int64_t kIOHIDEventTypeTemperature = 15;
CFStringRef keys[2] = { CFSTR("PrimaryUsagePage"), CFSTR("PrimaryUsage") };
int page = kHIDPage_AppleVendor, usage = kHIDUsage_TemperatureSensor;
CFRef<CFNumberRef> num0(CFNumberCreate(nullptr, kCFNumberSInt32Type, &page));
CFRef<CFNumberRef> num1(CFNumberCreate(nullptr, kCFNumberSInt32Type, &usage));
const void* values[] = { num0.get(), num1.get() };
CFRef<CFDictionaryRef> match(CFDictionaryCreate(nullptr,
(const void**)keys, values, 2,
&kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks));
CFRef<IOHIDEventSystemClientRef> system(IOHIDEventSystemClientCreate(kCFAllocatorDefault));
if (not system.get()) return -1;
IOHIDEventSystemClientSetMatching(system, match);
CFRef<CFArrayRef> services(IOHIDEventSystemClientCopyServices(system));
if (not services.get()) return -1;
double gpu_temp_sum = 0;
int gpu_temp_count = 0;
long count = CFArrayGetCount(services);
for (long i = 0; i < count; i++) {
auto sc = (IOHIDServiceClientRef)CFArrayGetValueAtIndex(services, i);
if (not sc) continue;
CFRef<CFStringRef> name(IOHIDServiceClientCopyProperty(sc, CFSTR("Product")));
if (not name.get()) continue;
char buf[200];
CFStringGetCString(name, buf, 200, kCFStringEncodingASCII);
string n(buf);
//? "GPU MTR Temp Sensor" is the standard Apple Silicon GPU temp sensor name
if (n.find("GPU") != string::npos) {
CFRef<IOHIDEventRef> event(IOHIDServiceClientCopyEvent(sc, kIOHIDEventTypeTemperature, 0, 0));
if (event.get()) {
double temp = IOHIDEventGetFloatValue(event, kIOHIDEventTypeTemperature << 16);
if (temp > 0 and temp < 150) {
gpu_temp_sum += temp;
gpu_temp_count++;
}
}
}
}
if (gpu_temp_count > 0)
return static_cast<long long>(round(gpu_temp_sum / gpu_temp_count));
#endif
return -1;
}
template <bool is_init>
bool collect(gpu_info* gpus_slice) {
if (not initialized) return false;
if constexpr (is_init) {
//? Device name
string chip = get_chip_name();
gpu_names[0] = chip + " GPU";
//? Power max (typical Apple Silicon GPU TDP ~15-20W)
gpus_slice[0].pwr_max_usage = 20000; // 20W in mW
gpu_pwr_total_max += gpus_slice[0].pwr_max_usage;
//? Temperature max
gpus_slice[0].temp_max = 110;
//? Memory total (unified memory architecture — GPU shares system RAM)
int64_t memsize = 0;
size_t size = sizeof(memsize);
if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) == 0)
gpus_slice[0].mem_total = memsize;
//? Supported functions
gpus_slice[0].supported_functions = {
.gpu_utilization = true,
.mem_utilization = true,
.gpu_clock = not gpu_freqs.empty(),
.mem_clock = false,
.pwr_usage = true,
.pwr_state = false,
.temp_info = true,
.mem_total = true,
.mem_used = true,
.pcie_txrx = false,
.encoder_utilization = false,
.decoder_utilization = false
};
}
//? Take new IOReport sample and compute delta
CFDictionaryRef cur_sample = IOReportCreateSamples(ior_sub, ior_chan, nullptr);
if (not cur_sample) return false;
uint64_t cur_time = get_mach_time_ms();
uint64_t dt = cur_time - prev_sample_time;
if (dt == 0) dt = 1;
CFRef<CFDictionaryRef> delta;
if (prev_sample) {
delta.reset(IOReportCreateSamplesDelta(prev_sample, cur_sample, nullptr));
CFRelease(prev_sample);
}
prev_sample = cur_sample;
prev_sample_time = cur_time;
if (not delta.get()) return false;
//? Parse delta samples
CFArrayRef channels = (CFArrayRef)CFDictionaryGetValue(delta, CFSTR("IOReportChannels"));
if (not channels) return false;
long long gpu_utilization = 0;
bool got_gpu_util = false;
double gpu_power_watts = 0;
bool got_gpu_power = false;
long chan_count = CFArrayGetCount(channels);
for (long i = 0; i < chan_count; i++) {
CFDictionaryRef item = (CFDictionaryRef)CFArrayGetValueAtIndex(channels, i);
if (not item) continue;
string group = cfstring_to_string(IOReportChannelGetGroup(item));
string subgroup = cfstring_to_string(IOReportChannelGetSubGroup(item));
string channel = cfstring_to_string(IOReportChannelGetChannelName(item));
//? GPU utilization from residency states
if (group == "GPU Stats" and subgroup == "GPU Performance States" and channel == "GPUPH") {
int32_t state_count = IOReportStateGetCount(item);
if (state_count <= 0) continue;
int64_t total_residency = 0;
int64_t active_residency = 0;
double weighted_freq = 0;
//? Find offset past IDLE/OFF/DOWN states
int offset = 0;
for (int32_t s = 0; s < state_count; s++) {
string name = cfstring_to_string(IOReportStateGetNameForIndex(item, s));
if (name == "IDLE" or name == "OFF" or name == "DOWN")
offset = s + 1;
total_residency += IOReportStateGetResidency(item, s);
}
int freq_count = static_cast<int>(gpu_freqs.size());
for (int32_t s = offset; s < state_count; s++) {
int64_t res = IOReportStateGetResidency(item, s);
active_residency += res;
int freq_idx = s - offset;
if (freq_idx < freq_count and active_residency > 0)
weighted_freq += static_cast<double>(res) * gpu_freqs[freq_idx];
}
if (total_residency > 0) {
double usage_ratio = static_cast<double>(active_residency) / static_cast<double>(total_residency);
gpu_utilization = clamp(static_cast<long long>(round(usage_ratio * 100.0)), 0ll, 100ll);
got_gpu_util = true;
//? Calculate average frequency
if (active_residency > 0 and not gpu_freqs.empty()) {
double avg_freq = weighted_freq / static_cast<double>(active_residency);
gpus_slice[0].gpu_clock_speed = static_cast<unsigned int>(round(avg_freq));
}
}
}
//? GPU power from Energy Model
if (group == "Energy Model" and channel == "GPU Energy") {
string unit = cfstring_to_string(IOReportChannelGetUnitLabel(item));
int64_t val = IOReportSimpleGetIntegerValue(item, 0);
double energy = static_cast<double>(val);
double divisor = static_cast<double>(dt) / 1000.0; // dt is in ms
if (unit.find("nJ") != string::npos) energy /= 1e9;
else if (unit.find("uJ") != string::npos or unit.find("\xc2\xb5J") != string::npos) energy /= 1e6;
else if (unit.find("mJ") != string::npos) energy /= 1e3;
//? energy is now in Joules
if (divisor > 0) {
gpu_power_watts = energy / divisor;
got_gpu_power = true;
}
}
}
//? Store GPU utilization
if (got_gpu_util) {
gpus_slice[0].gpu_percent.at("gpu-totals").push_back(gpu_utilization);
gpus_slice[0].mem_utilization_percent.push_back(gpu_utilization);
}
//? Store power usage (convert W to mW)
if (got_gpu_power) {
gpus_slice[0].pwr_usage = static_cast<long long>(round(gpu_power_watts * 1000.0));
if (gpus_slice[0].pwr_usage > gpus_slice[0].pwr_max_usage)
gpus_slice[0].pwr_max_usage = gpus_slice[0].pwr_usage;
gpus_slice[0].gpu_percent.at("gpu-pwr-totals").push_back(
clamp(static_cast<long long>(round(static_cast<double>(gpus_slice[0].pwr_usage) * 100.0 / static_cast<double>(gpus_slice[0].pwr_max_usage))), 0ll, 100ll));
}
//? GPU temperature
if (gpus_slice[0].supported_functions.temp_info and Config::getB("check_temp")) {
long long temp = get_gpu_temp_iohid();
if (temp > 0)
gpus_slice[0].temp.push_back(temp);
}
//? Memory usage (unified memory — report system memory usage)
if (gpus_slice[0].supported_functions.mem_total) {
vm_size_t page_size;
mach_port_t mach_port = mach_host_self();
vm_statistics64_data_t vm_stats;
mach_msg_type_number_t count = sizeof(vm_stats) / sizeof(natural_t);
host_page_size(mach_port, &page_size);
if (host_statistics64(mach_port, HOST_VM_INFO64, (host_info64_t)&vm_stats, &count) == KERN_SUCCESS) {
long long used = (static_cast<int64_t>(vm_stats.active_count)
+ static_cast<int64_t>(vm_stats.inactive_count)
+ static_cast<int64_t>(vm_stats.wire_count)
+ static_cast<int64_t>(vm_stats.speculative_count)
+ static_cast<int64_t>(vm_stats.compressor_page_count)
- static_cast<int64_t>(vm_stats.purgeable_count)
- static_cast<int64_t>(vm_stats.external_page_count)) * static_cast<int64_t>(page_size);
if (used < 0) used = 0;
gpus_slice[0].mem_used = used;
if (gpus_slice[0].mem_total > 0) {
auto used_pct = static_cast<long long>(round(static_cast<double>(used) * 100.0 / static_cast<double>(gpus_slice[0].mem_total)));
gpus_slice[0].gpu_percent.at("gpu-vram-totals").push_back(clamp(used_pct, 0ll, 100ll));
}
}
}
return true;
}
//? Explicit template instantiations
template bool collect<true>(gpu_info*);
template bool collect<false>(gpu_info*);
} // namespace AppleSilicon
//? Collect data from Apple Silicon GPU
auto collect(bool no_update) -> vector<gpu_info>& {
if (Runner::stopping or (no_update and not gpus.empty())) return gpus;
AppleSilicon::collect<0>(gpus.data());
//* Calculate averages
long long avg = 0;
long long mem_usage_total = 0;
long long mem_total = 0;
long long pwr_total = 0;
for (auto& gpu : gpus) {
if (gpu.supported_functions.gpu_utilization and not gpu.gpu_percent.at("gpu-totals").empty())
avg += gpu.gpu_percent.at("gpu-totals").back();
if (gpu.supported_functions.mem_used)
mem_usage_total += gpu.mem_used;
if (gpu.supported_functions.mem_total)
mem_total += gpu.mem_total;
if (gpu.supported_functions.pwr_usage)
pwr_total += gpu.pwr_usage;
//* Trim vectors if there are more values than needed for graphs
if (width != 0) {
while (cmp_greater(gpu.gpu_percent.at("gpu-totals").size(), width * 2)) gpu.gpu_percent.at("gpu-totals").pop_front();
while (cmp_greater(gpu.mem_utilization_percent.size(), width)) gpu.mem_utilization_percent.pop_front();
while (cmp_greater(gpu.gpu_percent.at("gpu-pwr-totals").size(), width)) gpu.gpu_percent.at("gpu-pwr-totals").pop_front();
while (cmp_greater(gpu.temp.size(), 18)) gpu.temp.pop_front();
while (cmp_greater(gpu.gpu_percent.at("gpu-vram-totals").size(), width/2)) gpu.gpu_percent.at("gpu-vram-totals").pop_front();
}
}
if (not gpus.empty()) {
shared_gpu_percent.at("gpu-average").push_back(avg / static_cast<long long>(gpus.size()));
if (mem_total != 0)
shared_gpu_percent.at("gpu-vram-total").push_back(mem_usage_total * 100 / mem_total);
if (gpu_pwr_total_max != 0)
shared_gpu_percent.at("gpu-pwr-total").push_back(pwr_total * 100 / gpu_pwr_total_max);
}
if (width != 0) {
while (cmp_greater(shared_gpu_percent.at("gpu-average").size(), width * 2)) shared_gpu_percent.at("gpu-average").pop_front();
while (cmp_greater(shared_gpu_percent.at("gpu-vram-total").size(), width)) shared_gpu_percent.at("gpu-vram-total").pop_front();
while (cmp_greater(shared_gpu_percent.at("gpu-pwr-total").size(), width)) shared_gpu_percent.at("gpu-pwr-total").pop_front();
}
return gpus;
}
} // namespace Gpu
#endif // GPU_SUPPORT
class MachProcessorInfo {
public:
processor_info_array_t info_array;
mach_msg_type_number_t info_count;
MachProcessorInfo() {}
virtual ~MachProcessorInfo() {vm_deallocate(mach_task_self(), (vm_address_t)info_array, (vm_size_t)sizeof(processor_info_array_t) * info_count);}
};
namespace Shared {
fs::path passwd_path;
uint64_t totalMem;
long pageSize, coreCount, clkTck, physicalCoreCount, arg_max;
double machTck;
int totalMem_len;
void init() {
//? Shared global variables init
coreCount = sysconf(_SC_NPROCESSORS_ONLN); // this returns all logical cores (threads)
if (coreCount < 1) {
coreCount = 1;
Logger::warning("Could not determine number of cores, defaulting to 1.");
}
size_t physicalCoreCountSize = sizeof(physicalCoreCount);
if (sysctlbyname("hw.physicalcpu", &physicalCoreCount, &physicalCoreCountSize, nullptr, 0) < 0) {
Logger::error("Could not get physical core count");
}
pageSize = sysconf(_SC_PAGE_SIZE);
if (pageSize <= 0) {
pageSize = 4096;
Logger::warning("Could not get system page size. Defaulting to 4096, processes memory usage might be incorrect.");
}
mach_timebase_info_data_t convf;
if (mach_timebase_info(&convf) == KERN_SUCCESS) {
machTck = convf.numer / convf.denom;
} else {
Logger::warning("Could not get mach clock tick conversion factor. Defaulting to 100, processes cpu usage might be incorrect.");
machTck = 100;
}
clkTck = sysconf(_SC_CLK_TCK);
if (clkTck <= 0) {
clkTck = 100;
Logger::warning("Could not get system clock ticks per second. Defaulting to 100, processes cpu usage might be incorrect.");
}
int64_t memsize = 0;
size_t size = sizeof(memsize);
if (sysctlbyname("hw.memsize", &memsize, &size, nullptr, 0) < 0) {
Logger::warning("Could not get memory size");
}
totalMem = memsize;
//* Get maximum length of process arguments
arg_max = sysconf(_SC_ARG_MAX);
//? Init for namespace Cpu
Cpu::current_cpu.core_percent.insert(Cpu::current_cpu.core_percent.begin(), Shared::coreCount, {});
Cpu::current_cpu.temp.insert(Cpu::current_cpu.temp.begin(), Shared::coreCount + 1, {});
Cpu::core_old_totals.insert(Cpu::core_old_totals.begin(), Shared::coreCount, 0);
Cpu::core_old_idles.insert(Cpu::core_old_idles.begin(), Shared::coreCount, 0);
Cpu::collect();
for (auto &[field, vec] : Cpu::current_cpu.cpu_percent) {
if (not vec.empty() and not v_contains(Cpu::available_fields, field)) Cpu::available_fields.push_back(field);
}
Cpu::cpuName = Cpu::get_cpuName();
Cpu::got_sensors = Cpu::get_sensors();
Cpu::core_mapping = Cpu::get_core_mapping();
//? Init for namespace Gpu
#ifdef GPU_SUPPORT
auto shown_gpus = Config::getS("shown_gpus");
if (shown_gpus.contains("apple")) {
Gpu::AppleSilicon::init();
}
if (not Gpu::gpu_names.empty()) {
for (auto const& [key, _] : Gpu::gpus[0].gpu_percent)
Cpu::available_fields.push_back(key);
for (auto const& [key, _] : Gpu::shared_gpu_percent)
Cpu::available_fields.push_back(key);
using namespace Gpu;
count = gpus.size();
gpu_b_height_offsets.resize(gpus.size());
for (size_t i = 0; i < gpu_b_height_offsets.size(); ++i)
gpu_b_height_offsets[i] = gpus[i].supported_functions.gpu_utilization
+ gpus[i].supported_functions.pwr_usage
+ (gpus[i].supported_functions.encoder_utilization or gpus[i].supported_functions.decoder_utilization)
+ (gpus[i].supported_functions.mem_total or gpus[i].supported_functions.mem_used)
* (1 + 2*(gpus[i].supported_functions.mem_total and gpus[i].supported_functions.mem_used) + 2*gpus[i].supported_functions.mem_utilization);
}
#endif
//? Init for namespace Mem
Mem::old_uptime = system_uptime();
Mem::collect();
}
} // namespace Shared
namespace Cpu {
string cpuName;
string cpuHz;
bool has_battery = true;
bool macM1 = false;
tuple<int, float, long, string> current_bat;
const array<string, 10> time_names = {"user", "nice", "system", "idle"};
std::unordered_map<string, long long> cpu_old = {
{"totals", 0},
{"idles", 0},
{"user", 0},
{"nice", 0},
{"system", 0},
{"idle", 0}
};
string get_cpuName() {
string name;
char buffer[1024];
size_t size = sizeof(buffer);
if (sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nullptr, 0) < 0) {
Logger::error("Failed to get CPU name");
return name;
}
return trim_name(string(buffer));
}
bool get_sensors() {
Logger::debug("get_sensors(): show_coretemp={} check_temp={}", Config::getB("show_coretemp"), Config::getB("check_temp"));
got_sensors = false;
if (Config::getB("show_coretemp") and Config::getB("check_temp")) {
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504
ThermalSensors sensors;
if (sensors.getSensors() > 0) {
Logger::debug("M1 sensors found");
got_sensors = true;
cpu_temp_only = true;
macM1 = true;
} else {
#endif
// try SMC (intel)
Logger::debug("checking intel");
try {
SMCConnection smcCon;
Logger::debug("SMC connection established");
long long t = smcCon.getTemp(-1); // check if we have package T
if (t > -1) {
Logger::debug("intel sensors found");
got_sensors = true;
t = smcCon.getTemp(0);
if (t == -1) {
// for some macs the core offset is 1 - check if we get a sane value with 1
if (smcCon.getTemp(1) > -1) {
Logger::debug("intel sensors with offset 1");
core_offset = 1;
}
}
} else {
Logger::debug("no intel sensors found");
got_sensors = false;
}
} catch (std::runtime_error &e) {
Logger::debug("SMC not available: {}", e.what());
// ignore, we don't have temp (common in VMs)
got_sensors = false;
}
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504
}
#endif
}
return got_sensors;
}
void update_sensors() {
current_cpu.temp_max = 95; // we have no idea how to get the critical temp
try {
if (macM1) {
#if __MAC_OS_X_VERSION_MIN_REQUIRED > 101504
ThermalSensors sensors;
current_cpu.temp.at(0).push_back(sensors.getSensors());
if (current_cpu.temp.at(0).size() > 20)
current_cpu.temp.at(0).pop_front();
#endif
} else {
SMCConnection smcCon;
int threadsPerCore = Shared::coreCount / Shared::physicalCoreCount;
long long packageT = smcCon.getTemp(-1); // -1 returns package T
current_cpu.temp.at(0).push_back(packageT);
for (int core = 0; core < Shared::coreCount; core++) {
long long temp = smcCon.getTemp((core / threadsPerCore) + core_offset); // same temp for all threads of same physical core
if (cmp_less(core + 1, current_cpu.temp.size())) {
current_cpu.temp.at(core + 1).push_back(temp);
if (current_cpu.temp.at(core + 1).size() > 20)
current_cpu.temp.at(core + 1).pop_front();
}
}
}
} catch (std::runtime_error &e) {
got_sensors = false;
Logger::error("failed getting CPU temp");
}
}
string get_cpuHz() {
unsigned int freq = 1;
size_t size = sizeof(freq);
int mib[] = {CTL_HW, HW_CPU_FREQ};
if (sysctl(mib, 2, &freq, &size, nullptr, 0) < 0) {
// this fails on Apple Silicon macs. Apparently you're not allowed to know
return "";
}
return std::to_string(freq / 1000.0 / 1000.0 / 1000.0).substr(0, 3);
}
auto get_core_mapping() -> std::unordered_map<int, int> {
std::unordered_map<int, int> core_map;
if (cpu_temp_only) return core_map;
natural_t cpu_count;
natural_t i;
MachProcessorInfo info {};
kern_return_t error;
error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count);
if (error != KERN_SUCCESS) {
Logger::error("Failed getting CPU info");
return core_map;
}
for (i = 0; i < cpu_count; i++) {
core_map[i] = i;
}
//? If core mapping from cpuinfo was incomplete try to guess remainder, if missing completely, map 0-0 1-1 2-2 etc.
if (cmp_less(core_map.size(), Shared::coreCount)) {
if (Shared::coreCount % 2 == 0 and (long) core_map.size() == Shared::coreCount / 2) {
for (int i = 0, n = 0; i < Shared::coreCount / 2; i++) {
if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
core_map[Shared::coreCount / 2 + i] = n++;
}
} else {
core_map.clear();
for (int i = 0, n = 0; i < Shared::coreCount; i++) {
if (std::cmp_greater_equal(n, core_sensors.size())) n = 0;
core_map[i] = n++;
}
}
}
//? Apply user set custom mapping if any
const auto &custom_map = Config::getS("cpu_core_map");
if (not custom_map.empty()) {
try {
for (const auto &split : ssplit(custom_map)) {
const auto vals = ssplit(split, ':');
if (vals.size() != 2) continue;
int change_id = std::stoi(vals.at(0));
int new_id = std::stoi(vals.at(1));
if (not core_map.contains(change_id) or cmp_greater(new_id, core_sensors.size())) continue;
core_map.at(change_id) = new_id;
}
} catch (...) {
}
}
return core_map;
}
class IOPSInfo_Wrap {
CFTypeRef data;
public:
IOPSInfo_Wrap() { data = IOPSCopyPowerSourcesInfo(); }
CFTypeRef& operator()() { return data; }
~IOPSInfo_Wrap() { CFRelease(data); }
};
class IOPSList_Wrap {
CFArrayRef data;
public:
IOPSList_Wrap(CFTypeRef cft_ref) { data = IOPSCopyPowerSourcesList(cft_ref); }
CFArrayRef& operator()() { return data; }
~IOPSList_Wrap() { CFRelease(data); }
};
auto get_battery() -> tuple<int, float, long, string> {
if (not has_battery) return {0, 0, 0, ""};
uint32_t percent = -1;
long seconds = -1;
string status = "discharging";
IOPSInfo_Wrap ps_info{};
if (ps_info()) {
IOPSList_Wrap one_ps_descriptor(ps_info());
if (one_ps_descriptor()) {
if (CFArrayGetCount(one_ps_descriptor())) {
CFDictionaryRef one_ps = IOPSGetPowerSourceDescription(ps_info(), CFArrayGetValueAtIndex(one_ps_descriptor(), 0));
has_battery = true;
CFNumberRef remaining = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSTimeToEmptyKey));
int32_t estimatedMinutesRemaining;
if (remaining) {
CFNumberGetValue(remaining, kCFNumberSInt32Type, &estimatedMinutesRemaining);
seconds = estimatedMinutesRemaining * 60;
}
CFNumberRef charge = (CFNumberRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSCurrentCapacityKey));
if (charge) {
CFNumberGetValue(charge, kCFNumberSInt32Type, &percent);
}
CFBooleanRef charging = (CFBooleanRef)CFDictionaryGetValue(one_ps, CFSTR(kIOPSIsChargingKey));
if (charging) {
bool isCharging = CFBooleanGetValue(charging);
if (isCharging) {
status = "charging";
}
}
if (percent == 100) {
status = "full";
}
} else {
has_battery = false;
}
} else {
has_battery = false;
}
}
return {percent, -1, seconds, status};
}
auto collect(bool no_update) -> cpu_info & {
if (Runner::stopping or (no_update and not current_cpu.cpu_percent.at("total").empty()))
return current_cpu;
auto &cpu = current_cpu;
if (getloadavg(cpu.load_avg.data(), cpu.load_avg.size()) < 0) {
Logger::error("failed to get load averages");
}
natural_t cpu_count;
natural_t i;
kern_return_t error;
processor_cpu_load_info_data_t *cpu_load_info = nullptr;
MachProcessorInfo info{};
error = host_processor_info(mach_host_self(), PROCESSOR_CPU_LOAD_INFO, &cpu_count, &info.info_array, &info.info_count);
if (error != KERN_SUCCESS) {
Logger::error("Failed getting CPU load info");
}
cpu_load_info = (processor_cpu_load_info_data_t *)info.info_array;
long long global_totals = 0;
long long global_idles = 0;
vector<long long> times_summed = {0, 0, 0, 0};
for (i = 0; i < cpu_count; i++) {
vector<long long> times;
//? 0=user, 1=nice, 2=system, 3=idle
for (int x = 0; const unsigned int c_state : {CPU_STATE_USER, CPU_STATE_NICE, CPU_STATE_SYSTEM, CPU_STATE_IDLE}) {
auto val = cpu_load_info[i].cpu_ticks[c_state];
times.push_back(val);
times_summed.at(x++) += val;
}