-
Notifications
You must be signed in to change notification settings - Fork 1
/
cpucounters.cpp
3626 lines (3124 loc) · 126 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-2013, 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)
//#define PCM_TEST_FALLBACK_TO_ATOM
#include <assert.h>
#include <stdarg.h>
#include <stdio.h>
#ifdef INTELPCM_EXPORTS
// Intelpcm.h includes cpucounters.h
#include "Intelpcm.dll\Intelpcm.h"
#else
#include "cpucounters.h"
#endif
#include "msr.h"
#include "pci.h"
#include "types.h"
#include "utils.h"
#ifdef _MSC_VER
#include <intrin.h>
#include <windows.h>
#include <tchar.h>
#include "winring0/OlsApiInit.h"
#else
#include <pthread.h>
#include <errno.h>
#include <sys/time.h>
#endif
#include <string.h>
#include <limits>
#include <map>
#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
#if defined (__FreeBSD__)
#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
// FreeBSD is much more restrictive about names for semaphores
#if defined (__FreeBSD__)
#define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "/Intel_PCM_inst_lock"
#define PCM_NUM_INSTANCES_SEMAPHORE_NAME "/Intel_num_PCM_inst"
#else
#define PCM_INSTANCE_LOCK_SEMAPHORE_NAME "Intel(r) PCM inst lock"
#define PCM_NUM_INSTANCES_SEMAPHORE_NAME "Num Intel(r) PCM insts"
#endif
#ifdef _MSC_VER
HMODULE hOpenLibSys = NULL;
bool PCM::initWinRing0Lib()
{
const BOOL result = InitOpenLibSys(&hOpenLibSys);
if(result == FALSE) hOpenLibSys = NULL;
return result==TRUE;
}
class SystemWideLock
{
HANDLE globalMutex;
public:
SystemWideLock()
{
globalMutex = CreateMutex(NULL, FALSE,
L"Global\\Intel(r) Performance Counter Monitor instance create/destroy lock");
// lock
WaitForSingleObject(globalMutex, INFINITE);
}
~SystemWideLock()
{
// unlock
ReleaseMutex(globalMutex);
}
};
#else // Linux or Apple
class SystemWideLock
{
const char * globalSemaphoreName;
sem_t * globalSemaphore;
public:
SystemWideLock() : globalSemaphoreName(PCM_INSTANCE_LOCK_SEMAPHORE_NAME)
{
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::cout << "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");
}
}
~SystemWideLock()
{
if (sem_post(globalSemaphore)) {
perror("sem_post error");
}
}
};
#endif // end of _MSC_VER else
PCM * PCM::instance = NULL;
int bitCount(uint64 n)
{
int count = 0;
while (n)
{
count += (int)(n & 0x00000001);
n >>= 1;
}
return count;
}
PCM * PCM::getInstance()
{
// no lock here
if (instance) return instance;
SystemWideLock lock;
if (instance) return instance;
return instance = new PCM();
}
uint32 build_bit_ui(int beg, int 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 = (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;
}
int32 extractThermalHeadroom(uint64 val)
{
if(val & (1ULL<<31ULL))
{ // valid reading
return (int32)extract_bits(val,16,22);
}
// invalid reading
return PCM_INVALID_THERMAL_HEADROOM;
}
uint64 get_frequency_from_cpuid();
union PCM_CPUID_INFO
{
int array[4];
struct { 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
}
PCM::PCM() :
UnsupportedMessage("Error: unsupported processor. Only Intel(R) processors are supported (Atom(R) and microarchitecture codename Nehalem, Westmere, Sandy Bridge and Ivy Bridge)."),
cpu_family(-1),
cpu_model(-1),
original_cpu_model(-1),
threads_per_core(0),
num_cores(0),
num_sockets(0),
core_gen_counter_num_max(0),
core_gen_counter_num_used(0), // 0 means no core gen counters used
core_gen_counter_width(0),
core_fixed_counter_num_max(0),
core_fixed_counter_num_used(0),
core_fixed_counter_width(0),
uncore_gen_counter_num_max(8),
uncore_gen_counter_num_used(0),
uncore_gen_counter_width(48),
uncore_fixed_counter_num_max(1),
uncore_fixed_counter_num_used(0),
uncore_fixed_counter_width(48),
perfmon_version(0),
perfmon_config_anythread(1),
nominal_frequency(0),
qpi_speed(0),
pkgThermalSpecPower(-1),
pkgMinimumPower(-1),
pkgMaximumPower(-1),
MSR(NULL),
server_pcicfg_uncore(NULL),
clientBW(NULL),
clientImcReads(NULL),
clientImcWrites(NULL),
disable_JKT_workaround(false),
coreCStateMsr(NULL),
pkgCStateMsr(NULL),
mode(INVALID_MODE),
canUsePerf(false)
{
char buffer[1024];
PCM_CPUID_INFO cpuinfo;
int max_cpuid;
pcm_cpuid(0, cpuinfo);
memset(buffer, 0, 1024);
((int *)buffer)[0] = cpuinfo.array[1];
((int *)buffer)[1] = cpuinfo.array[3];
((int *)buffer)[2] = cpuinfo.array[2];
if (strncmp(buffer, "GenuineIntel", 4 * 3) != 0)
{
std::cout << UnsupportedMessage << std::endl;
return;
}
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);
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::cout << UnsupportedMessage << " CPU Family: " << cpu_family << std::endl;
return;
}
if(!checkModel()) return;
#define PCM_PARAM_PROTECT(...) __VA_ARGS__
#define PCM_CSTATE_ARRAY(array_ , val ) \
{ \
static uint64 tmp[] = val; \
PCM_COMPILE_ASSERT( sizeof(tmp)/sizeof(uint64) == 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:
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:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0, 0, 0}) );
case HASWELL_ULT:
PCM_CSTATE_ARRAY(pkgCStateMsr, PCM_PARAM_PROTECT({0, 0, 0x60D, 0x3F8, 0, 0, 0x3F9, 0x3FA, 0x630, 0x631, 0x632}) );
default:
std::cout << "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 ATOM_BAYTRAIL:
case ATOM_AVOTON:
PCM_CSTATE_ARRAY(coreCStateMsr, PCM_PARAM_PROTECT({0, 0, 0, 0x3FC, 0, 0, 0x3FD, 0x3FE, 0, 0, 0}) );
default:
std::cout << "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 _MSC_VER
// version for Windows
#ifdef COMPILE_FOR_WINDOWS_7
DWORD GroupStart[5]; // at most 4 groups on Windows 7
GroupStart[0] = 0;
GroupStart[1] = GetActiveProcessorCount(0);
GroupStart[2] = GroupStart[1] + GetActiveProcessorCount(1);
GroupStart[3] = GroupStart[2] + GetActiveProcessorCount(2);
GroupStart[4] = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
if (GroupStart[3] + GetActiveProcessorCount(3) != GetActiveProcessorCount(ALL_PROCESSOR_GROUPS))
{
std::cout << "Error in processor group size counting (1)" << std::endl;
std::cout << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration." << std::endl;
return;
}
char * slpi = new char[sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)];
DWORD len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX);
DWORD 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::cout << "Error in Windows function 'GetLogicalProcessorInformationEx': " <<
GetLastError() << std::endl;
return;
}
}
char * base_slpi = slpi;
PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX pi = NULL;
for ( ; slpi < base_slpi + len; slpi += 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::cout << "Error in processor group size counting: " << num_cores << "!=" << GetActiveProcessorCount(ALL_PROCESSOR_GROUPS) << std::endl;
std::cout << "Make sure your binary is compiled for 64-bit: using 'x64' platform configuration." << std::endl;
return;
}
topology.resize(num_cores);
slpi = base_slpi;
pi = NULL;
for ( ; slpi < base_slpi + len; slpi += pi->Size)
{
pi = (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX)slpi;
if (pi->Relationship == RelationNumaNode)
{
++num_sockets;
for (unsigned int c = 0; c < (unsigned int)num_cores; ++c)
{
// std::cout << "c:"<<c<<" GroupStart[slpi->NumaNode.GroupMask.Group]: "<<GroupStart[slpi->NumaNode.GroupMask.Group]<<std::endl;
if (c < GroupStart[pi->NumaNode.GroupMask.Group] || c >= GroupStart[(pi->NumaNode.GroupMask.Group) + 1])
{
//std::cout <<"core "<<c<<" is not in group "<< slpi->NumaNode.GroupMask.Group << std::endl;
continue;
}
if ((1LL << (c - GroupStart[pi->NumaNode.GroupMask.Group])) & pi->NumaNode.GroupMask.Mask)
{
topology[c].core_id = c;
topology[c].os_id = c;
topology[c].socket = pi->NumaNode.NodeNumber;
// std::cout << "Core "<< c <<" is in NUMA node "<< topology[c].socket << " and belongs to processor group " << slpi->NumaNode.GroupMask.Group <<std::endl;
}
}
}
}
delete[] base_slpi;
#else // windows, not windows 7
int32 size = 1;
SYSTEM_LOGICAL_PROCESSOR_INFORMATION * slpi = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size];
DWORD len = sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
DWORD res = GetLogicalProcessorInformation(slpi, &len);
while (res == FALSE)
{
delete[] slpi;
if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
size = (int32) len / sizeof(SYSTEM_LOGICAL_PROCESSOR_INFORMATION);
slpi = new SYSTEM_LOGICAL_PROCESSOR_INFORMATION[size];
res = GetLogicalProcessorInformation(slpi, &len);
}
else
{
std::cout << "Error in Windows function 'GetLogicalProcessorInformation': " <<
GetLastError() << std::endl;
return;
}
}
for (i = 0; i < size; ++i)
{
if (slpi[i].Relationship == RelationProcessorCore)
{
//std::cout << "Physical core found, mask: "<<slpi[i].ProcessorMask<< std::endl;
threads_per_core = bitCount(slpi[i].ProcessorMask);
num_cores += threads_per_core;
}
}
topology.resize(num_cores);
for (i = 0; i < size; ++i)
{
if (slpi[i].Relationship == RelationNumaNode)
{
//std::cout << "NUMA node "<<slpi[i].NumaNode.NodeNumber<<" cores: "<<slpi[i].ProcessorMask<< std::endl;
++num_sockets;
for (int c = 0; c < num_cores; ++c)
{
if ((1LL << c) & slpi[i].ProcessorMask)
{
topology[c].core_id = c;
topology[c].os_id = c;
topology[c].socket = slpi[i].NumaNode.NodeNumber;
//std::cout << "Core "<< c <<" is in NUMA node "<< topology[c].socket << std::endl;
}
}
}
}
delete[] slpi;
#endif // end of COMPILE_FOR_WINDOWS_7
#else
// for Linux and Mac OS
TopologyEntry entry;
typedef std::map<uint32, uint32> socketIdMap_type;
socketIdMap_type socketIdMap;
#ifdef __linux__
// open /proc/cpuinfo
FILE * f_cpuinfo = fopen("/proc/cpuinfo", "r");
if (!f_cpuinfo)
{
std::cout << "Can not open /proc/cpuinfo file." << std::endl;
return;
}
while (0 != fgets(buffer, 1024, f_cpuinfo))
{
if (strncmp(buffer, "processor", sizeof("processor") - 1) == 0)
{
if (entry.os_id >= 0)
{
topology.push_back(entry);
if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core;
}
sscanf(buffer, "processor\t: %d", &entry.os_id);
//std::cout << "os_core_id: "<<entry.os_id<< std::endl;
continue;
}
if (strncmp(buffer, "physical id", sizeof("physical id") - 1) == 0)
{
sscanf(buffer, "physical id\t: %d", &entry.socket);
//std::cout << "physical id: "<<entry.socket<< std::endl;
socketIdMap[entry.socket] = 0;
continue;
}
if (strncmp(buffer, "core id", sizeof("core id") - 1) == 0)
{
sscanf(buffer, "core id\t: %d", &entry.core_id);
//std::cout << "core id: "<<entry.core_id<< std::endl;
continue;
}
}
if (entry.os_id >= 0)
{
topology.push_back(entry);
if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core;
}
fclose(f_cpuinfo);
#elif defined(__FreeBSD__)
size_t size = sizeof(num_cores);
cpuctl_cpuid_args_t cpuid_args;
int fd, apic_ids_per_package, apic_ids_per_core;
if(0 != sysctlbyname("kern.smp.cpus", &num_cores, &size, NULL, 0))
{
std::cout << "Unable to get kern.smp.cpus from sysctl." << std::endl;
return;
}
do_cpuid(1, cpuid_args.data);
apic_ids_per_package = (cpuid_args.data[1] & 0x00FF0000) >> 16;
cpuid_count(0xb, 0x0, cpuid_args.data);
if ((cpuid_args.data[2] & 0xFF00) == 0x100)
apic_ids_per_core = cpuid_args.data[1] & 0xFFFF;
else
apic_ids_per_core = 1;
for (i = 0; i < num_cores; i++)
{
char cpuctl_name[64];
int apic_id;
sprintf(cpuctl_name, "/dev/cpuctl%d", i);
fd = ::open(cpuctl_name, O_RDWR);
cpuid_args.level = 0xb;
::ioctl(fd, CPUCTL_CPUID, &cpuid_args);
apic_id = cpuid_args.data[3];
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;
if (entry.socket == 0 && entry.core_id == 0) ++threads_per_core;
topology.push_back(entry);
socketIdMap[entry.socket] = 0;
}
#else // Getting processor info for Mac OS
#define SAFE_SYSCTLBYNAME(message, ret_value) \
{ \
size_t size; \
char *pParam; \
if(0 != sysctlbyname(message, NULL, &size, NULL, 0)) \
{ \
std::cout << "Unable to determine size of " << message << " sysctl return type." << std::endl; \
return; \
} \
if(NULL == (pParam = (char *)malloc(size))) \
{ \
std::cout << "Unable to allocate memory for " << message << std::endl; \
return; \
} \
if(0 != sysctlbyname(message, (void*)pParam, &size, NULL, 0)) \
{ \
std::cout << "Unable to get " << message << " from sysctl." << std::endl; \
return; \
} \
ret_value = convertUnknownToInt(size, pParam); \
free(pParam); \
}
// End SAFE_SYSCTLBYNAME
// Using OSXs sysctl to get the number of CPUs right away
SAFE_SYSCTLBYNAME("hw.logicalcpu", num_cores)
#undef SAFE_SYSCTLBYNAME
// The OSX version needs the MSR handle earlier so that it can build the CPU topology.
// This topology functionality should potentially go into a different KEXT
MSR = new MsrHandle *[num_cores];
for(int i = 0; i < num_cores; i++)
{
MSR[i] = new MsrHandle(i);
}
TopologyEntry *entries = new TopologyEntry[num_cores];
MSR[0]->buildTopology(num_cores, entries);
for(int i = 0; i < num_cores; i++){
socketIdMap[entries[i].socket] = 0;
if(entries[i].os_id >= 0)
{
if(entries[i].core_id == 0 && entries[i].socket == 0) ++threads_per_core;
topology.push_back(entries[i]);
}
}
delete entries;
// End of OSX specific code
#endif // end of ifndef __APPLE__
num_cores = topology.size();
num_sockets = (std::max)(socketIdMap.size(), (size_t)1);
socketIdMap_type::iterator s = socketIdMap.begin();
for (uint sid = 0; s != socketIdMap.end(); ++s)
{
s->second = sid++;
}
for (int i = 0; i < num_cores; ++i)
{
topology[i].socket = socketIdMap[topology[i].socket];
}
#if 0
std::cout << "Number of socket ids: " << socketIdMap.size() << "\n";
std::cout << "Topology:\nsocket os_id core_id\n";
for (int i = 0; i < num_cores; ++i)
{
std::cout << topology[i].socket << " " << topology[i].os_id << " " << topology[i].core_id << std::endl;
}
#endif
#endif //end of ifdef _MSC_VER
std::cout << "Number of physical cores: " << (num_cores/threads_per_core) << std::endl;
std::cout << "Number of logical cores: " << num_cores << std::endl;
std::cout << "Threads (logical cores) per physical core: " << threads_per_core << std::endl;
std::cout << "Num sockets: " << num_sockets << std::endl;
std::cout << "Core PMU (perfmon) version: " << perfmon_version << std::endl;
std::cout << "Number of core PMU generic (programmable) counters: " << core_gen_counter_num_max << std::endl;
std::cout << "Width of generic (programmable) counters: " << core_gen_counter_width << " bits" << std::endl;
if (perfmon_version > 1)
{
std::cout << "Number of core PMU fixed counters: " << core_fixed_counter_num_max << std::endl;
std::cout << "Width of fixed counters: " << core_fixed_counter_width << " bits" << std::endl;
}
socketRefCore.resize(num_sockets);
int32 i = 0;
#ifndef __APPLE__
MSR = new MsrHandle *[num_cores];
try
{
for (i = 0; i < num_cores; ++i)
{
MSR[i] = new MsrHandle(i);
socketRefCore[topology[i].socket] = i;
}
}
catch (...)
{
// failed
for (int j = 0; j < i; j++)
delete MSR[j];
delete[] MSR;
MSR = NULL;
std::cerr << "Can not access CPUs Model Specific Registers (MSRs)." << std::endl;
#ifdef _MSC_VER
std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program." << std::endl;
#elif defined(__linux__)
std::cerr << "Try to execute 'modprobe msr' as root user and then" << std::endl;
std::cerr << "you also must have read and write permissions for /dev/cpu/*/msr devices (/dev/msr* for Android). The 'chown' command can help." << std::endl;
#elif defined(__FreeBSD__)
std::cerr << "Ensure cpuctl module is loaded and that you have read and write" << std::endl;
std::cerr << "permissions for /dev/cpuctl* devices (the 'chown' command can help)." << std::endl;
#endif
}
#else
for(i = 0; i < num_cores; ++i)
{
socketRefCore[topology[i].socket] = i;
}
#endif
if (MSR)
{
uint64 freq = 0;
MSR[0]->read(PLATFORM_INFO_ADDR, &freq);
const uint64 bus_freq = (
cpu_model == SANDY_BRIDGE
|| cpu_model == JAKETOWN
|| cpu_model == IVYTOWN
|| cpu_model == IVY_BRIDGE
|| cpu_model == HASWELL
|| original_cpu_model == ATOM_AVOTON
) ? (100000000ULL) : (133333333ULL);
nominal_frequency = ((freq >> 8) & 255) * bus_freq;
if(!nominal_frequency)
nominal_frequency = get_frequency_from_cpuid();
if(!nominal_frequency)
{
std::cout << "Error: Can not detect core frequency." << std::endl;
destroyMSR();
return;
}
std::cout << "Nominal core frequency: " << nominal_frequency << " Hz" << std::endl;
}
if(packageEnergyMetricsAvailable() && MSR)
{
uint64 rapl_power_unit = 0;
MSR[0]->read(MSR_RAPL_POWER_UNIT,&rapl_power_unit);
uint64 energy_status_unit = extract_bits(rapl_power_unit,8,12);
joulesPerEnergyUnit = 1./double(1ULL<<energy_status_unit); // (1/2)^energy_status_unit
//std::cout << "MSR_RAPL_POWER_UNIT: "<<energy_status_unit<<"; Joules/unit "<< joulesPerEnergyUnit << std::endl;
uint64 power_unit = extract_bits(rapl_power_unit,0,3);
double wattsPerPowerUnit = 1./double(1ULL<<power_unit);
uint64 package_power_info = 0;
MSR[0]->read(MSR_PKG_POWER_INFO,&package_power_info);
pkgThermalSpecPower = (uint32) (double(extract_bits(package_power_info, 0, 14))*wattsPerPowerUnit);
pkgMinimumPower = (uint32) (double(extract_bits(package_power_info, 16, 30))*wattsPerPowerUnit);
pkgMaximumPower = (uint32) (double(extract_bits(package_power_info, 32, 46))*wattsPerPowerUnit);
std::cout << "Package thermal spec power: "<< pkgThermalSpecPower << " Watt; ";
std::cout << "Package minimum power: "<< pkgMinimumPower << " Watt; ";
std::cout << "Package maximum power: "<< pkgMaximumPower << " Watt; " << std::endl;
if(snb_energy_status.empty())
for (i = 0; i < num_sockets; ++i)
snb_energy_status.push_back(new CounterWidthExtender(new CounterWidthExtender::MsrHandleCounter(MSR[socketRefCore[i]],MSR_PKG_ENERGY_STATUS)) );
if(dramEnergyMetricsAvailable() && jkt_dram_energy_status.empty())
for (i = 0; i < num_sockets; ++i)
jkt_dram_energy_status.push_back(new CounterWidthExtender(new CounterWidthExtender::MsrHandleCounter(MSR[socketRefCore[i]],MSR_DRAM_ENERGY_STATUS)));
}
if (hasPCICFGUncore() && MSR != NULL)
{
server_pcicfg_uncore = new ServerPCICFGUncore *[num_sockets];
try
{
for (i = 0; i < num_sockets; ++i)
{
server_pcicfg_uncore[i] = new ServerPCICFGUncore(i, this);
}
}
catch (...)
{
// failed
for (int j = 0; j < i; j++)
delete server_pcicfg_uncore[j];
delete[] server_pcicfg_uncore;
server_pcicfg_uncore = NULL;
std::cerr << "Can not access Jaketown/Ivytown PCI configuration space. Access to uncore counters (memory and QPI bandwidth) is disabled." << std::endl;
#ifdef _MSC_VER
std::cerr << "You must have signed msr.sys driver in your current directory and have administrator rights to run this program." << std::endl;
#else
//std::cerr << "you must have read and write permissions for /proc/bus/pci/7f/10.* and /proc/bus/pci/ff/10.* devices (the 'chown' command can help)." << std::endl;
//std::cerr << "you must have read and write permissions for /dev/mem device (the 'chown' command can help)."<< std::endl;
//std::cerr << "you must have read permission for /sys/firmware/acpi/tables/MCFG device (the 'chmod' command can help)."<< std::endl;
std::cerr << "You must be root to access these Jaketown/Ivytown counters in PCM. " << std::endl;
#endif
}
} else if((cpu_model == SANDY_BRIDGE || cpu_model == IVY_BRIDGE || cpu_model == HASWELL) && MSR != NULL)
{
// initialize memory bandwidth counting
try
{
clientBW = new ClientBW();
clientImcReads = new CounterWidthExtender(new CounterWidthExtender::ClientImcReadsCounter(clientBW));
clientImcWrites = new CounterWidthExtender(new CounterWidthExtender::ClientImcWritesCounter(clientBW));
} catch(...)
{
std::cerr << "Can not read memory controller counter information from PCI configuration space. Access to memory bandwidth counters is not possible." << std::endl;
#ifdef _MSC_VER
// TODO: add message here
#endif
#ifdef __linux__
std::cerr << "You must be root to access these SandyBridge/IvyBridge/Haswell counters in PCM. " << std::endl;
#endif
}
}
PCU_MSR_PMON_BOX_CTL_ADDR = JKTIVT_PCU_MSR_PMON_BOX_CTL_ADDR;
PCU_MSR_PMON_CTRX_ADDR[0] = JKTIVT_PCU_MSR_PMON_CTR0_ADDR;
PCU_MSR_PMON_CTRX_ADDR[1] = JKTIVT_PCU_MSR_PMON_CTR1_ADDR;
PCU_MSR_PMON_CTRX_ADDR[2] = JKTIVT_PCU_MSR_PMON_CTR2_ADDR;
PCU_MSR_PMON_CTRX_ADDR[3] = JKTIVT_PCU_MSR_PMON_CTR3_ADDR;
#ifdef PCM_USE_PERF
canUsePerf = true;
std::vector<int> dummy(PERF_MAX_COUNTERS, -1);
perfEventHandle.resize(num_cores, dummy);
#endif
}
void PCM::enableJKTWorkaround(bool enable)
{
if(disable_JKT_workaround) return;
std::cout << "Using PCM on your system might have a performance impact as per http://software.intel.com/en-us/articles/performance-impact-when-sampling-certain-llc-events-on-snb-ep-with-vtune" << std::endl;
std::cout << "You can avoid the performance impact by using the option --noJKTWA, however the cache metrics might be wrong then." << std::endl;
if(MSR)
{
for(int32 i = 0; i < num_cores; ++i)
{
uint64 val64 = 0;
MSR[i]->read(0x39C, &val64);
if(enable)
val64 |= 1ULL;
else
val64 &= (~1ULL);
MSR[i]->write(0x39C, val64);
}
}
if(server_pcicfg_uncore)
{
for (int32 i = 0; i < num_sockets; ++i)
{
if(server_pcicfg_uncore[i]) server_pcicfg_uncore[i]->enableJKTWorkaround(enable);
}
}
}
bool PCM::isCPUModelSupported(int model_)
{
return ( model_ == NEHALEM_EP
|| model_ == NEHALEM_EX
|| model_ == WESTMERE_EP
|| model_ == WESTMERE_EX
|| model_ == ATOM
|| model_ == CLARKDALE
|| model_ == SANDY_BRIDGE
|| model_ == JAKETOWN
|| model_ == IVY_BRIDGE
|| model_ == HASWELL
|| model_ == IVYTOWN
);
}
bool PCM::checkModel()
{