-
Notifications
You must be signed in to change notification settings - Fork 476
/
cpucounters.cpp
9546 lines (8679 loc) · 345 KB
/
cpucounters.cpp
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
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2009-2022, Intel Corporation
// written by Roman Dementiev
// Otto Bruggeman
// Thomas Willhalm
// Pat Fay
// Austen Ott
// Jim Harris (FreeBSD)
/*! \file cpucounters.cpp
\brief The bulk of PCM implementation
*/
//#define PCM_TEST_FALLBACK_TO_ATOM
#include <stdio.h>
#include <assert.h>
#ifdef PCM_EXPORTS
// pcm-lib.h includes cpucounters.h
#include "windows\pcm-lib.h"
#else
#include "cpucounters.h"
#endif
#include "msr.h"
#include "pci.h"
#include "types.h"
#include "utils.h"
#include "topology.h"
#if defined (__FreeBSD__) || defined(__DragonFly__)
#include <sys/param.h>
#include <sys/module.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/sem.h>
#include <sys/ioccom.h>
#include <sys/cpuctl.h>
#include <machine/cpufunc.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#include <windows.h>
#include <comdef.h>
#include <tchar.h>
#include "winring0/OlsApiInit.h"
#include "windows/windriver.h"
#else
#include <pthread.h>
#if defined(__FreeBSD__) || (defined(__DragonFly__) && __DragonFly_version >= 400707)
#include <pthread_np.h>
#include <sys/_cpuset.h>
#include <sys/cpuset.h>
#endif
#include <errno.h>
#include <sys/time.h>
#ifdef __linux__
#include <sys/mman.h>
#include <dirent.h>
#include <sys/resource.h>
#endif
#endif
#include <string.h>
#include <limits>
#include <map>
#include <unordered_map>
#include <algorithm>
#include <thread>
#include <future>
#include <functional>
#include <queue>
#include <condition_variable>
#include <mutex>
#include <atomic>
#ifdef __APPLE__
#include <sys/types.h>
#include <sys/sysctl.h>
#include <sys/sem.h>
#endif
namespace pcm {
#ifdef __APPLE__
// convertUnknownToInt is used in the safe sysctl call to convert an unknown size to an int
int convertUnknownToInt(size_t size, char* value);
#endif
#ifdef _MSC_VER
HMODULE hOpenLibSys = NULL;
#ifndef NO_WINRING
bool PCM::initWinRing0Lib()
{
const BOOL result = InitOpenLibSys(&hOpenLibSys);
if (result == FALSE)
{
DeinitOpenLibSys(&hOpenLibSys);
hOpenLibSys = NULL;
return false;
}
BYTE major, minor, revision, release;
GetDriverVersion(&major, &minor, &revision, &release);
TCHAR buffer[128];
_stprintf_s(buffer, 128, TEXT("\\\\.\\WinRing0_%d_%d_%d"),(int)major,(int)minor, (int)revision);
restrictDriverAccess(buffer);
return true;
}
#endif // NO_WINRING
#endif
#if defined(__FreeBSD__)
#define cpu_set_t cpuset_t
#endif
class TemporalThreadAffinity // speedup trick for Linux, FreeBSD, DragonFlyBSD, Windows
{
TemporalThreadAffinity(); // forbidden
#if defined(__FreeBSD__) || (defined(__DragonFly__) && __DragonFly_version >= 400707)
cpu_set_t old_affinity;
bool restore;
public:
TemporalThreadAffinity(uint32 core_id, bool checkStatus = true, const bool restore_ = true)
: restore(restore_)
{
assert(core_id < 1024);
auto res = pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity);
if (res != 0)
{
std::cerr << "ERROR: pthread_getaffinity_np for core " << core_id << " failed with code " << res << "\n";
throw std::exception();
}
cpu_set_t new_affinity;
CPU_ZERO(&new_affinity);
CPU_SET(core_id, &new_affinity);
// CPU_CMP() returns true if old_affinity is NOT equal to new_affinity
if (!(CPU_CMP(&old_affinity, &new_affinity)))
{
restore = false;
return; // the same affinity => return
}
res = pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &new_affinity);
if (res != 0 && checkStatus)
{
std::cerr << "ERROR: pthread_setaffinity_np for core " << core_id << " failed with code " << res << "\n";
throw std::exception();
}
}
~TemporalThreadAffinity()
{
if (restore) pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity);
}
bool supported() const { return true; }
#elif defined(__linux__)
cpu_set_t * old_affinity;
static constexpr auto maxCPUs = 8192;
const size_t set_size;
bool restore;
public:
TemporalThreadAffinity(const uint32 core_id, bool checkStatus = true, const bool restore_ = true)
: set_size(CPU_ALLOC_SIZE(maxCPUs)), restore(restore_)
{
assert(core_id < maxCPUs);
old_affinity = CPU_ALLOC(maxCPUs);
assert(old_affinity);
auto res = pthread_getaffinity_np(pthread_self(), set_size, old_affinity);
if (res != 0)
{
std::cerr << "ERROR: pthread_getaffinity_np for core " << core_id << " failed with code " << res << "\n";
throw std::exception();
}
cpu_set_t * new_affinity = CPU_ALLOC(maxCPUs);
assert(new_affinity);
CPU_ZERO_S(set_size, new_affinity);
CPU_SET_S(core_id, set_size, new_affinity);
if (CPU_EQUAL_S(set_size, old_affinity, new_affinity))
{
CPU_FREE(new_affinity);
restore = false;
return;
}
res = pthread_setaffinity_np(pthread_self(), set_size, new_affinity);
CPU_FREE(new_affinity);
if (res != 0 && checkStatus)
{
std::cerr << "ERROR: pthread_setaffinity_np for core " << core_id << " failed with code " << res << "\n";
throw std::exception();
}
}
~TemporalThreadAffinity()
{
if (restore) pthread_setaffinity_np(pthread_self(), set_size, old_affinity);
CPU_FREE(old_affinity);
}
bool supported() const { return true; }
#elif defined(_MSC_VER)
ThreadGroupTempAffinity affinity;
public:
TemporalThreadAffinity(uint32 core, bool checkStatus = true, const bool restore = true)
: affinity(core, checkStatus, restore)
{
}
bool supported() const { return true; }
#else // not implemented for os x
public:
TemporalThreadAffinity(uint32) { }
TemporalThreadAffinity(uint32, bool) {}
bool supported() const { return false; }
#endif
};
PCM * PCM::instance = NULL;
/*
static int bitCount(uint64 n)
{
int count = 0;
while (n)
{
count += static_cast<int>(n & 0x00000001);
n >>= static_cast<uint64>(1);
}
return count;
}
*/
std::mutex instanceCreationMutex;
PCM * PCM::getInstance()
{
// lock-free read
// cppcheck-suppress identicalConditionAfterEarlyExit
if (instance) return instance;
std::unique_lock<std::mutex> _(instanceCreationMutex);
// cppcheck-suppress identicalConditionAfterEarlyExit
if (instance) return instance;
return instance = new PCM();
}
uint64 PCM::extractCoreGenCounterValue(uint64 val)
{
if (canUsePerf) return val;
if(core_gen_counter_width)
return extract_bits(val, 0, core_gen_counter_width-1);
return val;
}
uint64 PCM::extractCoreFixedCounterValue(uint64 val)
{
if (canUsePerf) return val;
if(core_fixed_counter_width)
return extract_bits(val, 0, core_fixed_counter_width-1);
return val;
}
uint64 PCM::extractUncoreGenCounterValue(uint64 val)
{
if(uncore_gen_counter_width)
return extract_bits(val, 0, uncore_gen_counter_width-1);
return val;
}
uint64 PCM::extractUncoreFixedCounterValue(uint64 val)
{
if(uncore_fixed_counter_width)
return extract_bits(val, 0, uncore_fixed_counter_width-1);
return val;
}
uint64 PCM::extractQOSMonitoring(uint64 val)
{
//Check if any of the error bit(63) or Unavailable bit(62) of the IA32_QM_CTR MSR are 1
if(val & (3ULL<<62))
{
// invalid reading
return static_cast<uint64>(PCM_INVALID_QOS_MONITORING_DATA);
}
// valid reading
return extract_bits(val,0,61);
}
int32 extractThermalHeadroom(uint64 val)
{
if(val & (1ULL<<31ULL))
{ // valid reading
return static_cast<int32>(extract_bits(val, 16, 22));
}
// invalid reading
return static_cast<int32>(PCM_INVALID_THERMAL_HEADROOM);
}
uint64 get_frequency_from_cpuid();
#if defined(__FreeBSD__) || defined(__DragonFly__)
void pcm_cpuid_bsd(int leaf, PCM_CPUID_INFO& info, int core)
{
cpuctl_cpuid_args_t cpuid_args_freebsd;
char cpuctl_name[64];
snprintf(cpuctl_name, 64, "/dev/cpuctl%d", core);
auto fd = ::open(cpuctl_name, O_RDWR);
cpuid_args_freebsd.level = leaf;
::ioctl(fd, CPUCTL_CPUID, &cpuid_args_freebsd);
for (int i = 0; i < 4; ++i)
{
info.array[i] = cpuid_args_freebsd.data[i];
}
::close(fd);
}
#endif
/* Adding the new version of cpuid with leaf and subleaf as an input */
void pcm_cpuid(const unsigned leaf, const unsigned subleaf, PCM_CPUID_INFO & info)
{
#ifdef _MSC_VER
__cpuidex(info.array, leaf, subleaf);
#else
__asm__ __volatile__ ("cpuid" : \
"=a" (info.reg.eax), "=b" (info.reg.ebx), "=c" (info.reg.ecx), "=d" (info.reg.edx) : "a" (leaf), "c" (subleaf));
#endif
}
#ifdef __linux__
bool isNMIWatchdogEnabled(const bool silent);
bool keepNMIWatchdogEnabled();
#endif
void PCM::readCoreCounterConfig(const bool complainAboutMSR)
{
if (max_cpuid >= 0xa)
{
// get counter related info
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0xa, cpuinfo);
perfmon_version = extract_bits_ui(cpuinfo.array[0], 0, 7);
core_gen_counter_num_max = extract_bits_ui(cpuinfo.array[0], 8, 15);
core_gen_counter_width = extract_bits_ui(cpuinfo.array[0], 16, 23);
if (perfmon_version > 1)
{
core_fixed_counter_num_max = extract_bits_ui(cpuinfo.array[3], 0, 4);
core_fixed_counter_width = extract_bits_ui(cpuinfo.array[3], 5, 12);
}
else if (1 == perfmon_version)
{
core_fixed_counter_num_max = 3;
core_fixed_counter_width = core_gen_counter_width;
}
if (isForceRTMAbortModeAvailable())
{
uint64 TSXForceAbort = 0;
if (MSR.empty())
{
if (complainAboutMSR)
{
std::cerr << "PCM Error: Can't determine the number of available counters reliably because of no access to MSR.\n";
}
}
else if (MSR[0]->read(MSR_TSX_FORCE_ABORT, &TSXForceAbort) == sizeof(uint64))
{
TSXForceAbort &= 1;
/*
TSXForceAbort is 0 (default mode) => the number of useful gen counters is 3
TSXForceAbort is 1 => the number of gen counters is unchanged
*/
if (TSXForceAbort == 0)
{
core_gen_counter_num_max = 3;
}
}
else
{
std::cerr << "PCM Error: Can't determine the number of available counters reliably because reading MSR_TSX_FORCE_ABORT failed.\n";
}
}
#if defined(__linux__)
const auto env = std::getenv("PCM_NO_AWS_WORKAROUND");
auto aws_workaround = true;
if (env != nullptr && std::string(env) == std::string("1"))
{
aws_workaround = false;
}
if (aws_workaround == true && vm == true && linux_arch_perfmon == true && core_gen_counter_num_max > 3)
{
core_gen_counter_num_max = 3;
std::cerr << "INFO: Reducing the number of programmable counters to 3 to workaround the fixed cycle counter virtualization issue on AWS.\n";
std::cerr << " You can disable the workaround by setting PCM_NO_AWS_WORKAROUND=1 environment variable\n";
}
if (isNMIWatchdogEnabled(true) && keepNMIWatchdogEnabled())
{
--core_gen_counter_num_max;
std::cerr << "INFO: Reducing the number of programmable counters to " << core_gen_counter_num_max << " because NMI watchdog is enabled.\n";
}
#endif
}
}
bool PCM::isFixedCounterSupported(unsigned c)
{
if (max_cpuid >= 0xa)
{
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0xa, cpuinfo);
return extract_bits_ui(cpuinfo.reg.ecx, c, c) || (extract_bits_ui(cpuinfo.reg.edx, 4, 0) > c);
}
return false;
}
bool PCM::isHWTMAL1Supported() const
{
#ifdef PCM_USE_PERF
if (perfEventTaskHandle.empty() == false)
{
return false; // per PID/task perf collection does not support HW TMA L1
}
#endif
static int supported = -1;
if (supported < 0)
{
supported = 0;
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(1, cpuinfo);
if (extract_bits_ui(cpuinfo.reg.ecx, 15, 15) && MSR.size())
{
uint64 perf_cap;
if (MSR[0]->read(MSR_PERF_CAPABILITIES, &perf_cap) == sizeof(uint64))
{
supported = (int)extract_bits(perf_cap, 15, 15);
}
}
if (hybrid)
{
supported = 0;
}
}
return supported > 0;
}
void PCM::readCPUMicrocodeLevel()
{
if (MSR.empty()) return;
const int ref_core = 0;
TemporalThreadAffinity affinity(ref_core);
if (affinity.supported() && isCoreOnline(ref_core))
{ // see "Update Signature and Verification" and "Determining the Signature"
// sections in Intel SDM how to read ucode level
if (MSR[ref_core]->write(MSR_IA32_BIOS_SIGN_ID, 0) == sizeof(uint64))
{
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(1, cpuinfo); // cpuid instructions updates MSR_IA32_BIOS_SIGN_ID
uint64 result = 0;
if (MSR[ref_core]->read(MSR_IA32_BIOS_SIGN_ID, &result) == sizeof(uint64))
{
cpu_microcode_level = result >> 32;
}
}
}
}
int32 PCM::getMaxCustomCoreEvents()
{
return core_gen_counter_num_max;
}
int PCM::getCPUModelFromCPUID()
{
static int result = -1;
if (result < 0)
{
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(1, cpuinfo);
result = (((cpuinfo.array[0]) & 0xf0) >> 4) | ((cpuinfo.array[0] & 0xf0000) >> 12);
}
return result;
}
bool PCM::detectModel()
{
char buffer[1024];
union {
char cbuf[16];
int ibuf[16 / sizeof(int)];
} buf;
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0, cpuinfo);
std::fill(buffer, buffer + 1024, 0);
std::fill(buf.cbuf, buf.cbuf + 16, 0);
buf.ibuf[0] = cpuinfo.array[1];
buf.ibuf[1] = cpuinfo.array[3];
buf.ibuf[2] = cpuinfo.array[2];
if (strncmp(buf.cbuf, "GenuineIntel", 4 * 3) != 0)
{
std::cerr << getUnsupportedMessage() << "\n";
return false;
}
max_cpuid = cpuinfo.array[0];
pcm_cpuid(1, cpuinfo);
cpu_family = (((cpuinfo.array[0]) >> 8) & 0xf) | ((cpuinfo.array[0] & 0xf00000) >> 16);
cpu_model = (((cpuinfo.array[0]) & 0xf0) >> 4) | ((cpuinfo.array[0] & 0xf0000) >> 12);
cpu_stepping = cpuinfo.array[0] & 0x0f;
if (cpuinfo.reg.ecx & (1UL << 31UL)) {
vm = true;
std::cerr << "Detected a hypervisor/virtualization technology. Some metrics might not be available due to configuration or availability of virtual hardware features.\n";
}
readCoreCounterConfig();
if (cpu_family != 6)
{
std::cerr << getUnsupportedMessage() << " CPU Family: " << cpu_family << "\n";
return false;
}
pcm_cpuid(7, 0, cpuinfo);
std::cerr << "\n===== Processor information =====\n";
#ifdef __linux__
auto checkLinuxCpuinfoFlag = [](const std::string& flag) -> bool
{
std::ifstream linuxCpuinfo("/proc/cpuinfo");
if (linuxCpuinfo.is_open())
{
std::string line;
while (std::getline(linuxCpuinfo, line))
{
auto tokens = split(line, ':');
if (tokens.size() >= 2 && tokens[0].find("flags") == 0)
{
for (const auto & curFlag : split(tokens[1], ' '))
{
if (flag == curFlag)
{
return true;
}
}
}
}
linuxCpuinfo.close();
}
return false;
};
linux_arch_perfmon = checkLinuxCpuinfoFlag("arch_perfmon");
std::cerr << "Linux arch_perfmon flag : " << (linux_arch_perfmon ? "yes" : "no") << "\n";
if (vm == true && linux_arch_perfmon == false)
{
std::cerr << "ERROR: vPMU is not enabled in the hypervisor. Please see details in https://software.intel.com/content/www/us/en/develop/documentation/vtune-help/top/set-up-analysis-target/on-virtual-machine.html \n";
std::cerr << " you can force-continue by setting PCM_IGNORE_ARCH_PERFMON=1 environment variable.\n";
auto env = std::getenv("PCM_IGNORE_ARCH_PERFMON");
auto ignore_arch_perfmon = false;
if (env != nullptr && std::string(env) == std::string("1"))
{
ignore_arch_perfmon = true;
}
if (!ignore_arch_perfmon)
{
return false;
}
}
#endif
hybrid = (cpuinfo.reg.edx & (1 << 15)) ? true : false;
std::cerr << "Hybrid processor : " << (hybrid ? "yes" : "no") << "\n";
std::cerr << "IBRS and IBPB supported : " << ((cpuinfo.reg.edx & (1 << 26)) ? "yes" : "no") << "\n";
std::cerr << "STIBP supported : " << ((cpuinfo.reg.edx & (1 << 27)) ? "yes" : "no") << "\n";
std::cerr << "Spec arch caps supported : " << ((cpuinfo.reg.edx & (1 << 29)) ? "yes" : "no") << "\n";
std::cerr << "Max CPUID level : " << max_cpuid << "\n";
std::cerr << "CPU model number : " << cpu_model << "\n";
return true;
}
bool PCM::isRDTDisabled() const
{
static int flag = -1;
if (flag < 0)
{
// flag not yet initialized
const char * varname = "PCM_NO_RDT";
char* env = nullptr;
#ifdef _MSC_VER
_dupenv_s(&env, NULL, varname);
#else
env = std::getenv(varname);
#endif
if (env != nullptr && std::string(env) == std::string("1"))
{
std::cout << "Disabling RDT usage because PCM_NO_RDT=1 environment variable is set.\n";
flag = 1;
}
else
{
flag = 0;
}
#ifdef _MSC_VER
free(env);
#endif
}
return flag > 0;
}
bool PCM::QOSMetricAvailable() const
{
if (isRDTDisabled()) return false;
#ifndef __linux__
if (isSecureBoot()) return false;
#endif
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0x7,0,cpuinfo);
return (cpuinfo.reg.ebx & (1<<12))?true:false;
}
bool PCM::L3QOSMetricAvailable() const
{
if (isRDTDisabled()) return false;
#ifndef __linux__
if (isSecureBoot()) return false;
#endif
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0xf,0,cpuinfo);
return (cpuinfo.reg.edx & (1<<1))?true:false;
}
bool PCM::L3CacheOccupancyMetricAvailable() const
{
PCM_CPUID_INFO cpuinfo;
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return false;
pcm_cpuid(0xf,0x1,cpuinfo);
return (cpuinfo.reg.edx & 1)?true:false;
}
bool PCM::CoreLocalMemoryBWMetricAvailable() const
{
if (cpu_model == SKX && cpu_stepping < 5) return false; // SKZ4 errata
PCM_CPUID_INFO cpuinfo;
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return false;
pcm_cpuid(0xf,0x1,cpuinfo);
return (cpuinfo.reg.edx & 2)?true:false;
}
bool PCM::CoreRemoteMemoryBWMetricAvailable() const
{
if (cpu_model == SKX && cpu_stepping < 5) return false; // SKZ4 errata
PCM_CPUID_INFO cpuinfo;
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return false;
pcm_cpuid(0xf, 0x1, cpuinfo);
return (cpuinfo.reg.edx & 4) ? true : false;
}
unsigned PCM::getMaxRMID() const
{
unsigned maxRMID = 0;
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0xf,0,cpuinfo);
maxRMID = (unsigned)cpuinfo.reg.ebx + 1;
return maxRMID;
}
void PCM::initRDT()
{
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return;
#ifdef __linux__
auto env = std::getenv("PCM_USE_RESCTRL");
if (env != nullptr && std::string(env) == std::string("1"))
{
std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because environment variable PCM_USE_RESCTRL=1\n";
resctrl.init();
useResctrl = true;
return;
}
if (resctrl.isMounted())
{
std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because resctrl driver is mounted.\n";
resctrl.init();
useResctrl = true;
return;
}
if (isSecureBoot())
{
std::cerr << "INFO: using Linux resctrl driver for RDT metrics (L3OCC, LMB, RMB) because Secure Boot mode is enabled.\n";
resctrl.init();
useResctrl = true;
return;
}
#endif
std::cerr << "Initializing RMIDs" << std::endl;
unsigned maxRMID;
/* Calculate maximum number of RMID supported by socket */
maxRMID = getMaxRMID();
// std::cout << "Maximum RMIDs per socket in the system : " << maxRMID << "\n";
std::vector<uint32> rmid(num_sockets);
for(int32 i = 0; i < num_sockets; i ++)
rmid[i] = maxRMID - 1;
/* Associate each core with 1 RMID */
for(int32 core = 0; core < num_cores; core ++ )
{
if(!isCoreOnline(core)) continue;
uint64 msr_pqr_assoc = 0 ;
uint64 msr_qm_evtsel = 0 ;
MSR[core]->lock();
//Read 0xC8F MSR for each core
MSR[core]->read(IA32_PQR_ASSOC, &msr_pqr_assoc);
//std::cout << "initRMID reading IA32_PQR_ASSOC 0x" << std::hex << msr_pqr_assoc << std::dec << "\n";
//std::cout << "Socket Id : " << topology[core].socket;
msr_pqr_assoc &= 0xffffffff00000000ULL;
msr_pqr_assoc |= (uint64)(rmid[topology[core].socket] & ((1ULL<<10)-1ULL));
//std::cout << "initRMID writing IA32_PQR_ASSOC 0x" << std::hex << msr_pqr_assoc << std::dec << "\n";
//Write 0xC8F MSR with new RMID for each core
MSR[core]->write(IA32_PQR_ASSOC,msr_pqr_assoc);
msr_qm_evtsel = static_cast<uint64>(rmid[topology[core].socket] & ((1ULL<<10)-1ULL));
msr_qm_evtsel <<= 32;
//Write 0xC8D MSR with new RMID for each core
//std::cout << "initRMID writing IA32_QM_EVTSEL 0x" << std::hex << msr_qm_evtsel << std::dec << "\n";
MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel);
MSR[core]->unlock();
/* Initializing the memory bandwidth counters */
if (CoreLocalMemoryBWMetricAvailable())
{
memory_bw_local.push_back(std::make_shared<CounterWidthExtender>(new CounterWidthExtender::MBLCounter(MSR[core]), 24, 1000));
if (CoreRemoteMemoryBWMetricAvailable())
{
memory_bw_total.push_back(std::make_shared<CounterWidthExtender>(new CounterWidthExtender::MBTCounter(MSR[core]), 24, 1000));
}
}
rmid[topology[core].socket] --;
//std::cout << std::flush; // Explicitly flush after each iteration
}
/* Get The scaling factor by running CPUID.0xF.0x1 instruction */
L3ScalingFactor = getL3ScalingFactor();
}
void PCM::initQOSevent(const uint64 event, const int32 core)
{
if(!isCoreOnline(core)) return;
uint64 msr_qm_evtsel = 0 ;
//Write 0xC8D MSR with the event id
MSR[core]->read(IA32_QM_EVTSEL, &msr_qm_evtsel);
//std::cout << "initQOSevent reading IA32_QM_EVTSEL 0x" << std::hex << msr_qm_evtsel << std::dec << "\n";
msr_qm_evtsel &= 0xfffffffffffffff0ULL;
msr_qm_evtsel |= event & ((1ULL<<8)-1ULL);
//std::cout << "initQOSevent writing IA32_QM_EVTSEL 0x" << std::hex << msr_qm_evtsel << std::dec << "\n";
MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel);
//std::cout << std::flush;
}
void PCM::initCStateSupportTables()
{
#define PCM_PARAM_PROTECT(...) __VA_ARGS__
#define PCM_CSTATE_ARRAY(array_ , val ) \
{ \
static uint64 tmp[] = val; \
PCM_COMPILE_ASSERT(sizeof(tmp) / sizeof(uint64) == (static_cast<int>(MAX_C_STATE)+1)); \
array_ = tmp; \
break; \
}
// fill package C state array
switch(cpu_model)
{
case ATOM:
case ATOM_2:
case CENTERTON:
case AVOTON:
case BAYTRAIL:
case CHERRYTRAIL:
case APOLLO_LAKE:
case GEMINI_LAKE:
case DENVERTON:
case ADL:
case RPL:
case SNOWRIDGE:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x3F8, 0, 0x3F9, 0, 0x3FA, 0, 0, 0, 0 }) );
case NEHALEM_EP:
case NEHALEM:
case CLARKDALE:
case WESTMERE_EP:
case NEHALEM_EX:
case WESTMERE_EX:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) );
case SANDY_BRIDGE:
case JAKETOWN:
case IVY_BRIDGE:
case IVYTOWN:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) );
case HASWELL:
case HASWELL_2:
case HASWELLX:
case BDX_DE:
case BDX:
case KNL:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) );
case SKX:
case ICX:
case SPR:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0, 0, 0, 0x3F9, 0, 0, 0, 0}) );
case HASWELL_ULT:
case BROADWELL:
PCM_SKL_PATH_CASES
case BROADWELL_XEON_E3:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0x630, 0x631, 0x632}) );
default:
std::cerr << "PCM error: package C-states support array is not initialized. Package C-states metrics will not be shown.\n";
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) );
};
// fill core C state array
switch(cpu_model)
{
case ATOM:
case ATOM_2:
case CENTERTON:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) );
case NEHALEM_EP:
case NEHALEM:
case CLARKDALE:
case WESTMERE_EP:
case NEHALEM_EX:
case WESTMERE_EX:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3FC, 0, 0, 0x3FD, 0, 0, 0, 0}) );
case SANDY_BRIDGE:
case JAKETOWN:
case IVY_BRIDGE:
case IVYTOWN:
case HASWELL:
case HASWELL_2:
case HASWELL_ULT:
case HASWELLX:
case BDX_DE:
case BDX:
case BROADWELL:
case BROADWELL_XEON_E3:
case BAYTRAIL:
case AVOTON:
case CHERRYTRAIL:
case APOLLO_LAKE:
case GEMINI_LAKE:
case DENVERTON:
PCM_SKL_PATH_CASES
case ADL:
case RPL:
case SNOWRIDGE:
case ICX:
case SPR:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3FC, 0, 0, 0x3FD, 0x3FE, 0, 0, 0}) );
case KNL:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0, 0, 0, 0x3FF, 0, 0, 0, 0}) );
case SKX:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0, 0, 0, 0x3FD, 0, 0, 0, 0}) );
default:
std::cerr << "PCM error: core C-states support array is not initialized. Core C-states metrics will not be shown.\n";
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) );
};
}
#ifdef __linux__
constexpr auto perfSlotsPath = "/sys/bus/event_source/devices/cpu/events/slots";
constexpr auto perfBadSpecPath = "/sys/bus/event_source/devices/cpu/events/topdown-bad-spec";
constexpr auto perfBackEndPath = "/sys/bus/event_source/devices/cpu/events/topdown-be-bound";
constexpr auto perfFrontEndPath = "/sys/bus/event_source/devices/cpu/events/topdown-fe-bound";
constexpr auto perfRetiringPath = "/sys/bus/event_source/devices/cpu/events/topdown-retiring";
bool perfSupportsTopDown()
{
static int yes = -1;
if (-1 == yes)
{
const auto slots = readSysFS(perfSlotsPath, true);
const auto bad = readSysFS(perfBadSpecPath, true);
const auto be = readSysFS(perfBackEndPath, true);
const auto fe = readSysFS(perfFrontEndPath, true);
const auto ret = readSysFS(perfRetiringPath, true);
yes = (slots.size() && bad.size() && be.size() && fe.size() && ret.size()) ? 1 : 0;
}
return 1 == yes;
}
#endif
const std::vector<std::string> qat_evtsel_mapping =
{
{ "sample_cnt" }, //0x0
{ "pci_trans_cnt" }, //0x1
{ "max_rd_lat" }, //0x2
{ "rd_lat_acc_avg" }, //0x3
{ "max_lat" }, //0x4
{ "lat_acc_avg" }, //0x5
{ "bw_in" }, //0x6
{ "bw_out" }, //0x7
{ "at_page_req_lat_acc_avg" }, //0x8
{ "at_trans_lat_acc_avg" }, //0x9
{ "at_max_tlb_used" }, //0xA
{ "util_cpr0" }, //0xB
{ "util_dcpr0" }, //0xC
{ "util_dcpr1" }, //0xD
{ "util_dcpr2" }, //0xE
{ "util_xlt0" }, //0xF
{ "util_xlt1" }, //0x10
{ "util_cph0" }, //0x11
{ "util_cph1" }, //0x12
{ "util_cph2" }, //0x13
{ "util_cph3" }, //0x14
{ "util_cph4" }, //0x15
{ "util_cph5" }, //0x16
{ "util_cph6" }, //0x17
{ "util_cph7" }, //0x18
{ "util_ath0" }, //0x19
{ "util_ath1" }, //0x1A
{ "util_ath2" }, //0x1B
{ "util_ath3" }, //0x1C
{ "util_ath4" }, //0x1D
{ "util_ath5" }, //0x1E
{ "util_ath6" }, //0x1F
{ "util_ath7" }, //0x20
{ "util_ucs0" }, //0x21
{ "util_ucs1" }, //0x22
{ "util_ucs2" }, //0x23
{ "util_ucs3" }, //0x24
{ "util_pke0" }, //0x25
{ "util_pke1" }, //0x26
{ "util_pke2" }, //0x27
{ "util_pke3" }, //0x28
{ "util_pke4" }, //0x29
{ "util_pke5" }, //0x2A
{ "util_pke6" }, //0x2B
{ "util_pke7" }, //0x2C
{ "util_pke8" }, //0x2D
{ "util_pke9" }, //0x2E
{ "util_pke10" }, //0x2F
{ "util_pke11" }, //0x30
{ "util_pke12" }, //0x31
{ "util_pke13" }, //0x32
{ "util_pke14" }, //0x33
{ "util_pke15" }, //0x34
{ "util_pke16" }, //0x35
{ "util_pke17" }, //0x36
{ "unknown" } //0x37
};
class VirtualDummyRegister : public HWRegister
{
uint64 lastValue;
public:
VirtualDummyRegister() : lastValue(0) {}
void operator = (uint64 val) override
{
lastValue = val;
}
operator uint64 () override
{
return lastValue;
}
};
class QATTelemetryVirtualGeneralConfigRegister : public HWRegister
{
friend class QATTelemetryVirtualCounterRegister;
int domain, b, d, f;
PCM::IDX_OPERATION operation;
PCM::IDX_STATE state;
std::unordered_map<std::string, uint32> data_cache; //data cache
public:
QATTelemetryVirtualGeneralConfigRegister(int domain_, int b_, int d_, int f_) :
domain(domain_),
b(b_),