-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpucounters.cpp
5532 lines (4862 loc) · 199 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
/*
Copyright (c) 2009-2017, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// 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 "PCM-Lib_Win\pcm-lib.h"
#else
#include "cpucounters.h"
#endif
#include "msr.h"
#include "pci.h"
#include "types.h"
#include "utils.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 "PCM_Win/windriver.h"
#else
#include <pthread.h>
#if defined(__FreeBSD__) || (defined(__DragonFly__) && __DragonFly_version >= 400707)
#include <pthread_np.h>
#endif
#include <errno.h>
#include <sys/time.h>
#ifdef __linux__
#include <sys/mman.h>
#endif
#endif
#include <string.h>
#include <limits>
#include <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>
// convertUnknownToInt is used in the safe sysctl call to convert an unkown size to an int
int convertUnknownToInt(size_t size, char* value);
#endif
#undef PCM_UNCORE_PMON_BOX_CHECK_STATUS // debug only
#undef PCM_DEBUG_TOPOLOGY // debug of topoogy enumeration routine
// FreeBSD is much more restrictive about names for semaphores
#if defined (__FreeBSD__)
#define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "/PCM_inst_lock"
#define PCM_NUM_INSTANCES_SEMAPHORE_NAME "/num_PCM_inst"
#else
#define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "PCM inst lock"
#define PCM_NUM_INSTANCES_SEMAPHORE_NAME "Num PCM insts"
#endif
#ifdef _MSC_VER
HMODULE hOpenLibSys = NULL;
bool PCM::initWinRing0Lib()
{
const BOOL result = InitOpenLibSys(&hOpenLibSys);
if (result == FALSE)
{
hOpenLibSys = NULL;
return false;
}
BYTE major, minor, revision, release;
GetDriverVersion(&major, &minor, &revision, &release);
wchar_t buffer[128];
swprintf_s(buffer, 128, _T("\\\\.\\WinRing0_%d_%d_%d"),(int)major,(int)minor, (int)revision);
restrictDriverAccess(buffer);
return true;
}
class InstanceLock
{
HANDLE Mutex;
InstanceLock();
public:
InstanceLock(const bool global)
{
Mutex = CreateMutex(NULL, FALSE,
global?(L"Global\\Processor Counter Monitor instance create/destroy lock"):(L"Local\\Processor Counter Monitor instance create/destroy lock"));
// lock
WaitForSingleObject(Mutex, INFINITE);
}
~InstanceLock()
{
// unlock
ReleaseMutex(Mutex);
CloseHandle(Mutex);
}
};
#else // Linux or Apple
pthread_mutex_t processIntanceMutex = PTHREAD_MUTEX_INITIALIZER;
class InstanceLock
{
const char * globalSemaphoreName;
sem_t * globalSemaphore;
bool global;
InstanceLock();
public:
InstanceLock(const bool global_) : globalSemaphoreName(PCM_INSTANCE_LOCK_SEMAPHORE_NAME), globalSemaphore(NULL), global(global_)
{
if(!global)
{
pthread_mutex_lock(&processIntanceMutex);
return;
}
umask(0);
while (1)
{
//sem_unlink(globalSemaphoreName); // temporary
globalSemaphore = sem_open(globalSemaphoreName, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1);
if (SEM_FAILED == globalSemaphore)
{
if (EACCES == errno)
{
std::cerr << "PCM Error, do not have permissions to open semaphores in /dev/shm/. Waiting one second and retrying..." << std::endl;
sleep(1);
}
}
else
{
/*
if (sem_post(globalSemaphore)) {
perror("sem_post error");
}
*/
break; // success
}
}
if (sem_wait(globalSemaphore)) {
perror("sem_wait error");
}
}
~InstanceLock()
{
if(!global)
{
pthread_mutex_unlock(&processIntanceMutex);
return;
}
if (sem_post(globalSemaphore)) {
perror("sem_post error");
}
}
};
#endif // end of _MSC_VER else
#if defined(__FreeBSD__)
#define cpu_set_t cpuset_t
#endif
class TemporalThreadAffinity // speedup trick for Linux, FreeBSD, DragonFlyBSD
{
#if defined(__linux__) || defined(__FreeBSD__) || (defined(__DragonFly__) && __DragonFly_version >= 400707)
cpu_set_t old_affinity;
TemporalThreadAffinity(); // forbiden
public:
TemporalThreadAffinity(uint32 core_id)
{
pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity);
cpu_set_t new_affinity;
CPU_ZERO(&new_affinity);
CPU_SET(core_id, &new_affinity);
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &new_affinity);
}
~TemporalThreadAffinity()
{
pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &old_affinity);
}
#else // not implemented for windows or os x
TemporalThreadAffinity(); // forbiden
public:
TemporalThreadAffinity(uint32) { }
#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;
}
*/
PCM * PCM::getInstance()
{
// no lock here
if (instance) return instance;
InstanceLock lock(false);
if (instance) return instance;
return instance = new PCM();
}
uint32 build_bit_ui(uint32 beg, uint32 end)
{
uint32 myll = 0;
if (end == 31)
{
myll = (uint32)(-1);
}
else
{
myll = (1 << (end + 1)) - 1;
}
myll = myll >> beg;
return myll;
}
uint32 extract_bits_ui(uint32 myin, uint32 beg, uint32 end)
{
uint32 myll = 0;
uint32 beg1, end1;
// Let the user reverse the order of beg & end.
if (beg <= end)
{
beg1 = beg;
end1 = end;
}
else
{
beg1 = end;
end1 = beg;
}
myll = myin >> beg1;
myll = myll & build_bit_ui(beg1, end1);
return myll;
}
uint64 build_bit(uint32 beg, uint32 end)
{
uint64 myll = 0;
if (end == 63)
{
myll = static_cast<uint64>(-1);
}
else
{
myll = (1LL << (end + 1)) - 1;
}
myll = myll >> beg;
return myll;
}
uint64 extract_bits(uint64 myin, uint32 beg, uint32 end)
{
uint64 myll = 0;
uint32 beg1, end1;
// Let the user reverse the order of beg & end.
if (beg <= end)
{
beg1 = beg;
end1 = end;
}
else
{
beg1 = end;
end1 = beg;
}
myll = myin >> beg1;
myll = myll & build_bit(beg1, end1);
return myll;
}
uint64 PCM::extractCoreGenCounterValue(uint64 val)
{
if(core_gen_counter_width)
return extract_bits(val, 0, core_gen_counter_width-1);
return val;
}
uint64 PCM::extractCoreFixedCounterValue(uint64 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();
union PCM_CPUID_INFO
{
int array[4];
struct { unsigned int eax, ebx, ecx, edx; } reg;
};
void pcm_cpuid(int leaf, PCM_CPUID_INFO & info)
{
#ifdef _MSC_VER
// version for Windows
__cpuid(info.array, leaf);
#else
__asm__ __volatile__ ("cpuid" : \
"=a" (info.reg.eax), "=b" (info.reg.ebx), "=c" (info.reg.ecx), "=d" (info.reg.edx) : "a" (leaf));
#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
}
bool PCM::detectModel()
{
char buffer[1024];
union {
char cbuf[16];
int ibuf[16/sizeof(int)];
} buf;
PCM_CPUID_INFO cpuinfo;
int max_cpuid;
pcm_cpuid(0, cpuinfo);
memset(buffer, 0, 1024);
memset(buf.cbuf, 0, 16);
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() << std::endl;
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 = original_cpu_model = (((cpuinfo.array[0]) & 0xf0) >> 4) | ((cpuinfo.array[0] & 0xf0000) >> 12);
cpu_stepping = cpuinfo.array[0] & 0x0f;
if (cpuinfo.reg.ecx & (1UL<<31UL)) {
std::cerr << "Detected a hypervisor/virtualization technology. Some metrics might not be available due to configuration or availability of virtual hardware features." << std::endl;
}
if (max_cpuid >= 0xa)
{
// get counter related info
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);
}
}
if (cpu_family != 6)
{
std::cerr << getUnsupportedMessage() << " CPU Family: " << cpu_family << std::endl;
return false;
}
return true;
}
bool PCM::QOSMetricAvailable()
{
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0x7,0,cpuinfo);
return (cpuinfo.reg.ebx & (1<<12))?true:false;
}
bool PCM::L3QOSMetricAvailable()
{
PCM_CPUID_INFO cpuinfo;
pcm_cpuid(0xf,0,cpuinfo);
return (cpuinfo.reg.edx & (1<<1))?true:false;
}
bool PCM::L3CacheOccupancyMetricAvailable()
{
PCM_CPUID_INFO cpuinfo;
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return false;
pcm_cpuid(0xf,0x1,cpuinfo);
return (cpuinfo.reg.edx & 1)?true:false;
}
bool PCM::CoreLocalMemoryBWMetricAvailable()
{
if (cpu_model == SKX) 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()
{
if (cpu_model == SKX) 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::initRMID()
{
if (!(QOSMetricAvailable() && L3QOSMetricAvailable()))
return;
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 << std::endl;
//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 << std::endl;
//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 << std::endl;
MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel);
MSR[core]->unlock();
/* Initializing the memory bandwidth counters */
memory_bw_local.push_back(std::shared_ptr<CounterWidthExtender>(new CounterWidthExtender(new CounterWidthExtender::MBLCounter(MSR[core]), 24, 500)));
memory_bw_total.push_back(std::shared_ptr<CounterWidthExtender>(new CounterWidthExtender(new CounterWidthExtender::MBTCounter(MSR[core]), 24, 500)));
rmid[topology[core].socket] --;
}
/* 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 << std::endl;
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 << std::endl;
MSR[core]->write(IA32_QM_EVTSEL,msr_qm_evtsel);
}
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(original_cpu_model)
{
case ATOM:
case ATOM_2:
case ATOM_CENTERTON:
case ATOM_AVOTON:
case ATOM_BAYTRAIL:
case ATOM_CHERRYTRAIL:
case ATOM_APOLLO_LAKE:
case ATOM_DENVERTON:
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:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0, 0, 0, 0x3F9, 0, 0, 0, 0}) );
case HASWELL_ULT:
case BROADWELL:
case SKL:
case SKL_UY:
case KBL:
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." << std::endl;
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) );
};
// fill core C state array
switch(original_cpu_model)
{
case ATOM:
case ATOM_2:
case ATOM_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 ATOM_BAYTRAIL:
case ATOM_AVOTON:
case ATOM_CHERRYTRAIL:
case ATOM_APOLLO_LAKE:
case ATOM_DENVERTON:
case SKL_UY:
case SKL:
case KBL:
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." << std::endl;
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }) );
};
}
#ifdef __linux__
std::string readSysFS(const char * path)
{
FILE * f = fopen(path, "r");
if (!f)
{
std::cerr << "Can not open "<< path <<" file." << std::endl;
return std::string();
}
char buffer[1024];
if(NULL == fgets(buffer, 1024, f))
{
std::cerr << "Can not read "<< path << "." << std::endl;
return std::string();
}
fclose(f);
return std::string(buffer);
}
int readMaxFromSysFS(const char * path)
{
std::string content = readSysFS(path);
const char * buffer = content.c_str();
int result = -1;
pcm_sscanf(buffer) >> s_expect("0-") >> result;
if(result == -1)
{
pcm_sscanf(buffer) >> result;
}
return result;
}
#endif
bool PCM::discoverSystemTopology()
{
typedef std::map<uint32, uint32> socketIdMap_type;
socketIdMap_type socketIdMap;
PCM_CPUID_INFO cpuid_args;
pcm_cpuid(1, cpuid_args);
int apic_ids_per_package = (cpuid_args.array[1] & 0x00FF0000) >> 16, apic_ids_per_core;
if (apic_ids_per_package == 0)
{
std::cout << "apic_ids_per_package == 0" << std::endl;
return false;
}
pcm_cpuid(0xb, 0x0, cpuid_args);
if ((cpuid_args.array[2] & 0xFF00) == 0x100)
apic_ids_per_core = cpuid_args.array[1] & 0xFFFF;
else
apic_ids_per_core = 1;
if (apic_ids_per_core == 0)
{
std::cout << "apic_ids_per_core == 0" << std::endl;
return false;
}
// init constants for CPU topology leaf 0xB
// adapted from Topology Enumeration Reference code for Intel 64 Architecture
// https://software.intel.com/en-us/articles/intel-64-architecture-processor-topology-enumeration
int wasCoreReported = 0, wasThreadReported = 0;
int subleaf = 0, levelType, levelShift;
unsigned long coreplusSMT_Mask = 0L;
uint32 coreSelectMask = 0, smtSelectMask = 0, smtMaskWidth = 0;
uint32 l2CacheMaskShift = 0, l2CacheMaskWidth;
uint32 pkgSelectMask = (-1), pkgSelectMaskShift = 0;
unsigned long mask;
do
{
pcm_cpuid(0xb, subleaf, cpuid_args);
if (cpuid_args.array[1] == 0)
{ // if EBX ==0 then this subleaf is not valid, we can exit the loop
break;
}
mask = (1<<(16)) - 1;
levelType = (cpuid_args.array[2] & mask) >> 8;
mask = (1<<(5)) - 1;
levelShift = (cpuid_args.array[0] & mask);
switch (levelType)
{
case 1: //level type is SMT, so levelShift is the SMT_Mask_Width
smtSelectMask = ~((-1) << levelShift);
smtMaskWidth = levelShift;
wasThreadReported = 1;
break;
case 2: //level type is Core, so levelShift is the CorePlsuSMT_Mask_Width
coreplusSMT_Mask = ~((-1) << levelShift);
pkgSelectMaskShift = levelShift;
pkgSelectMask = (-1) ^ coreplusSMT_Mask;
wasCoreReported = 1;
break;
default:
break;
}
subleaf++;
} while (1);
if(wasThreadReported && wasCoreReported)
{
coreSelectMask = coreplusSMT_Mask ^ smtSelectMask;
}
else if (!wasCoreReported && wasThreadReported)
{
pkgSelectMaskShift = smtMaskWidth;
pkgSelectMask = (-1) ^ smtSelectMask;
}
else
{
std::cerr << "ERROR: this should not happen if hardware function normally" << std::endl;
return false;
}
pcm_cpuid(0x4, 2, cpuid_args); // get ID for L2 cache
mask = ((1<<(12)) - 1) << (14); // mask with bits 25:14 set to 1
l2CacheMaskWidth = 1 + ((cpuid_args.array[0] & mask) >> 14); // number of APIC IDs sharing L2 cache
for( ; l2CacheMaskWidth > 1; l2CacheMaskWidth >>= 1)
{
l2CacheMaskShift++;
}
#ifdef PCM_DEBUG_TOPOLOGY
std::cerr << "DEBUG: Number of threads sharing L2 cache = " << l2CacheMaskWidth
<< " [the most significant bit = " << l2CacheMaskShift << "]" << std::endl;
#endif
#ifdef _MSC_VER
// version for Windows 7 and later version
char * slpi = new char[sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)];
DWORD len = (DWORD)sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX);
BOOL res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len);
while (res == FALSE)
{
delete[] slpi;
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
slpi = new char[len];
res = GetLogicalProcessorInformationEx(RelationAll, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi, &len);
}
else
{
std::wcerr << "Error in Windows function 'GetLogicalProcessorInformationEx': " <<
GetLastError() << " ";
const TCHAR * strError = _com_error(GetLastError()).ErrorMessage();
if (strError) std::wcerr << strError;
std::wcerr << std::endl;
return false;
}
}
char * base_slpi = slpi;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pi = NULL;
for ( ; slpi < base_slpi + len; slpi += (DWORD)pi->Size)
{
pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi;
if (pi->Relationship == RelationProcessorCore)
{
threads_per_core = (pi->Processor.Flags == LTP_PC_SMT) ? 2 : 1;
// std::cout << "thr per core: "<< threads_per_core << std::endl;
num_cores += threads_per_core;
}
}
if (num_cores != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS))
{
std::cerr << "Error in processor group size counting: " << num_cores << "!=" << GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) << std::endl;
std::cerr << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration." << std::endl;
return false;
}
for (int i = 0; i < (int)num_cores; i++)
{
ThreadGroupTempAffinity affinity(i);
pcm_cpuid(0xb, 0x0, cpuid_args);
int apic_id = cpuid_args.array[3];
TopologyEntry entry;
entry.os_id = i;
entry.socket = apic_id / apic_ids_per_package;
entry.core_id = (apic_id % apic_ids_per_package) / apic_ids_per_core;
topology.push_back(entry);
socketIdMap[entry.socket] = 0;
}
delete[] base_slpi;
#else
// for Linux, Mac OS, FreeBSD and DragonFlyBSD
TopologyEntry entry;
#ifdef __linux__
num_cores = readMaxFromSysFS("/sys/devices/system/cpu/present");
if(num_cores == -1)
{
std::cerr << "Can not read number of present cores" << std::endl;
return false;
}
++num_cores;
// open /proc/cpuinfo
FILE * f_cpuinfo = fopen("/proc/cpuinfo", "r");
if (!f_cpuinfo)
{
std::cerr << "Can not open /proc/cpuinfo file." << std::endl;
return false;
}
// map with key=pkg_apic_id (not necessarily zero based or sequential) and
// associated value=socket_id that should be 0 based and sequential
std::map<int, int> found_pkg_ids;
topology.resize(num_cores);
char buffer[1024];
while (0 != fgets(buffer, 1024, f_cpuinfo))
{
if (strncmp(buffer, "processor", sizeof("processor") - 1) == 0)
{
pcm_sscanf(buffer) >> s_expect("processor\t: ") >> entry.os_id;
//std::cout << "os_core_id: "<<entry.os_id<< std::endl;
TemporalThreadAffinity _(entry.os_id);
pcm_cpuid(0xb, 0x0, cpuid_args);
int apic_id = cpuid_args.array[3];
entry.thread_id = (apic_id & smtSelectMask);
entry.core_id = (apic_id & coreSelectMask) >> smtMaskWidth;
entry.socket = (apic_id & pkgSelectMask) >> pkgSelectMaskShift;
entry.tile_id = (apic_id >> l2CacheMaskShift);
topology[entry.os_id] = entry;
socketIdMap[entry.socket] = 0;
++num_online_cores;
}
}
fclose(f_cpuinfo);
// produce debug output similar to Intel MPI cpuinfo
#ifdef PCM_DEBUG_TOPOLOGY
std::cerr << "===== Processor identification =====" << std::endl;
std::cerr << "Processor Thread Id. Core Id. Tile Id. Package Id." << std::endl;
std::map<uint32, std::vector<uint32> > os_id_by_core, os_id_by_tile, core_id_by_socket;
for(auto it = topology.begin(); it != topology.end(); ++it)
{
std::cerr << std::left << std::setfill(' ') << std::setw(16) << it->os_id
<< std::setw(16) << it->thread_id
<< std::setw(16) << it->core_id
<< std::setw(16) << it->tile_id
<< std::setw(16) << it->socket
<< std::endl << std::flush;
if(std::find(core_id_by_socket[it->socket].begin(), core_id_by_socket[it->socket].end(), it->core_id)
== core_id_by_socket[it->socket].end())
core_id_by_socket[it->socket].push_back(it->core_id);
// add socket offset to distinguish cores and tiles from different sockets
os_id_by_core[(it->socket << 15) + it->core_id].push_back(it->os_id);
os_id_by_tile[(it->socket << 15) + it->tile_id].push_back(it->os_id);
}
std::cerr << "===== Placement on packages =====" << std::endl;
std::cerr << "Package Id. Core Id. Processors" << std::endl;
for(auto pkg = core_id_by_socket.begin(); pkg != core_id_by_socket.end(); ++pkg)
{
auto core_id = pkg->second.begin();
std::cerr << std::left << std::setfill(' ') << std::setw(15) << pkg->first << *core_id;
for(++core_id; core_id != pkg->second.end(); ++core_id)
{
std::cerr << "," << *core_id;
}
std::cerr << std::endl;
}
std::cerr << std::endl << "===== Core/Tile sharing =====" << std::endl;
std::cerr << "Level Processors" << std::endl << "Core ";
for(auto core = os_id_by_core.begin(); core != os_id_by_core.end(); ++core)
{
auto os_id = core->second.begin();
std::cerr << "(" << *os_id;
for(++os_id; os_id != core->second.end(); ++os_id) {
std::cerr << "," << *os_id;
}
std::cerr << ")";
}
std::cerr << std::endl << "Tile / L2$ ";
for(auto core = os_id_by_tile.begin(); core != os_id_by_tile.end(); ++core)
{
auto os_id = core->second.begin();
std::cerr << "(" << *os_id;
for(++os_id; os_id != core->second.end(); ++os_id) {
std::cerr << "," << *os_id;
}
std::cerr << ")";
}
std::cerr << std::endl;
#endif // PCM_DEBUG_TOPOLOGY
#elif defined(__FreeBSD__) || defined(__DragonFly__)
size_t size = sizeof(num_cores);
cpuctl_cpuid_args_t cpuid_args_freebsd;
int fd;