forked from intel/pcm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpucounters.h
2795 lines (2389 loc) · 103 KB
/
cpucounters.h
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
// Thomas Willhalm
#ifndef CPUCOUNTERS_HEADER
#define CPUCOUNTERS_HEADER
/*! \file cpucounters.h
\brief Main CPU counters header
Include this header file if you want to access CPU counters (core and uncore - including memory controller chips and QPI)
*/
#define PCM_VERSION " ($Format:%ci ID=%h$)"
#ifndef PCM_API
#define PCM_API
#endif
#include "types.h"
#include "msr.h"
#include "pci.h"
#include "client_bw.h"
#include "width_extender.h"
#include <vector>
#include <limits>
#include <string>
#include <memory>
#include <map>
#include <string.h>
#ifdef PCM_USE_PERF
#include <linux/perf_event.h>
#include <errno.h>
#define PCM_PERF_COUNT_HW_REF_CPU_CYCLES (9)
#endif
#ifndef _MSC_VER
#define NOMINMAX
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <unistd.h>
#endif
class SystemCounterState;
class SocketCounterState;
class CoreCounterState;
class BasicCounterState;
class ServerUncorePowerState;
class PCM;
class CoreTaskQueue;
#ifdef _MSC_VER
void PCM_API restrictDriverAccess(LPCWSTR path);
#endif
/*
CPU performance monitoring routines
A set of performance monitoring routines for recent Intel CPUs
*/
struct PCM_API TopologyEntry // decribes a core
{
int32 os_id;
int32 thread_id;
int32 core_id;
int32 tile_id; // tile is a constalation of 1 or more cores sharing salem L2 cache. Unique for entire system
int32 socket;
TopologyEntry() : os_id(-1), thread_id (-1), core_id(-1), tile_id(-1), socket(-1) { }
};
//! Object to access uncore counters in a socket/processor with microarchitecture codename SandyBridge-EP (Jaketown) or Ivytown-EP or Ivytown-EX
class ServerPCICFGUncore
{
int32 iMCbus,UPIbus;
uint32 groupnr;
int32 cpu_model;
std::vector<std::shared_ptr<PciHandleType> > imcHandles;
std::vector<std::shared_ptr<PciHandleType> > edcHandles;
std::vector<std::shared_ptr<PciHandleType> > qpiLLHandles;
std::vector<uint64> qpi_speed;
uint32 num_imc;
uint32 MCX_CHY_REGISTER_DEV_ADDR[2][4];
uint32 MCX_CHY_REGISTER_FUNC_ADDR[2][4];
uint32 EDCX_ECLK_REGISTER_DEV_ADDR[8];
uint32 EDCX_ECLK_REGISTER_FUNC_ADDR[8];
uint32 QPI_PORTX_REGISTER_DEV_ADDR[3];
uint32 QPI_PORTX_REGISTER_FUNC_ADDR[3];
uint32 LINK_PCI_PMON_BOX_CTL_ADDR;
uint32 LINK_PCI_PMON_CTL_ADDR[4];
uint32 LINK_PCI_PMON_CTR_ADDR[4];
static PCM_Util::Mutex socket2busMutex;
static std::vector<std::pair<uint32, uint32> > socket2iMCbus;
static std::vector<std::pair<uint32, uint32> > socket2UPIbus;
void initSocket2Bus(std::vector<std::pair<uint32, uint32> > & socket2bus, uint32 device, uint32 function, const uint32 DEV_IDS[], uint32 devIdsSize);
ServerPCICFGUncore(); // forbidden
ServerPCICFGUncore(ServerPCICFGUncore &); // forbidden
ServerPCICFGUncore & operator = (const ServerPCICFGUncore &); // forbidden
PciHandleType * createIntelPerfMonDevice(uint32 groupnr, int32 bus, uint32 dev, uint32 func, bool checkVendor = false);
void programIMC(const uint32 * MCCntConfig);
void programEDC(const uint32 * EDCCntConfig);
typedef std::pair<size_t, std::vector<uint64 *> > MemTestParam;
void initMemTest(MemTestParam & param);
void doMemTest(const MemTestParam & param);
void cleanupMemTest(const MemTestParam & param);
void cleanupQPIHandles();
public:
//! \brief Initialize access data structures
//! \param socket_ socket id
//! \param pcm pointer to PCM instance
ServerPCICFGUncore(uint32 socket_, const PCM * pcm);
//! \brief Program performance counters (disables programming power counters)
void program();
//! \brief Get the number of integrated controller reads (in cache lines)
uint64 getImcReads();
//! \brief Get the number of integrated controller writes (in cache lines)
uint64 getImcWrites();
//! \brief Get the number of cache lines read by EDC (embedded DRAM controller)
uint64 getEdcReads();
//! \brief Get the number of cache lines written by EDC (embedded DRAM controller)
uint64 getEdcWrites();
//! \brief Get the number of incoming data flits to the socket through a port
//! \param port QPI port id
uint64 getIncomingDataFlits(uint32 port);
//! \brief Get the number of outgoing data and non-data or idle flits (depending on the architecture) from the socket through a port
//! \param port QPI port id
uint64 getOutgoingFlits(uint32 port);
virtual ~ServerPCICFGUncore();
//! \brief Program power counters (disables programming performance counters)
//! \param mc_profile memory controller measurement profile. See description of profiles in pcm-power.cpp
void program_power_metrics(int mc_profile);
//! \brief Program memory counters (disables programming performance counters)
//! \param rankA count DIMM rank1 statistics (disables memory channel monitoring)
//! \param rankB count DIMM rank2 statistics (disables memory channel monitoring)
void programServerUncoreMemoryMetrics(int rankA = -1, int rankB = -1);
//! \brief Get number of QPI LL clocks on a QPI port
//! \param port QPI port number
uint64 getQPIClocks(uint32 port);
//! \brief Get number cycles on a QPI port when the link was in a power saving half-lane mode
//! \param port QPI port number
uint64 getQPIL0pTxCycles(uint32 port);
//! \brief Get number cycles on a UPI port when the link was in a L0 mode (fully active)
//! \param port UPI port number
uint64 getUPIL0TxCycles(uint32 port);
//! \brief Get number cycles on a QPI port when the link was in a power saving shutdown mode
//! \param port QPI port number
uint64 getQPIL1Cycles(uint32 port);
//! \brief Get number DRAM channel cycles
//! \param channel channel number
uint64 getDRAMClocks(uint32 channel);
//! \brief Get number MCDRAM channel cycles
//! \param channel channel number
uint64 getMCDRAMClocks(uint32 channel);
//! \brief Direct read of memory controller PMU counter (counter meaning depends on the programming: power/performance/etc)
//! \param channel channel number
//! \param counter counter number
uint64 getMCCounter(uint32 channel, uint32 counter);
//! \brief Direct read of embedded DRAM memory controller PMU counter (counter meaning depends on the programming: power/performance/etc)
//! \param channel channel number
//! \param counter counter number
uint64 getEDCCounter(uint32 channel, uint32 counter);
//! \brief Direct read of QPI LL PMU counter (counter meaning depends on the programming: power/performance/etc)
//! \param port port number
//! \param counter counter number
uint64 getQPILLCounter(uint32 port, uint32 counter);
//! \brief Freezes event counting
void freezeCounters();
//! \brief Unfreezes event counting
void unfreezeCounters();
//! \brief Measures/computes the maximum theoretical QPI link bandwidth speed in GByte/seconds
uint64 computeQPISpeed(const uint32 ref_core, const int cpumodel);
//! \brief Enable correct counting of various LLC events (with memory access perf penalty)
void enableJKTWorkaround(bool enable);
//! \brief Returns the number of detected QPI ports
size_t getNumQPIPorts() const { return (size_t)qpiLLHandles.size(); }
//! \brief Returns the speed of the QPI link
uint64 getQPILinkSpeed(const uint32 linkNr) const
{
return qpi_speed.empty() ? 0 : qpi_speed[linkNr];
}
//! \brief Print QPI Speeds
void reportQPISpeed() const;
//! \brief Returns the number of detected integrated memory controllers
uint32 getNumMC() const { return num_imc; }
//! \brief Returns the total number of detected memory channels on all integrated memory controllers
size_t getNumMCChannels() const { return (size_t)imcHandles.size(); }
//! \brief Returns the total number of detected memory channels on all embedded DRAM controllers (EDC)
size_t getNumEDCChannels() const { return (size_t)edcHandles.size(); }
};
class SimpleCounterState
{
template <class T>
friend uint64 getNumberOfEvents(const T & before, const T & after);
friend class PCM;
uint64 data;
public:
SimpleCounterState() : data(0)
{ }
virtual ~SimpleCounterState() { }
};
typedef SimpleCounterState PCIeCounterState;
typedef SimpleCounterState IIOCounterState;
#ifndef HACK_TO_REMOVE_DUPLICATE_ERROR
template class PCM_API std::allocator<TopologyEntry>;
template class PCM_API std::vector<TopologyEntry>;
template class PCM_API std::allocator<CounterWidthExtender *>;
template class PCM_API std::vector<CounterWidthExtender *>;
template class PCM_API std::allocator<uint32>;
template class PCM_API std::vector<uint32>;
template class PCM_API std::allocator<char>;
#endif
/*!
\brief CPU Performance Monitor
This singleton object needs to be instantiated for each process
before accessing counting and measuring routines
*/
class PCM_API PCM
{
friend class BasicCounterState;
friend class UncoreCounterState;
PCM(); // forbidden to call directly because it is a singleton
int32 cpu_family;
int32 cpu_model, original_cpu_model;
int32 cpu_stepping;
int32 threads_per_core;
int32 num_cores;
int32 num_sockets;
int32 num_phys_cores_per_socket;
int32 num_online_cores;
int32 num_online_sockets;
uint32 core_gen_counter_num_max;
uint32 core_gen_counter_num_used;
uint32 core_gen_counter_width;
uint32 core_fixed_counter_num_max;
uint32 core_fixed_counter_num_used;
uint32 core_fixed_counter_width;
uint32 uncore_gen_counter_num_max;
uint32 uncore_gen_counter_num_used;
uint32 uncore_gen_counter_width;
uint32 uncore_fixed_counter_num_max;
uint32 uncore_fixed_counter_num_used;
uint32 uncore_fixed_counter_width;
uint32 perfmon_version;
int32 perfmon_config_anythread;
uint64 nominal_frequency;
uint64 max_qpi_speed; // in GBytes/second
uint32 L3ScalingFactor;
int32 pkgThermalSpecPower, pkgMinimumPower, pkgMaximumPower;
std::vector<TopologyEntry> topology;
std::string errorMessage;
static PCM * instance;
bool allow_multiple_instances;
bool programmed_pmu;
std::vector<std::shared_ptr<SafeMsrHandle> > MSR;
std::vector<std::shared_ptr<ServerPCICFGUncore> > server_pcicfg_uncore;
uint64 PCU_MSR_PMON_BOX_CTL_ADDR, PCU_MSR_PMON_CTRX_ADDR[4];
std::map<int32, uint32> IIO_UNIT_STATUS_ADDR;
std::map<int32, uint32> IIO_UNIT_CTL_ADDR;
std::map<int32, std::vector<uint32> > IIO_CTR_ADDR;
std::map<int32, uint32> IIO_CLK_ADDR;
std::map<int32, std::vector<uint32> > IIO_CTL_ADDR;
double joulesPerEnergyUnit;
std::vector<std::shared_ptr<CounterWidthExtender> > energy_status;
std::vector<std::shared_ptr<CounterWidthExtender> > dram_energy_status;
std::vector<std::shared_ptr<CounterWidthExtender> > memory_bw_local;
std::vector<std::shared_ptr<CounterWidthExtender> > memory_bw_total;
std::shared_ptr<ClientBW> clientBW;
std::shared_ptr<CounterWidthExtender> clientImcReads;
std::shared_ptr<CounterWidthExtender> clientImcWrites;
std::shared_ptr<CounterWidthExtender> clientIoRequests;
bool disable_JKT_workaround;
bool blocked; // track if time-driven counter update is running or not: PCM is blocked
uint64 * coreCStateMsr; // MSR addresses of core C-state free-running counters
uint64 * pkgCStateMsr; // MSR addresses of package C-state free-running counters
std::vector<std::shared_ptr<CoreTaskQueue> > coreTaskQueues;
public:
enum { MAX_C_STATE = 10 }; // max C-state on Intel architecture
//! \brief Returns true if the specified core C-state residency metric is supported
bool isCoreCStateResidencySupported(int state)
{
if (state == 0 || state == 1)
return true;
return (coreCStateMsr != NULL && state <= ((int)MAX_C_STATE) && coreCStateMsr[state] != 0);
}
//! \brief Returns true if the specified package C-state residency metric is supported
bool isPackageCStateResidencySupported(int state)
{
return (pkgCStateMsr != NULL && state <= ((int)MAX_C_STATE) && pkgCStateMsr[state] != 0);
}
//! \brief Redirects output destination to provided file, instead of std::cout
void setOutput(const std::string filename);
//! \brief Restores output, closes output file if opened
void restoreOutput();
//! \brief Set Run State.
// Arguments:
// -- 1 - program is running
// -- 0 -pgram is sleeping
void setRunState(int new_state) { run_state = new_state; }
//! \brief Returns program's Run State.
// Results:
// -- 1 - program is running
// -- 0 -pgram is sleeping
int getRunState(void) { return run_state; }
bool isBlocked(void) { return blocked; }
void setBlocked(const bool new_blocked) { blocked = new_blocked; }
//! \brief Call it before program() to allow multiple running instances of PCM on the same system
void allowMultipleInstances()
{
allow_multiple_instances = true;
}
//! Mode of programming (parameter in the program() method)
enum ProgramMode {
DEFAULT_EVENTS = 0, /*!< Default choice of events, the additional parameter is not needed and ignored */
CUSTOM_CORE_EVENTS = 1, /*!< Custom set of core events specified in the parameter to the program method. The parameter must be a pointer to array of four \c CustomCoreEventDescription values */
EXT_CUSTOM_CORE_EVENTS = 2, /*!< Custom set of core events specified in the parameter to the program method. The parameter must be a pointer to a \c ExtendedCustomCoreEventDescription data structure */
INVALID_MODE /*!< Non-programmed mode */
};
//! Return codes (e.g. for program(..) method)
enum ErrorCode {
Success = 0,
MSRAccessDenied = 1,
PMUBusy = 2,
UnknownError
};
enum PerfmonField {
INVALID, /* Use to parse invalid field */
OPCODE,
EVENT_SELECT,
UMASK,
RESET,
EDGE_DET,
IGNORED,
OVERFLOW_ENABLE,
ENABLE,
INVERT,
THRESH,
CH_MASK,
FC_MASK,
/* Below are not part of perfmon definition */
H_EVENT_NAME,
V_EVENT_NAME,
MULTIPLIER,
DIVIDER,
COUNTER_INDEX
};
enum PCIeWidthMode {
X1,
X4,
X8,
X16,
XFF
};
enum { // offsets/enumeration of IIO stacks
IIO_CBDMA = 0, // shared with DMI
IIO_PCIe0 = 1,
IIO_PCIe1 = 2,
IIO_PCIe2 = 3,
IIO_MCP0 = 4,
IIO_MCP1 = 5,
IIO_STACK_COUNT = 6
};
struct SimplePCIeDevInfo
{
enum PCIeWidthMode width;
std::string pciDevName;
std::string busNumber;
SimplePCIeDevInfo() : width(XFF) { }
};
/*! \brief Custom Core event description
See "Intel 64 and IA-32 Architectures Software Developers Manual Volume 3B:
System Programming Guide, Part 2" for the concrete values of the data structure fields,
e.g. Appendix A.2 "Performance Monitoring Events for Intel(r) Core(tm) Processor Family
and Xeon Processor Family"
*/
struct CustomCoreEventDescription
{
int32 event_number, umask_value;
};
/*! \brief Extended custom core event description
In contrast to CustomCoreEventDescription supports configuration of all fields.
See "Intel 64 and IA-32 Architectures Software Developers Manual Volume 3B:
System Programming Guide, Part 2" for the concrete values of the data structure fields,
e.g. Appendix A.2 "Performance Monitoring Events for Intel(r) Core(tm) Processor Family
and Xeon Processor Family"
*/
struct ExtendedCustomCoreEventDescription
{
FixedEventControlRegister * fixedCfg; // if NULL, then default configuration performed for fixed counters
uint32 nGPCounters; // number of general purpose counters
EventSelectRegister * gpCounterCfg; // general purpose counters, if NULL, then default configuration performed for GP counters
uint64 OffcoreResponseMsrValue[2];
ExtendedCustomCoreEventDescription() : fixedCfg(NULL), nGPCounters(0), gpCounterCfg(NULL)
{
OffcoreResponseMsrValue[0] = 0;
OffcoreResponseMsrValue[1] = 0;
}
};
struct CustomIIOEventDescription
{
/* We program the same counters to every IIO Stacks */
std::string eventNames[4];
IIOPMUCNTCTLRegister eventOpcodes[4];
int multiplier[4]; //Some IIO event requires transformation to get meaningful output (i.e. DWord to bytes)
int divider[4]; //We usually like to have some kind of divider (i.e. /10e6 )
};
private:
ProgramMode mode;
CustomCoreEventDescription coreEventDesc[4];
#ifdef _MSC_VER
HANDLE numInstancesSemaphore; // global semaphore that counts the number of PCM instances on the system
#else
// global semaphore that counts the number of PCM instances on the system
sem_t * numInstancesSemaphore;
#endif
std::vector<int32> socketRefCore;
bool canUsePerf;
#ifdef PCM_USE_PERF
std::vector<std::vector<int> > perfEventHandle;
void readPerfData(uint32 core, std::vector<uint64> & data);
enum {
PERF_INST_RETIRED_ANY_POS = 0,
PERF_CPU_CLK_UNHALTED_THREAD_POS = 1,
PERF_CPU_CLK_UNHALTED_REF_POS = 2,
PERF_GEN_EVENT_0_POS = 3,
PERF_GEN_EVENT_1_POS = 4,
PERF_GEN_EVENT_2_POS = 5,
PERF_GEN_EVENT_3_POS = 6
};
enum {
PERF_GROUP_LEADER_COUNTER = PERF_INST_RETIRED_ANY_POS
};
#endif
std::ofstream * outfile; // output file stream
std::streambuf * backup_ofile; // backup of original output = cout
int run_state; // either running (1) or sleeping (0)
bool PMUinUse();
void cleanupPMU();
void freeRMID();
bool decrementInstanceSemaphore(); // returns true if it was the last instance
#ifdef __APPLE__
// OSX does not have sem_getvalue, so we must get the number of instances by a different method
uint32 getNumInstances();
uint32 decrementNumInstances();
uint32 incrementNumInstances();
#endif
void computeQPISpeedBeckton(int core_nr);
void destroyMSR();
void computeNominalFrequency();
static bool isCPUModelSupported(int model_);
std::string getSupportedUarchCodenames() const;
std::string getUnsupportedMessage() const;
bool detectModel();
bool checkModel();
void initCStateSupportTables();
bool discoverSystemTopology();
void printSystemTopology() const;
bool initMSR();
bool detectNominalFrequency();
void initEnergyMonitoring();
void initUncoreObjects();
/*!
* \brief initializes each core with an RMID
*
* \returns nothing
*/
void initRMID();
/*!
* \brief initializes each core event MSR with an RMID for QOS event (L3 cache monitoring or memory bandwidth monitoring)
*
* \returns nothing
*/
void initQOSevent(const uint64 event, const int32 core);
void programBecktonUncore(int core);
void programNehalemEPUncore(int core);
void enableJKTWorkaround(bool enable);
template <class CounterStateType>
void readAndAggregateMemoryBWCounters(const uint32 core, CounterStateType & counterState);
template <class CounterStateType>
void readAndAggregateUncoreMCCounters(const uint32 socket, CounterStateType & counterState);
template <class CounterStateType>
void readAndAggregateEnergyCounters(const uint32 socket, CounterStateType & counterState);
template <class CounterStateType>
void readPackageThermalHeadroom(const uint32 socket, CounterStateType & counterState);
template <class CounterStateType>
void readAndAggregatePackageCStateResidencies(std::shared_ptr<SafeMsrHandle> msr, CounterStateType & result);
void readQPICounters(SystemCounterState & counterState);
void reportQPISpeed() const;
uint64 CX_MSR_PMON_CTRY(uint32 Cbo, uint32 Ctr) const;
uint64 CX_MSR_PMON_BOX_FILTER(uint32 Cbo) const;
uint64 CX_MSR_PMON_BOX_FILTER1(uint32 Cbo) const;
uint64 CX_MSR_PMON_CTLY(uint32 Cbo, uint32 Ctl) const;
uint64 CX_MSR_PMON_BOX_CTL(uint32 Cbo) const;
uint32 getMaxNumOfCBoxes() const;
void programCboOpcodeFilter(const uint32 opc, const uint32 cbo, std::shared_ptr<SafeMsrHandle> msr, const uint32 nc_ = 0);
public:
/*!
\brief checks if QOS monitoring support present
\returns true or false
*/
bool QOSMetricAvailable();
/*!
\brief checks L3 cache support for QOS present
\returns true or false
*/
bool L3QOSMetricAvailable();
/*!
\brief checks if L3 cache monitoring present
\returns true or false
*/
bool L3CacheOccupancyMetricAvailable();
/*!
\brief checks if local memory bandwidth monitoring present
\returns true or false
*/
bool CoreLocalMemoryBWMetricAvailable();
/*!
\brief checks if total memory bandwidth monitoring present
\returns true or false
*/
bool CoreRemoteMemoryBWMetricAvailable();
/*!
* \brief returns the max number of RMID supported by socket
*
* \returns maximum number of RMID supported by socket
*/
unsigned getMaxRMID() const;
/*!
\brief Returns PCM object
Returns PCM object. If the PCM has not been created before than
an instance is created. PCM is a singleton.
\return Pointer to PCM object
*/
static PCM * getInstance(); // the only way to get access
/*!
\brief Checks the status of PCM object
Call this method to check if PCM gained access to model specific registers. The method is deprecated, see program error code instead.
\return true iff access to model specific registers works without problems
*/
bool good(); // true if access to CPU counters works
/*! \brief Returns the error message
Call this when good() returns false, otherwise return an empty string
*/
const std::string & getErrorMessage() const
{
return errorMessage;
}
/*! \brief Programs performance counters
\param mode_ mode of programming, see ProgramMode definition
\param parameter_ optional parameter for some of programming modes
Call this method before you start using the performance counting routines.
\warning Using this routines with other tools that *program* Performance Monitoring
Units (PMUs) on CPUs is not recommended because PMU can not be shared. Tools that are known to
program PMUs: Intel(r) VTune(tm), Intel(r) Performance Tuning Utility (PTU). This code may make
VTune or PTU measurements invalid. VTune or PTU measurement may make measurement with this code invalid. Please enable either usage of these routines or VTune/PTU/etc.
*/
ErrorCode program(const ProgramMode mode_ = DEFAULT_EVENTS, const void * parameter_ = NULL); // program counters and start counting
/*! \brief Programs uncore power/energy counters on microarchitectures codename SandyBridge-EP and later Xeon uarch
\param mc_profile profile for integrated memory controller PMU. See possible profile values in pcm-power.cpp example
\param pcu_profile profile for power control unit PMU. See possible profile values in pcm-power.cpp example
\param freq_bands array of three integer values for core frequency band monitoring. See usage in pcm-power.cpp example
Call this method before you start using the power counter routines on microarchitecture codename SandyBridge-EP and later Xeon uarch
\warning After this call the memory and QPI bandwidth counters on microarchitecture codename SandyBridge-EP and later Xeon uarch will not work.
\warning Using this routines with other tools that *program* Performance Monitoring
Units (PMUs) on CPUs is not recommended because PMU can not be shared. Tools that are known to
program PMUs: Intel(r) VTune(tm), Intel(r) Performance Tuning Utility (PTU). This code may make
VTune or PTU measurements invalid. VTune or PTU measurement may make measurement with this code invalid. Please enable either usage of these routines or VTune/PTU/etc.
*/
ErrorCode programServerUncorePowerMetrics(int mc_profile, int pcu_profile, int * freq_bands = NULL);
/*! \brief Programs uncore memory counters on microarchitectures codename SandyBridge-EP and later Xeon uarch
\param rankA count DIMM rank1 statistics (disables memory channel monitoring)
\param rankB count DIMM rank2 statistics (disables memory channel monitoring)
Call this method before you start using the memory counter routines on microarchitecture codename SandyBridge-EP and later Xeon uarch
\warning Using this routines with other tools that *program* Performance Monitoring
Units (PMUs) on CPUs is not recommended because PMU can not be shared. Tools that are known to
program PMUs: Intel(r) VTune(tm), Intel(r) Performance Tuning Utility (PTU). This code may make
VTune or PTU measurements invalid. VTune or PTU measurement may make measurement with this code invalid. Please enable either usage of these routines or VTune/PTU/etc.
*/
ErrorCode programServerUncoreMemoryMetrics(int rankA = -1, int rankB = -1);
//! \brief Freezes uncore event counting (works only on microarchitecture codename SandyBridge-EP and IvyTown)
void freezeServerUncoreCounters();
//! \brief Unfreezes uncore event counting (works only on microarchitecture codename SandyBridge-EP and IvyTown)
void unfreezeServerUncoreCounters();
/*! \brief Reads the power/energy counter state of a socket (works only on microarchitecture codename SandyBridge-EP)
\param socket socket id
\return State of power counters in the socket
*/
ServerUncorePowerState getServerUncorePowerState(uint32 socket);
/*! \brief Cleanups resources and stops performance counting
One needs to call this method when your program finishes or/and you are not going to use the
performance counting routines anymore.
*/
void cleanup();
/*! \brief Forces PMU reset
If there is no chance to free up PMU from other applications you might try to call this method at your own risk.
*/
void resetPMU();
/*! \brief Reads all counter states (including system, sockets and cores)
\param systemState system counter state (return parameter)
\param socketStates socket counter states (return parameter)
\param coreStates core counter states (return parameter)
*/
void getAllCounterStates(SystemCounterState & systemState, std::vector<SocketCounterState> & socketStates, std::vector<CoreCounterState> & coreStates);
/*! \brief Reads uncore counter states (including system and sockets) but no core counters
\param systemState system counter state (return parameter)
\param socketStates socket counter states (return parameter)
*/
void getUncoreCounterStates(SystemCounterState & systemState, std::vector<SocketCounterState> & socketStates);
/*! \brief Return true if the core in online
\param os_core_id OS core id
*/
bool isCoreOnline(int32 os_core_id) const;
/*! \brief Return true if the socket in online
\param socket_id OS socket id
*/
bool isSocketOnline(int32 socket_id) const;
/*! \brief Reads the counter state of the system
System consists of several sockets (CPUs).
Socket has a CPU in it. Socket (CPU) consists of several (logical) cores.
\return State of counters in the entire system
*/
SystemCounterState getSystemCounterState();
/*! \brief Reads the counter state of a socket
\param socket socket id
\return State of counters in the socket
*/
SocketCounterState getSocketCounterState(uint32 socket);
/*! \brief Reads the counter state of a (logical) core
Be aware that during the measurement other threads may be scheduled on the same core by the operating system (this is called context-switching). The performance events caused by these threads will be counted as well.
\param core core id
\return State of counters in the core
*/
CoreCounterState getCoreCounterState(uint32 core);
/*! \brief Reads number of logical cores in the system
\return Number of logical cores in the system
*/
uint32 getNumCores() const;
/*! \brief Reads number of online logical cores in the system
\return Number of online logical cores in the system
*/
uint32 getNumOnlineCores() const;
/*! \brief Reads number of sockets (CPUs) in the system
\return Number of sockets in the system
*/
uint32 getNumSockets() const;
/*! \brief Reads number of online sockets (CPUs) in the system
\return Number of online sockets in the system
*/
uint32 getNumOnlineSockets() const;
/*! \brief Reads how many hardware threads has a physical core
"Hardware thread" is a logical core in a different terminology.
If Intel(r) Hyperthreading(tm) is enabled then this function returns 2.
\return Number of hardware threads per physical core
*/
uint32 getThreadsPerCore() const;
/*! \brief Checks if SMT (HyperThreading) is enabled.
\return true iff SMT (HyperThreading) is enabled.
*/
bool getSMT() const; // returns true iff SMT ("Hyperthreading") is on
/*! \brief Reads the nominal core frequency
\return Nominal frequency in Hz
*/
uint64 getNominalFrequency() const; // in Hz
/*! \brief runs CPUID.0xF.0x01 to get the L3 up scaling factor to calculate L3 Occupancy
* Scaling factor is returned in EBX register after running the CPU instruction
* \return L3 up scaling factor
*/
uint32 getL3ScalingFactor() const;
/*! \brief runs CPUID.0xB.0x01 to get maximum logical cores (including SMT) per socket.
* max_lcores_per_socket is returned in EBX[15:0]. Compare this value with number of cores per socket
* detected in the system to see if some cores are offlined
* \return true iff max_lcores_per_socket == number of cores per socket detected
*/
bool isSomeCoreOfflined();
//! \brief Identifiers of supported CPU models
enum SupportedCPUModels
{
NEHALEM_EP = 26,
NEHALEM = 30,
ATOM = 28,
ATOM_2 = 53,
ATOM_CENTERTON = 54,
ATOM_BAYTRAIL = 55,
ATOM_AVOTON = 77,
ATOM_CHERRYTRAIL = 76,
ATOM_APOLLO_LAKE = 92,
ATOM_DENVERTON = 95,
CLARKDALE = 37,
WESTMERE_EP = 44,
NEHALEM_EX = 46,
WESTMERE_EX = 47,
SANDY_BRIDGE = 42,
JAKETOWN = 45,
IVY_BRIDGE = 58,
HASWELL = 60,
HASWELL_ULT = 69,
HASWELL_2 = 70,
IVYTOWN = 62,
HASWELLX = 63,
BROADWELL = 61,
BROADWELL_XEON_E3 = 71,
BDX_DE = 86,
SKL_UY = 78,
KBL = 158,
KBL_1 = 142,
BDX = 79,
KNL = 87,
SKL = 94,
SKX = 85,
END_OF_MODEL_LIST = 0x0ffff
};
//! \brief Reads CPU model id
//! \return CPU model ID
uint32 getCPUModel() const { return (uint32)cpu_model; }
//! \brief Reads original CPU model id
//! \return CPU model ID
uint32 getOriginalCPUModel() const { return (uint32)original_cpu_model; }
//! \brief Reads CPU stepping id
//! \return CPU stepping ID
uint32 getCPUStepping() const { return (uint32)cpu_stepping; }
//! \brief Determines physical thread of given processor ID within a core
//! \param os_id processor identifier
//! \return physical thread identifier
int32 getThreadId(uint32 os_id) const { return (int32)topology[os_id].thread_id; }
//! \brief Determines physical core of given processor ID within a socket
//! \param os_id processor identifier
//! \return physical core identifier
int32 getCoreId(uint32 os_id) const { return (int32)topology[os_id].core_id; }
//! \brief Determines physical tile (cores sharing L2 cache) of given processor ID
//! \param os_id processor identifier
//! \return physical tile identifier
int32 getTileId(uint32 os_id) const { return (int32)topology[os_id].tile_id; }
//! \brief Determines socket of given core
//! \param core_id core identifier
//! \return socket identifier
int32 getSocketId(uint32 core_id) const { return (int32)topology[core_id].socket; }
//! \brief Returns the number of Intel(r) Quick Path Interconnect(tm) links per socket
//! \return number of QPI links per socket
uint64 getQPILinksPerSocket() const
{
switch (cpu_model)
{
case NEHALEM_EP:
case WESTMERE_EP:
case CLARKDALE:
if (num_sockets == 2)
return 2;
else
return 1;
case NEHALEM_EX:
case WESTMERE_EX:
return 4;
case JAKETOWN:
case IVYTOWN:
case HASWELLX:
case BDX_DE:
case BDX:
case SKX:
return (server_pcicfg_uncore.size() && server_pcicfg_uncore[0].get()) ? (server_pcicfg_uncore[0]->getNumQPIPorts()) : 0;
}
return 0;
}
//! \brief Returns the number of detected integrated memory controllers per socket
uint32 getMCPerSocket() const
{
switch (cpu_model)
{
case NEHALEM_EP:
case WESTMERE_EP:
case CLARKDALE:
return 1;
case NEHALEM_EX:
case WESTMERE_EX:
return 2;
case JAKETOWN:
case IVYTOWN:
case HASWELLX:
case BDX_DE:
case SKX:
case BDX:
case KNL:
return (server_pcicfg_uncore.size() && server_pcicfg_uncore[0].get()) ? (server_pcicfg_uncore[0]->getNumMC()) : 0;
}
return 0;
}
//! \brief Returns the total number of detected memory channels on all integrated memory controllers per socket
size_t getMCChannelsPerSocket() const
{
switch (cpu_model)
{
case NEHALEM_EP:
case WESTMERE_EP:
case CLARKDALE:
return 3;
case NEHALEM_EX:
case WESTMERE_EX:
return 4;
case JAKETOWN:
case IVYTOWN:
case HASWELLX:
case BDX_DE:
case SKX:
case BDX:
case KNL:
return (server_pcicfg_uncore.size() && server_pcicfg_uncore[0].get()) ? (server_pcicfg_uncore[0]->getNumMCChannels()) : 0;
}
return 0;
}
//! \brief Returns the total number of detected memory channels on all integrated memory controllers per socket
size_t getEDCChannelsPerSocket() const
{
switch (cpu_model)
{
case KNL:
return (server_pcicfg_uncore.size() && server_pcicfg_uncore[0].get()) ? (server_pcicfg_uncore[0]->getNumEDCChannels()) : 0;
}
return 0;
}
//! \brief Returns the max number of instructions per cycle
//! \return max number of instructions per cycle
uint32 getMaxIPC() const
{
switch (cpu_model)
{
case NEHALEM_EP:
case WESTMERE_EP:
case NEHALEM_EX:
case WESTMERE_EX:
case CLARKDALE:
case SANDY_BRIDGE:
case JAKETOWN:
case IVYTOWN:
case IVY_BRIDGE:
case HASWELL:
case HASWELLX:
case BROADWELL:
case BDX_DE:
case BDX:
case SKL:
case KBL:
case SKX:
return 4;
case ATOM:
case KNL: