aboutsummaryrefslogtreecommitdiffstats
path: root/einj_mem_uc.c
blob: 7978674203336645c3faeab30be932d6f69eb3aa (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
// SPDX-License-Identifier: GPL-2.0

/*
 * Copyright (C) 2015 Intel Corporation
 * Author: Tony Luck
 *
 * This software may be redistributed and/or modified under the terms of
 * the GNU General Public License ("GPL") version 2 only as published by the
 * Free Software Foundation.
 */

#include <fcntl.h>
#include <time.h>
#include <sys/time.h>
#include <setjmp.h>
#include <signal.h>
#define _GNU_SOURCE 1
#define __USE_GNU 1
#include <sched.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <pthread.h>
#include <sys/wait.h>
#include "einj.h"

#ifndef MAP_HUGETLB
#define MAP_HUGETLB 0x40000
#endif

char *progname;
long pagesize;
int Sflag;

unsigned long long vtop(unsigned long long addr, pid_t pid);
extern void proc_cpuinfo(int *nsockets, int *ncpus, char *model, int *modelnum, int **apicmap);
extern void proc_interrupts(long *nmce, long *ncmci);
extern void do_memcpy(void *dst, void *src, int cnt);
static void show_help(void);

static int nsockets, ncpus, lcpus_persocket;
static int force_flag;
static int cmci_skip_flag;
static int all_flag;
static int *apicmap;
static int child_process;

#define	CACHE_LINE_SIZE	64
#define	DOUBLE_INJECT_OFFSET (pagesize / 4)

/*
 * Vendor extensions for platform specific operations
 */
struct vendor_error_type_extension {
	int32_t	length;
	int32_t	pcie_sbdf;
	int16_t	vendor_id;
	int16_t	device_id;
	int8_t	rev_id;
	int8_t	reserved[3];
};

static void inject_double_uc(unsigned long long addr, void *vaddr, int notrigger)
{
	PRINT_INJECTING;

	if (Sflag) {
		vaddr = (void *)((long)vaddr & ~(pagesize - 1));
		madvise(vaddr, pagesize, MADV_HWPOISON);
		return;
	}

	wfile(EINJ_ETYPE, 0x10);
	wfile(EINJ_ADDR, addr);
	wfile(EINJ_MASK, ~0x0ul);
	wfile(EINJ_FLAGS, 2);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);

	wfile(EINJ_ADDR, vtop((unsigned long long)(vaddr + DOUBLE_INJECT_OFFSET), getpid()));
	wfile(EINJ_DOIT, 1);
}

static void inject_core_ce(unsigned long long addr, void *vaddr, int notrigger)
{
	unsigned int cpu;

	PRINT_INJECTING;
	cpu = sched_getcpu();
	wfile(EINJ_ETYPE, 0x1);
	wfile(EINJ_APIC, cpu);
	wfile(EINJ_FLAGS, 1);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_core_non_fatal(unsigned long long addr, void *vaddr, int notrigger)
{
	unsigned int cpu;

	PRINT_INJECTING;
	cpu = sched_getcpu();
	wfile(EINJ_ETYPE, 0x2);
	wfile(EINJ_APIC, cpu);
	wfile(EINJ_FLAGS, 1);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_core_fatal(unsigned long long addr, void *vaddr, int notrigger)
{
	unsigned int cpu;

	PRINT_INJECTING;
	cpu = sched_getcpu();
	wfile(EINJ_ETYPE, 0x4);
	wfile(EINJ_APIC, cpu);
	wfile(EINJ_FLAGS, 1);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

#ifdef __x86_64__
static void inject_llc(unsigned long long addr, void *vaddr, int notrigger)
{
	unsigned cpu;

	PRINT_INJECTING;
	cpu = sched_getcpu();
	wfile(EINJ_ETYPE, 0x2);
	wfile(EINJ_ADDR, addr);
	wfile(EINJ_MASK, ~0x0ul);
	wfile(EINJ_APIC, apicmap[cpu]);
	wfile(EINJ_FLAGS, 3);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}
#elif __aarch64__
static void inject_llc(unsigned long long addr, void *vaddr, int notrigger)
{
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x400);
	wfile(EINJ_MASK, 0x01);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}


static void inject_cmn_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x800);
	wfile(EINJ_MASK, 0x01);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_gic_ce(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x200);
	wfile(EINJ_MASK, 0x02);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_gic_non_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x400);
	wfile(EINJ_MASK, 0x02);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tcu_ce(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x200);
	wfile(EINJ_MASK, 0x03);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tcu_non_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x400);
	wfile(EINJ_MASK, 0x03);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tcu_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x800);
	wfile(EINJ_MASK, 0x03);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tbu_ce(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x200);
	wfile(EINJ_MASK, 0x04);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tbu_non_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x400);
	wfile(EINJ_MASK, 0x04);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}

static void inject_smmu_tbu_fatal(unsigned long long addr, void *vaddr, int notrigger) {
	PRINT_INJECTING;
	wfile(EINJ_ETYPE, 0x800);
	wfile(EINJ_MASK, 0x04);
	wfile(EINJ_FLAGS, 0x01);
	wfile(EINJ_NOTRIGGER, notrigger);
	wfile(EINJ_DOIT, 1);
}
#endif



#ifdef __x86_64__
static void check_configuration(void)
{
	char	model[512];
	int	modelnum;

	if (!is_privileged() || !is_einj_support())
		exit(1);

	model[0] = '\0';
	proc_cpuinfo(&nsockets, &ncpus, model, &modelnum, &apicmap);
	if (nsockets == 0 || ncpus == 0) {
		fprintf(stderr, "%s: could not find number of sockets/cpus\n", progname);
		exit(1);
	}
	if (ncpus % nsockets) {
		fprintf(stderr, "%s: strange topology. Are all cpus online?\n", progname);
		exit(1);
	}
	lcpus_persocket = ncpus / nsockets;
}
#elif __aarch64__

static void check_configuration(void)
{
	if (!is_privileged() || !is_einj_support())
		exit(1);
}
#endif

#define REP9(stmt) stmt;stmt;stmt;stmt;stmt;stmt;stmt;stmt;stmt

volatile int vol;

int dosums(void)
{
	vol = 0;
	REP9(REP9(REP9(vol++)));
	return vol;
}

#define MB(n)	((n) * 1024 * 1024)

static void *thp_data_alloc(void)
{
	char	*p = malloc(MB(128));
	int	i;

	if (p == NULL) {
		fprintf(stderr, "%s: cannot allocate memory\n", progname);
		exit(1);
	}
	srandom(getpid() * time(NULL));
	for (i = 0; i < MB(128); i++)
		p[i] = random();
	return p + MB(64);
}

int get_huge_pagesize(void)
{
	FILE *fp;
	char *line = NULL;
	size_t linelen = 0;
	int hpagesize = 0;
	if ((fp = fopen("/proc/meminfo", "r")) == NULL) {
		fprintf(stderr, "open /proc/meminfo");
		exit(1);
	}
	while (getline(&line, &linelen, fp) > 0) {
		if (sscanf(line, "Hugepagesize: %d kB", &hpagesize) >= 1)
			break;
	}
	free(line);
	fclose(fp);
	return hpagesize * 1024;
}

static void *hugetlb_alloc(void)
{
	int	HPS = get_huge_pagesize();
	char	*p = mmap(NULL, HPS, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON|MAP_HUGETLB, -1, 0);
	int	i;

	if (p == MAP_FAILED) {
		fprintf(stderr, "%s: cannot allocate memory\n", progname);
		exit(1);
	}
	srandom(getpid() * time(NULL));
	for (i = 0; i < HPS; i++)
		p[i] = random();
	return p + HPS / 4;
}

static void *data_alloc_common(int flag)
{
	char	*p = mmap(NULL, pagesize, PROT_READ|PROT_WRITE, flag, -1, 0);
	int	i;

	if (p == NULL) {
		fprintf(stderr, "%s: cannot allocate memory\n", progname);
		exit(1);
	}
	srandom(getpid() * time(NULL));
	for (i = 0; i < pagesize; i++)
		p[i] = random();
	return p + pagesize / 4;
}

static void *data_alloc(void)
{
	return data_alloc_common(MAP_SHARED|MAP_ANON);
}

static void *data_alloc_private(void)
{
	return data_alloc_common(MAP_PRIVATE|MAP_ANON);
}

static FILE *pcfile;

static void *map_file_alloc(void)
{
	char c, *p;
	int i;

	pcfile = tmpfile();
	for (i = 0; i < pagesize; i++) {
		c = random();
		fputc(c, pcfile);
	}
	fflush(pcfile);

	p = mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_SHARED, fileno(pcfile), 0);
	if (p == NULL) {
		fprintf(stderr, "%s: cannot mmap tmpfile\n", progname);
		exit(1);
	}
	*p = random();

	return p + pagesize / 4;
}

static void *mlock_data_alloc(void)
{
	char	*p = mmap(NULL, pagesize, PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0);
	int	i;

	if (p == NULL) {
		fprintf(stderr, "%s: cannot allocate memory\n", progname);
		exit(1);
	}
	srandom(getpid() * time(NULL));
	for (i = 0; i < pagesize; i++)
		p[i] = random();
	if (mlock(p, pagesize) == -1) {
		fprintf(stderr, "%s: cannot mlock(2) memory\n", progname);
		exit(1);
	}
	return p + pagesize / 4;
}

static void *instr_alloc(void)
{
	char	*p = (char *)dosums;

	p += 2 * pagesize;

	/*pre-load the dosum memory page to prevent vtop conversion failure*/
	dosums();

	return (void *)((long)p & ~(pagesize - 1));
}

/*
 * parameters to the single and write tests.
 */
int trigger_offset = 0;	/* where to hit after the poison addr */

int trigger_single(char *addr)
{
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	return target[0];
}

int trigger_double(char *addr)
{
	PRINT_TRIGGERING;
	return addr[0] + addr[1];
}

int trigger_split(char *addr)
{
	long *a = (long *)(addr - 1);

	PRINT_TRIGGERING;
	return a[0];
}

int trigger_write(char *addr)
{
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	target[0] = 'a';
	return 0;
}

#ifdef __aarch64__
#define __put_mem_asm(store, reg, x, addr)				\
	asm volatile(							\
	store "	" reg "0, [%1]\n"					\
	:								\
	: "r" (x), "r" (addr))

int trigger_write_byte(char *addr)
{
	int8_t __pu_val = 0x1E;
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	__put_mem_asm("strb", "%w", __pu_val, target);

	return 0;
}

int trigger_write_word(char *addr)
{
	int16_t __pu_val = 0x1EFF;
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	__put_mem_asm("strh", "%w", __pu_val, target);

	return 0;
}

int trigger_write_dword(char *addr)
{
	int32_t __pu_val = 0x1FFFEEEE;
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	__put_mem_asm("str", "%w", __pu_val, target);
	return 0;
}

int trigger_write_qword(char *addr)
{
	int64_t __pu_val = 0x1EEEFFFFFEEEE;
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	__put_mem_asm("str", "%x", __pu_val, target);
	return 0;
}
#endif

int thread(char *addr)
{
	printf(">> trigger_thread\n");

	return addr[0];
}

int trigger_thread(char *addr)
{
	unsigned long ret;
	pthread_t id1, id2;

	ret = pthread_create(&id1, NULL, (void*)thread, addr);
	if (ret != 0) {
		printf("create pthread error\n");
		exit(1);
	}

	ret = pthread_create(&id2, NULL, (void*)thread, addr);
	if (ret != 0) {
		printf("create pthread error\n");
		exit(1);
	}

	pthread_join(id1, NULL);
	pthread_join(id2, NULL);

	return 0;
}

int trigger_share(char *addr)
{
	int pid, status;
	char *p;

	switch (pid = fork()) {
	case -1:
		fprintf(stderr, "%s: fork failed\n", progname);
		return -1;
	case 0:
		/* mmap share memory */
		p = mmap(NULL, pagesize, PROT_READ, MAP_SHARED, fileno(pcfile), 0);
		if (p == NULL) {
			fprintf(stderr, "%s: cannot mmap sharefile\n", progname);
			exit(1);
		}

		PRINT_TRIGGERING;
		return *(p + pagesize / 4);
	}

	while (wait(&status) != pid)
		;

	PRINT_TRIGGERING;
	return addr[0];
}

int trigger_overflow(char *addr)
{
	char *target = addr + trigger_offset;

	PRINT_TRIGGERING;
	return target[0] + (target + DOUBLE_INJECT_OFFSET)[0];
}

/*
 * parameters to the memcpy and copyin tests.
 */
int memcpy_runup = 0;	/* how much to copy before hitting poison */
int memcpy_size = 512;	/* Total amount to copy */
int memcpy_align = 0;	/* Relative alignment of src/dst */

/* argument is "runup:size:align" */
void parse_memcpy(char *arg)
{
	char *endp;

	memcpy_runup = strtol(arg, &endp, 0);
	if (*endp != ':')
		show_help();
	memcpy_size = strtol(endp + 1, &endp, 0);
	if (*endp != ':')
		show_help();
	memcpy_align = strtol(endp + 1, &endp, 0);
	if (*endp != '\0')
		show_help();
	if (memcpy_runup < 0 || memcpy_runup > pagesize / 4) {
		fprintf(stderr, "%s: runup out of range\n", progname);
		exit(1);
	}
	if (memcpy_size < 0 || memcpy_size > pagesize / 4) {
		fprintf(stderr, "%s: size out of range\n", progname);
		exit(1);
	}
	if (memcpy_runup > memcpy_size) {
		fprintf(stderr, "%s: runup must be less than size\n", progname);
		exit(1);
	}
	if (memcpy_align < 0 || memcpy_align >= CACHE_LINE_SIZE) {
		fprintf(stderr, "%s: bad alignment\n", progname);
		exit(1);
	}
}

int trigger_memcpy(char *addr)
{
	char *src = addr - memcpy_runup;
	char *dst = addr + pagesize / 2;

	PRINT_TRIGGERING;
	dst -= memcpy_align;
	do_memcpy(dst, src, memcpy_size);
	return 0;
}

static int copyin_fd = -1;

int trigger_copyin(char *addr)
{
	int	ret;
	char	filename[] = "/tmp/einj-XXXXXX";

	if ((copyin_fd = mkstemp(filename)) == -1) {
		fprintf(stderr, "%s: couldn't make temp file\n", progname);
		return -1;
	}
	(void)unlink(filename);
	PRINT_TRIGGERING;
	if ((ret = write(copyin_fd, addr - memcpy_runup, memcpy_size)) != memcpy_size) {
		if (ret == -1)
			fprintf(stderr, "%s: couldn't write temp file (errno=%d)\n", progname, errno);
		else
			fprintf(stderr, "%s: short (%d bytes) write to temp file\n", progname, ret);
	}

	return 0;
}

int trigger_copyout(char *addr)
{
	char *buf = malloc(pagesize);
	int ret;

	if (buf == NULL) {
		fprintf(stderr, "%s: couldn't allocate memory\n", progname);
		return -1;
	}
	rewind(pcfile);
	PRINT_TRIGGERING;
	ret = fread(buf, 1, pagesize, pcfile);
	fprintf(stderr, "%s: read returned %d\n", progname, ret);

	return 0;
}

int trigger_copy_on_write(char *addr)
{
	int pid, status;

	switch (pid = fork()) {
	case -1:
		fprintf(stderr, "%s: fork failed\n", progname);
		return -1;
	case 0:
		child_process = 1;
		/* force kernel to copy this page */
		PRINT_TRIGGERING;
		*addr = '*';
		exit(0);
	}

	fprintf(stderr, "%s: COW parent waiting for pid=%d\n", progname, pid);
	while (wait(&status) != pid)
		;

	PRINT_TRIGGERING;
	return addr[0];
}

int trigger_patrol(char *addr)
{
	PRINT_TRIGGERING;
	sleep(1);
}

#ifdef __x86_64__
int trigger_llc(char *addr)
{
	PRINT_TRIGGERING;
	asm volatile("clflush %0" : "+m" (*addr));
}

int trigger_prefetch(char *addr)
{
	PRINT_TRIGGERING;
	__builtin_prefetch(addr, 0, 3);
	sleep(5);
}
#elif __aarch64__
int trigger_llc(char *addr)
{
	asm volatile("dc civac, %0" : : "r" (addr) : "memory");
}

int trigger_prefetch(char *addr)
{
	PRINT_TRIGGERING;
	asm volatile("prfm pldl1keep, %a0\n" : : "p" (addr));
	sleep(5);
}
#endif

int trigger_instr(char *addr)
{
	int ret;

	PRINT_TRIGGERING;
	ret = dosums();

	if (ret != 729)
		printf("Corruption during instruction fault recovery (%d)\n", ret);

	return ret;
}

static int futex(int *uaddr, int futex_op, int val,
		 const struct timespec *timeout, int *uaddr2, int val3)
{
	return syscall(SYS_futex, uaddr, futex_op, val, timeout, uaddr, val3);
}

int trigger_futex(char *addr)
{
	int ret;

	PRINT_TRIGGERING;
	ret = futex((int *)addr, FUTEX_WAIT, 0, NULL, NULL, 0);
	if (ret == -1)
		printf("futex returned with errno=%d\n", errno);
	else
		printf("futex return %d\n", ret);

	return ret;
}

/* attributes of the test and which events will follow our trigger */
#define	F_MCE		1
#define	F_CMCI		2
#define F_SIGBUS	4
#define	F_FATAL		8
#define F_EITHER	16
#define F_LONGWAIT	32

struct test {
	char	*testname;
	char	*testhelp;
	void	*(*alloc)(void);
	void	(*inject)(unsigned long long, void *, int);
	int	notrigger;
	int	(*trigger)(char *);
	int	flags;
} tests[] = {
	{
		"single", "Single read in pipeline to target address, generates SRAR machine check",
		data_alloc, inject_mem_uc, 1, trigger_single, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"double", "Double read in pipeline to target address, generates SRAR machine check",
		data_alloc, inject_mem_uc, 1, trigger_double, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"split", "Unaligned read crosses cacheline from good to bad. Probably fatal",
		data_alloc, inject_mem_uc, 1, trigger_split, F_MCE|F_CMCI|F_SIGBUS|F_FATAL,
	},
	{
		"THP", "Try to inject in transparent huge page, generates SRAR machine check",
		thp_data_alloc, inject_mem_uc, 1, trigger_single, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"hugetlb", "Try to inject in hugetlb page, generates SRAR machine check",
		hugetlb_alloc, inject_mem_uc, 1, trigger_single, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"store", "Write to target address. Should generate a UCNA/CMCI",
		data_alloc, inject_mem_uc, 1, trigger_write, F_CMCI,
	},
#ifdef __aarch64__
	{
		"cmn_non_fatal", "CMN SLC Data RAM DE. Should generate a UCNA/CMCI",
		data_alloc, inject_llc, 1, trigger_single, F_CMCI,
	},
	{
		"cmn_fatal", "CMN SLC Data RAM UE. Should fatal",
		data_alloc, inject_cmn_fatal, 1, trigger_single, F_FATAL,
	},
	{
		"gic_ce", "GIC corrected error. Should generate a CMCI",
		data_alloc, inject_gic_ce, 1, trigger_single, F_CMCI,
	},
	{
		"gic_non_fatal", "GIC deferred error",
		data_alloc, inject_gic_non_fatal, 1, trigger_single, F_CMCI,
	},
	{
		"smmu_tcu_ce", "SMMU TCU corrected error. Should generate a UCNA/CMCI",
		data_alloc, inject_smmu_tcu_ce, 1, trigger_single, F_CMCI,
	},
	{
		"smmu_tcu_non_fatal", "SMMU TCU deferred error. Should generate a UCNA/CMCI",
		data_alloc, inject_smmu_tcu_non_fatal, 1, trigger_single, F_CMCI,
	},
	{
		"smmu_tcu_fatal", "SMMU TCU uncorrected error. Should fatal",
		data_alloc, inject_smmu_tcu_fatal, 1, trigger_single, F_FATAL,
	},
	{
		"smmu_tbu_ce", "SMMU TBU corrected error. Should generate a UCNA/CMCI",
		data_alloc, inject_smmu_tbu_ce, 1, trigger_single, F_CMCI,
	},
	{
		"smmu_tbu_non_fatal", "SMMU TBU deferred error. Should generate a UCNA/CMCI",
		data_alloc, inject_smmu_tbu_non_fatal, 1, trigger_single, F_CMCI,
	},
	{
		"smmu_tbu_fatal", "SMMU TBU uncorrected error. Should fatal",
		data_alloc, inject_smmu_tbu_fatal, 1, trigger_single, F_FATAL,
	},
	{
		"strbyte", "Write to target address. Should generate a UCNA/CMCI",
		data_alloc, inject_mem_uc, 1, trigger_write_byte, F_CMCI,
	},
	{
		"strword", "Write to target address. Should generate a UCNA/CMCI",
		data_alloc, inject_mem_uc, 1, trigger_write_word, F_CMCI,
	},
	{
		"strdword", "Write to target address. Should generate a UCNA/CMCI",
		data_alloc, inject_mem_uc, 1, trigger_write_dword, F_CMCI,
	},
	{
		"strqword", "Write to target address. Should generate a UCNA/CMCI",
		data_alloc, inject_mem_uc, 1, trigger_write_qword, F_CMCI,
	},
#endif
	{
		"prefetch", "Prefetch data into L1 cache. Should generate CMCI",
		data_alloc, inject_mem_uc, 1, trigger_prefetch, F_CMCI,
	},
	{
		"memcpy", "Streaming read from target address. Probably fatal",
		data_alloc, inject_mem_uc, 1, trigger_memcpy, F_MCE|F_CMCI|F_SIGBUS|F_FATAL,
	},
	{
		"instr", "Instruction fetch. Generates SRAR that OS should transparently fix",
		instr_alloc, inject_mem_uc, 1, trigger_instr, F_MCE|F_CMCI,
	},
	{
		"patrol", "Patrol scrubber, generates SRAO machine check",
		data_alloc, inject_mem_uc, 0, trigger_patrol, F_EITHER|F_LONGWAIT,
	},
	{
		"thread", "Single read by two threads to target address at the same time, generates SRAR machine check",
		data_alloc, inject_mem_uc, 1, trigger_thread, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"share", "Share memory is read by two tasks to target address, generates SRAR machine check",
		map_file_alloc, inject_mem_uc, 1, trigger_share, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"overflow", "Read to two target addresses at the same time, Probably fatal",
		data_alloc, inject_double_uc, 1, trigger_overflow, F_MCE|F_CMCI|F_SIGBUS|F_FATAL,
	},
	{
		"llc", "Cache write-back, generates SRAO machine check",
		data_alloc, inject_llc, 1, trigger_llc, F_MCE,
	},
	{
		"copyin", "Kernel copies data from user. Probably fatal",
		data_alloc, inject_mem_uc, 1, trigger_copyin, F_MCE|F_CMCI|F_FATAL,
	},
	{
		"copyout", "Kernel copies data to user. Probably fatal",
		map_file_alloc, inject_mem_uc, 1, trigger_copyout, F_MCE|F_CMCI|F_SIGBUS|F_FATAL,
	},
	{
		"copy-on-write", "Kernel copies user page. Probably fatal",
		data_alloc_private, inject_mem_uc, 1, trigger_copy_on_write, F_MCE|F_CMCI|F_SIGBUS|F_FATAL,
	},
	{
		"futex", "Kernel access to futex(2). Probably fatal",
		data_alloc, inject_mem_uc, 1, trigger_futex, F_MCE|F_CMCI|F_FATAL,
	},
	{
		"mlock", "mlock target page then inject/read to generates SRAR machine check",
		mlock_data_alloc, inject_mem_uc, 1, trigger_single, F_MCE|F_CMCI|F_SIGBUS,
	},
	{
		"core_ce", "Core corrected error",
		data_alloc, inject_core_ce, 1, trigger_single, F_CMCI,
	},
	{
		"core_non_fatal", "Core deferred error",
		data_alloc, inject_core_non_fatal, 1, trigger_single, F_CMCI,
	},
	{
		"core_fatal", "Core uncorrected error. Should fatal",
		data_alloc, inject_core_fatal, 1, trigger_single, F_CMCI|F_FATAL,
	},
	{ NULL }
};

static void show_help(void)
{
	struct test *t;

	printf("Usage: %s [-a][-c count][-d delay][-f][-i][j][k] [-m runup:size:align][testname]\n", progname);
	printf("  %-8s %-5s %s\n", "Testname", "Fatal", "Description");
	for (t = tests; t->testname; t++)
		printf("  %-8s %-5s %s\n", t->testname,
			(t->flags & F_FATAL) ? "YES" : "no",
			t->testhelp);
	exit(0);
}

static struct test *lookup_test(char *s)
{
	struct test *t;

	for (t = tests; t->testname; t++)
		if (strcmp(s, t->testname) == 0)
			return t;
	fprintf(stderr, "%s: unknown test '%s'\n", progname, s);
	exit(1);
}

static struct test *next_test(struct test *t)
{
	t++;
	if (t->testname == NULL)
		t = tests;
	return t;
}

static jmp_buf env;

static void recover(int sig, siginfo_t *si, void *v)
{
	printf("signal %d code %d addr %p\n", sig, si->si_code, si->si_addr);
	siglongjmp(env, 1);
}

struct sigaction recover_act = {
	.sa_sigaction = recover,
	.sa_flags = SA_SIGINFO,
};

void kick_by_file(struct test *t, char *addr) {
	const char *trigger = "./trigger_start";
	const char *trigger_flag = "trigger";
	char trigger_buf[16];
	int count = 64*3;
	int fd;
	errno = 0;

	if (unlink(trigger) < 0 && errno != ENOENT) {
		fprintf(stderr, "fail to remove trigger file\n");
		exit(1);
	}

	memset(trigger_buf, 0, sizeof(trigger_buf));
	while (count--) {
		if ((fd = open(trigger, O_RDONLY)) < 0) {
			sleep(1);
			continue;
		}
		if (read(fd, trigger_buf, sizeof(trigger_buf)) > 0 &&
			strstr(trigger_buf, trigger_flag) != NULL) {
			break;
		}
		sleep(1);
	}

	/* trigger now */
	t->trigger(addr);
}

static int cmci_is_disabled(void)
{
	FILE *fp = popen("grep -c mce=no_cmci /proc/cmdline", "r");
	int disabled = 0;

	if (fp) {
		fscanf(fp, "%d", &disabled);
		pclose(fp);
	}

	return disabled;
}

int main(int argc, char **argv)
{
	int c, i;
	int	count = 1, kick = 0, inject_skip_flag = 0;
	double	delay = 1.0;
	struct test *t;
	void	*vaddr;
	long long paddr;
	pid_t pid;
#ifdef __x86_64__
	int	cmci_wait_count = 0;
	int	either;
	long	b_mce, b_cmci, a_mce, a_cmci;
	struct timeval t1, t2;
#endif

	progname = argv[0];
	pagesize = getpagesize();
	pid = getpid();

	while ((c = getopt(argc, argv, "ac:d:fhijkm:z:S")) != -1) switch (c) {
	case 'a':
		all_flag = 1;
		break;
	case 'c':
		count = strtol(optarg, NULL, 0);
		break;
	case 'd':
		delay = strtod(optarg, NULL);
		break;
	case 'f':
		force_flag = 1;
		break;
	case 'i':
		cmci_skip_flag = 1;
		break;
	case 'j':
		inject_skip_flag = 1;
		break;
	case 'k':
		kick = 1;
		break;
	case 'm':
		parse_memcpy(optarg);
		break;
	case 'z':
		trigger_offset = strtod(optarg, NULL);
		break;
	case 'S':
		Sflag = 1;
		break;
	case 'h': case '?':
		show_help();
		break;
	}

	if (Sflag == 0 && inject_skip_flag == 0)
		check_configuration();

	if (optind < argc)
		t = lookup_test(argv[optind]);
	else
		t = tests;

	if (cmci_is_disabled())
		t->flags &= ~F_CMCI;

	if ((t->flags & F_FATAL) && !force_flag) {
		fprintf(stderr, "%s: selected test may be fatal. Use '-f' flag if you really want to do this\n", progname);
		exit(1);
	}

	sigaction(SIGBUS, &recover_act, NULL);

	for (i = 0; i < count; i++) {
		vaddr = t->alloc();
		paddr = vtop((long long)vaddr, pid);
		printf("%d: %-8s vaddr = %p paddr = %llx\n", i, t->testname, vaddr, paddr);
#ifdef __x86_64__
		cmci_wait_count = 0;
		either = 0;
		proc_interrupts(&b_mce, &b_cmci);
		gettimeofday(&t1, NULL);
#endif
		if (sigsetjmp(env, 1)) {
			if ((t->flags & F_SIGBUS) == 0) {
				printf("Unexpected SIGBUS\n");
			}
		} else {
			if (!inject_skip_flag)
				t->inject(paddr, vaddr, t->notrigger);
			sleep(3);
			if (kick)
				kick_by_file(t, vaddr);
			else
				t->trigger(vaddr);
			if (t->flags & F_SIGBUS) {
				printf("Expected SIGBUS, didn't get one\n");
			}
		}

		if (copyin_fd != -1) {
			close(copyin_fd);
			copyin_fd = -1;
		}

		if (pcfile) {
			fclose(pcfile);
			pcfile = NULL;
		}

		/* if system didn't already take page offline, ask it to do so now */
		if (paddr == vtop((long long)vaddr, pid)) {
			printf("Manually take page offline\n");
			wfile("/sys/devices/system/memory/hard_offline_page", paddr);
		}

		/* Give system a chance to process on possibly deep C-state idle cpus */
		usleep(100);
#ifdef __x86_64__
		proc_interrupts(&a_mce, &a_cmci);
#endif
		if (t->flags & F_FATAL) {
			printf("Big surprise ... still running. Thought that would be fatal\n");
		}
#ifdef __x86_64__
		if (Sflag == 0 && (t->flags & (F_MCE | F_EITHER))) {
			if (a_mce == b_mce) {
				if (t->flags & F_EITHER)
					goto skip1;
				printf("Expected MCE, but none seen\n");
			} else if (a_mce == b_mce + 1) {
				printf("Saw local machine check\n");
			} else if (a_mce == b_mce + ncpus) {
				printf("Saw broadcast machine check\n");
			} else {
				printf("Unusual number of MCEs seen: %ld\n", a_mce - b_mce);
			}
			either++;
		} else {
			if (a_mce != b_mce) {
				printf("Saw %ld unexpected MCEs (%ld systemwide)\n", b_mce - a_mce, (b_mce - a_mce) / ncpus);
			}
		}
skip1:
		if (Sflag == 0 && (t->flags & (F_CMCI | F_EITHER))) {
			int maxwait = (t->flags & F_LONGWAIT) ? 20000 : 500;

			while (a_cmci < b_cmci + lcpus_persocket) {
				if (cmci_wait_count > maxwait) {
					break;
				}
				usleep(1000);
				proc_interrupts(&a_mce, &a_cmci);
				cmci_wait_count++;
			}
			if (a_cmci != b_cmci && cmci_wait_count != 0) {
				gettimeofday(&t2, NULL);
				printf("CMCIs took ~%.6f secs to be reported.\n",
					(t2.tv_sec - t1.tv_sec) +
						(t2.tv_usec - t1.tv_usec) /1.0e6);
			}
			if (a_cmci == b_cmci) {
				if (t->flags & F_EITHER)
					goto skip2;
				if (!cmci_skip_flag) {
					printf("Expected CMCI, but none seen\n");
					printf("Test failed\n");
					return 1;
				}
			} else if (!cmci_skip_flag && a_cmci < b_cmci + lcpus_persocket) {
				printf("Unusual number of CMCIs seen: %ld\n", a_cmci - b_cmci);
				printf("Test failed\n");
				return 1;
			}
			either++;
		} else {
			if (!cmci_skip_flag && a_cmci != b_cmci) {
				printf("Saw %ld unexpected CMCIs (%ld per socket)\n", a_cmci - b_cmci, (a_cmci - b_cmci) / lcpus_persocket);
				printf("Test failed\n");
				return 1;
			}
		}
skip2:
		if (t->flags & F_EITHER) switch (either) {
		case 0:
			printf("Expected CMCI or MCE, but saw neither\n");
			printf("Test failed\n");
			return 1;
		case 2:
			printf("Expected one of CMCI or MCE, but saw both\n");
			printf("Test failed\n");
			return 1;
		}

		usleep((useconds_t)(delay * 1.0e6));
		if (all_flag) {
			t = next_test(t);
			while (t->flags & F_FATAL)
				t = next_test(t);
		}
#endif
		if (child_process)
			break;
	}

	printf("Test passed\n");
	return 0;
}