-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpucounters.h
3956 lines (3439 loc) · 146 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-2020, 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)
*/
#include "version.h"
#ifndef PCM_API
#define PCM_API
#endif
#undef PCM_HA_REQUESTS_READS_ONLY
#undef PCM_DEBUG_TOPOLOGY // debug of topology enumeration routine
#undef PCM_UNCORE_PMON_BOX_CHECK_STATUS // debug only
#include "types.h"
#include "msr.h"
#include "pci.h"
#include "bw.h"
#include "width_extender.h"
#include "exceptions/unsupported_processor_exception.hpp"
#include <vector>
#include <array>
#include <limits>
#include <string>
#include <memory>
#include <map>
#include <unordered_map>
#include <string.h>
#include <assert.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
#ifdef _MSC_VER
#if _MSC_VER>= 1600
#include <intrin.h>
#endif
#endif
#include "resctrl.h"
namespace pcm {
#ifdef _MSC_VER
void PCM_API restrictDriverAccess(LPCWSTR path);
#endif
class SystemCounterState;
class SocketCounterState;
class CoreCounterState;
class BasicCounterState;
class ServerUncoreCounterState;
class PCM;
class CoreTaskQueue;
class SystemRoot;
/*
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;
int32 native_cpu_model = -1;
enum CoreType
{
Atom = 0x20,
Core = 0x40,
Invalid = -1
};
CoreType core_type = Invalid;
TopologyEntry() : os_id(-1), thread_id (-1), core_id(-1), tile_id(-1), socket(-1) { }
const char* getCoreTypeStr()
{
switch (core_type)
{
case Atom:
return "Atom";
case Core:
return "Core";
case Invalid:
return "invalid";
}
return "unknown";
}
};
class HWRegister
{
public:
virtual void operator = (uint64 val) = 0; // write operation
virtual operator uint64 () = 0; //read operation
virtual ~HWRegister() {}
};
class PCICFGRegister64 : public HWRegister
{
std::shared_ptr<PciHandleType> handle;
size_t offset;
public:
PCICFGRegister64(const std::shared_ptr<PciHandleType> & handle_, size_t offset_) :
handle(handle_),
offset(offset_)
{
}
void operator = (uint64 val) override
{
cvt_ds cvt;
cvt.ui64 = val;
handle->write32(offset, cvt.ui32.low);
handle->write32(offset + sizeof(uint32), cvt.ui32.high);
}
operator uint64 () override
{
uint64 result = 0;
handle->read64(offset, &result);
return result;
}
};
class PCICFGRegister32 : public HWRegister
{
std::shared_ptr<PciHandleType> handle;
size_t offset;
public:
PCICFGRegister32(const std::shared_ptr<PciHandleType> & handle_, size_t offset_) :
handle(handle_),
offset(offset_)
{
}
void operator = (uint64 val) override
{
handle->write32(offset, (uint32)val);
}
operator uint64 () override
{
uint32 result = 0;
handle->read32(offset, &result);
return result;
}
};
class MMIORegister64 : public HWRegister
{
std::shared_ptr<MMIORange> handle;
size_t offset;
public:
MMIORegister64(const std::shared_ptr<MMIORange> & handle_, size_t offset_) :
handle(handle_),
offset(offset_)
{
}
void operator = (uint64 val) override
{
handle->write64(offset, val);
}
operator uint64 () override
{
return handle->read64(offset);
}
};
class MMIORegister32 : public HWRegister
{
std::shared_ptr<MMIORange> handle;
size_t offset;
public:
MMIORegister32(const std::shared_ptr<MMIORange> & handle_, size_t offset_) :
handle(handle_),
offset(offset_)
{
}
void operator = (uint64 val) override
{
handle->write32(offset, (uint32)val);
}
operator uint64 () override
{
return (uint64)handle->read32(offset);
}
};
class MSRRegister : public HWRegister
{
std::shared_ptr<SafeMsrHandle> handle;
size_t offset;
public:
MSRRegister(const std::shared_ptr<SafeMsrHandle> & handle_, size_t offset_) :
handle(handle_),
offset(offset_)
{
}
void operator = (uint64 val) override
{
handle->write(offset, val);
}
operator uint64 () override
{
uint64 value = 0;
handle->read(offset, &value);
return value;
}
};
class CounterWidthExtenderRegister : public HWRegister
{
std::shared_ptr<CounterWidthExtender> handle;
public:
CounterWidthExtenderRegister(const std::shared_ptr<CounterWidthExtender> & handle_) :
handle(handle_)
{
}
void operator = (uint64 val) override
{
if (val == 0)
{
handle->reset();
}
else
{
std::cerr << "ERROR: writing non-zero values to CounterWidthExtenderRegister is not supported\n";
throw std::exception();
}
}
operator uint64 () override
{
return handle->read();;
}
};
class UncorePMU
{
typedef std::shared_ptr<HWRegister> HWRegisterPtr;
HWRegisterPtr unitControl;
public:
HWRegisterPtr counterControl[4];
HWRegisterPtr counterValue[4];
HWRegisterPtr fixedCounterControl;
HWRegisterPtr fixedCounterValue;
HWRegisterPtr filter[2];
UncorePMU(const HWRegisterPtr & unitControl_,
const HWRegisterPtr & counterControl0,
const HWRegisterPtr & counterControl1,
const HWRegisterPtr & counterControl2,
const HWRegisterPtr & counterControl3,
const HWRegisterPtr & counterValue0,
const HWRegisterPtr & counterValue1,
const HWRegisterPtr & counterValue2,
const HWRegisterPtr & counterValue3,
const HWRegisterPtr & fixedCounterControl_ = HWRegisterPtr(),
const HWRegisterPtr & fixedCounterValue_ = HWRegisterPtr(),
const HWRegisterPtr & filter0 = HWRegisterPtr(),
const HWRegisterPtr & filter1 = HWRegisterPtr()
) :
unitControl(unitControl_),
counterControl{ counterControl0, counterControl1, counterControl2, counterControl3 },
counterValue{ counterValue0, counterValue1, counterValue2, counterValue3 },
fixedCounterControl(fixedCounterControl_),
fixedCounterValue(fixedCounterValue_),
filter{ filter0 , filter1 }
{
}
UncorePMU() {}
virtual ~UncorePMU() {}
bool valid() const
{
return unitControl.get() != nullptr;
}
void writeUnitControl(const uint32 value)
{
*unitControl = value;
}
void cleanup();
void freeze(const uint32 extra);
bool initFreeze(const uint32 extra, const char* xPICheckMsg = nullptr);
void unfreeze(const uint32 extra);
void resetUnfreeze(const uint32 extra);
};
enum ServerUncoreMemoryMetrics
{
PartialWrites,
Pmem,
PmemMemoryMode,
PmemMixedMode
};
//! Object to access uncore counters in a socket/processor with microarchitecture codename SandyBridge-EP (Jaketown) or Ivytown-EP or Ivytown-EX
class ServerPCICFGUncore
{
friend class PCM;
int32 iMCbus,UPIbus,M2Mbus;
uint32 groupnr;
int32 cpu_model;
typedef std::vector<UncorePMU> UncorePMUVector;
UncorePMUVector imcPMUs;
UncorePMUVector edcPMUs;
UncorePMUVector xpiPMUs;
UncorePMUVector m3upiPMUs;
UncorePMUVector m2mPMUs;
UncorePMUVector haPMUs;
std::vector<UncorePMUVector*> allPMUs{ &imcPMUs, &edcPMUs, &xpiPMUs, &m3upiPMUs , &m2mPMUs, &haPMUs };
std::vector<uint64> qpi_speed;
std::vector<uint32> num_imc_channels; // number of memory channels in each memory controller
std::vector<std::pair<uint32, uint32> > XPIRegisterLocation; // (device, function)
std::vector<std::pair<uint32, uint32> > M3UPIRegisterLocation; // (device, function)
std::vector<std::vector< std::pair<uint32, uint32> > > MCRegisterLocation; // MCRegisterLocation[controller]: (device, function)
std::vector<std::pair<uint32, uint32> > EDCRegisterLocation; // EDCRegisterLocation: (device, function)
std::vector<std::pair<uint32, uint32> > M2MRegisterLocation; // M2MRegisterLocation: (device, function)
std::vector<std::pair<uint32, uint32> > HARegisterLocation; // HARegisterLocation: (device, function)
static std::vector<std::pair<uint32, uint32> > socket2iMCbus;
static std::vector<std::pair<uint32, uint32> > socket2UPIbus;
static std::vector<std::pair<uint32, uint32> > socket2M2Mbus;
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);
void programM2M(const uint64 * M2MCntConfig);
void programM2M();
void programHA(const uint32 * config);
void programHA();
void programXPI(const uint32 * XPICntConfig);
void programM3UPI(const uint32* M3UPICntConfig);
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();
void cleanupPMUs();
void writeAllUnitControl(const uint32 value);
void initDirect(uint32 socket_, const PCM * pcm);
void initPerf(uint32 socket_, const PCM * pcm);
void initBuses(uint32 socket_, const PCM * pcm);
void initRegisterLocations(const PCM * pcm);
uint64 getPMUCounter(std::vector<UncorePMU> & pmu, const uint32 id, const uint32 counter);
public:
enum EventPosition {
READ=0,
WRITE=1,
READ_RANK_A=0,
WRITE_RANK_A=1,
READ_RANK_B=2,
WRITE_RANK_B=3,
PARTIAL=2,
PMM_READ=2,
PMM_WRITE=3,
PMM_MM_MISS_CLEAN=2,
PMM_MM_MISS_DIRTY=3,
NM_HIT=0, // NM : Near Memory (DRAM cache) in Memory Mode
M2M_CLOCKTICKS=1
};
//! \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 reads for given controller (in cache lines)
//! \param controller controller ID/number
uint64 getImcReadsForController(uint32 controller);
//! \brief Get the number of integrated controller reads for given channels (in cache lines)
//! \param beginChannel first channel in the range
//! \param endChannel last channel + 1: the range is [beginChannel, endChannel). endChannel is not included.
uint64 getImcReadsForChannels(uint32 beginChannel, uint32 endChannel);
//! \brief Get the number of integrated controller writes (in cache lines)
uint64 getImcWrites();
//! \brief Get the number of requests to home agent (BDX/HSX only)
uint64 getHALocalRequests();
//! \brief Get the number of local requests to home agent (BDX/HSX only)
uint64 getHARequests();
//! \brief Get the number of PMM memory reads (in cache lines)
uint64 getPMMReads();
//! \brief Get the number of PMM memory writes (in cache lines)
uint64 getPMMWrites();
//! \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);
~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)
//! \brief metrics metric set (see the ServerUncoreMemoryMetrics enum)
void programServerUncoreMemoryMetrics(const ServerUncoreMemoryMetrics & metrics, const int rankA = -1, const 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 Direct read of M3UPI PMU counter (counter meaning depends on the programming: power/performance/etc)
//! \param port port number
//! \param counter counter number
uint64 getM3UPICounter(uint32 port, uint32 counter);
//! \brief Direct read of M2M counter
//! \param box box ID/number
//! \param counter counter number
uint64 getM2MCounter(uint32 box, 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 xpiPMUs.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 (uint32)num_imc_channels.size(); }
//! \brief Returns the total number of detected memory channels on all integrated memory controllers
size_t getNumMCChannels() const { return (size_t)imcPMUs.size(); }
//! \brief Returns the total number of detected memory channels on given integrated memory controller
//! \param controller controller number
size_t getNumMCChannels(const uint32 controller) const;
//! \brief Returns the total number of detected memory channels on all embedded DRAM controllers (EDC)
size_t getNumEDCChannels() const { return edcPMUs.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;
typedef std::vector<uint64> eventGroup_t;
class PerfVirtualControlRegister;
/*!
\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;
friend class Socket;
friend class ServerUncore;
friend class PerfVirtualControlRegister;
friend class Aggregator;
friend class ServerPCICFGUncore;
PCM(); // forbidden to call directly because it is a singleton
PCM(const PCM &) = delete;
PCM & operator = (const PCM &) = delete;
int32 cpu_family;
int32 cpu_model;
bool hybrid = false;
int32 cpu_stepping;
int64 cpu_microcode_level;
int32 max_cpuid;
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;
SystemRoot* systemTopology;
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;
std::vector<UncorePMU> pcuPMUs;
std::vector<std::map<int32, UncorePMU> > iioPMUs;
std::vector<UncorePMU> uboxPMUs;
double joulesPerEnergyUnit;
std::vector<std::shared_ptr<CounterWidthExtender> > energy_status;
std::vector<std::shared_ptr<CounterWidthExtender> > dram_energy_status;
std::vector<std::vector<UncorePMU> > cboPMUs;
std::vector<std::shared_ptr<CounterWidthExtender> > memory_bw_local;
std::vector<std::shared_ptr<CounterWidthExtender> > memory_bw_total;
#ifdef __linux__
Resctrl resctrl;
#endif
bool useResctrl;
std::shared_ptr<FreeRunningBWCounters> clientBW;
std::shared_ptr<CounterWidthExtender> clientImcReads;
std::shared_ptr<CounterWidthExtender> clientImcWrites;
std::shared_ptr<CounterWidthExtender> clientIoRequests;
std::vector<std::shared_ptr<ServerBW> > serverBW;
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;
bool L2CacheHitRatioAvailable;
bool L3CacheHitRatioAvailable;
bool L3CacheMissesAvailable;
bool L2CacheMissesAvailable;
bool L2CacheHitsAvailable;
bool L3CacheHitsNoSnoopAvailable;
bool L3CacheHitsSnoopAvailable;
bool L3CacheHitsAvailable;
bool forceRTMAbortMode;
std::vector<uint64> FrontendBoundSlots, BadSpeculationSlots, BackendBoundSlots, RetiringSlots, AllSlotsRaw;
bool isFixedCounterSupported(unsigned c);
bool vm = false;
bool linux_arch_perfmon = false;
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)
{
if (state == 0)
{
return true;
}
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
};
// Offsets/enumeration of IIO stacks Skylake server.
enum SkylakeIIOStacks {
SKX_IIO_CBDMA_DMI = 0,
SKX_IIO_PCIe0 = 1,
SKX_IIO_PCIe1 = 2,
SKX_IIO_PCIe2 = 3,
SKX_IIO_MCP0 = 4,
SKX_IIO_MCP1 = 5,
SKX_IIO_STACK_COUNT = 6
};
// Offsets/enumeration of IIO stacks for IceLake server.
enum IcelakeIIOStacks {
ICX_IIO_PCIe0 = 0,
ICX_IIO_PCIe1 = 1,
ICX_IIO_MCP0 = 2,
ICX_IIO_PCIe2 = 3,
ICX_IIO_PCIe3 = 4,
ICX_IIO_CBDMA_DMI = 5,
ICX_IIO_STACK_COUNT = 6
};
// Offsets/enumeration of IIO stacks for IceLake server.
enum SnowridgeIIOStacks {
SNR_IIO_QAT = 0,
SNR_IIO_CBDMA_DMI = 1,
SNR_IIO_NIS = 2,
SNR_IIO_HQM = 3,
SNR_IIO_PCIe0 = 4,
SNR_IIO_STACK_COUNT = 5
};
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 = 0, umask_value = 0;
};
/*! \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
EventSelectRegister * gpCounterHybridAtomCfg; // general purpose counters for Atom cores in hybrid processors
uint64 OffcoreResponseMsrValue[2];
uint64 LoadLatencyMsrValue, FrontendMsrValue;
static uint64 invalidMsrValue() { return ~0ULL; }
ExtendedCustomCoreEventDescription() : fixedCfg(NULL), nGPCounters(0), gpCounterCfg(nullptr), gpCounterHybridAtomCfg(nullptr), LoadLatencyMsrValue(invalidMsrValue()), FrontendMsrValue(invalidMsrValue())
{
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[PERF_MAX_CUSTOM_COUNTERS];
CustomCoreEventDescription hybridAtomEventDesc[PERF_MAX_CUSTOM_COUNTERS];
#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_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,
PERF_TOPDOWN_SLOTS_POS = PERF_GEN_EVENT_0_POS + PERF_MAX_CUSTOM_COUNTERS,
PERF_TOPDOWN_FRONTEND_POS = PERF_TOPDOWN_SLOTS_POS + 1,
PERF_TOPDOWN_BADSPEC_POS = PERF_TOPDOWN_SLOTS_POS + 2,
PERF_TOPDOWN_BACKEND_POS = PERF_TOPDOWN_SLOTS_POS + 3,
PERF_TOPDOWN_RETIRING_POS = PERF_TOPDOWN_SLOTS_POS + 4
};
std::unordered_map<int, int> perfTopDownPos;
enum {
PERF_GROUP_LEADER_COUNTER = PERF_INST_RETIRED_POS,
PERF_TOPDOWN_GROUP_LEADER_COUNTER = PERF_TOPDOWN_SLOTS_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 needToRestoreNMIWatchdog;
std::vector<std::vector<EventSelectRegister> > lastProgrammedCustomCounters;
uint32 checkCustomCoreProgramming(std::shared_ptr<SafeMsrHandle> msr);
ErrorCode programCoreCounters(int core, const PCM::ProgramMode mode, const ExtendedCustomCoreEventDescription * pExtDesc,
std::vector<EventSelectRegister> & programmedCustomCounters);
bool PMUinUse();
void cleanupPMU(const bool silent = false);
void cleanupRDT(const bool silent = false);
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(const 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 showSpecControlMSRs();
void initEnergyMonitoring();
void initUncoreObjects();
/*!
* \brief initializes each core with an RMID
*
* \returns nothing
*/
void initRDT();
/*!
* \brief Initializes RDT
*
* Initializes RDT infrastructure through resctrl Linux driver or direct MSR programming.
* For the latter: 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;
void readCoreCounterConfig(const bool complainAboutMSR = false);
void readCPUMicrocodeLevel();
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;
void programCboOpcodeFilter(const uint32 opc0, UncorePMU & pmu, const uint32 nc_, const uint32 opc1, const uint32 loc, const uint32 rem);
void initLLCReadMissLatencyEvents(uint64 * events, uint32 & opCode);
void initCHARequestEvents(uint64 * events);
void programCbo();
uint64 getCBOCounterState(const uint32 socket, const uint32 ctr_);
template <class Iterator>
static void program(UncorePMU& pmu, const Iterator& eventsBegin, const Iterator& eventsEnd, const uint32 extra)
{
if (!eventsBegin) return;
Iterator curEvent = eventsBegin;
for (int c = 0; curEvent != eventsEnd; ++c, ++curEvent)
{
auto ctrl = pmu.counterControl[c];
if (ctrl.get() != nullptr)
{
*ctrl = MC_CH_PCI_PMON_CTL_EN;
*ctrl = MC_CH_PCI_PMON_CTL_EN | *curEvent;
}
}
if (extra)
{
pmu.resetUnfreeze(extra);
}
}
void programPCU(uint32 * events, const uint64 filter);
void programUBOX(const uint64* events);
void cleanupUncorePMUs(const bool silent = false);
bool isCLX() const // Cascade Lake-SP
{
return (PCM::SKX == cpu_model) && (cpu_stepping > 4 && cpu_stepping < 8);
}
static bool isCPX(int cpu_model_, int cpu_stepping_) // Cooper Lake
{
return (PCM::SKX == cpu_model_) && (cpu_stepping_ >= 10);
}