File: mcelog.c

package info (click to toggle)
mcelog 1.0~pre3-72-gcbd4da4-1
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 808 kB
  • sloc: ansic: 6,915; sh: 471; makefile: 128
file content (1226 lines) | stat: -rw-r--r-- 28,129 bytes parent folder | download
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
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
/* Copyright (C) 2004,2005,2006 Andi Kleen, SuSE Labs.
   Copyright (C) 2008 Intel Corporation 
   Authors: Andi Kleen, Ying Huang
   Decode IA32/x86-64 machine check events in /dev/mcelog. 

   mcelog is free software; you can redistribute it and/or
   modify it under the terms of the GNU General Public
   License as published by the Free Software Foundation; version
   2.

   mcelog is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should find a copy of v2 of the GNU General Public License somewhere
   on your Linux system; if not, write to the Free Software Foundation, 
   Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */

#define _GNU_SOURCE 1
#include <sys/fcntl.h>
#include <sys/ioctl.h>
#include <asm/types.h>
#include <asm/ioctls.h>
#include <linux/limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <syslog.h>
#include <ctype.h>
#include <poll.h>
#include <time.h>
#include <getopt.h>
#include <errno.h>
#include <stddef.h>
#include <assert.h>
#include <signal.h>
#include <pwd.h>
#include "mcelog.h"
#include "paths.h"
#include "k8.h"
#include "intel.h"
#include "p4.h"
#include "dmi.h"
#include "dimm.h"
#include "tsc.h"
#include "version.h"
#include "config.h"
#include "diskdb.h"
#include "memutil.h"
#include "eventloop.h"
#include "memdb.h"
#include "server.h"
#include "trigger.h"
#include "client.h"
#include "msg.h"
#include "yellow.h"
#include "page.h"

enum cputype cputype = CPU_GENERIC;	

char *logfn = LOG_DEV_FILENAME; 

int ignore_nodev;
int filter_bogus = 1;
int cpu_forced;
static double cpumhz;
static int cpumhz_forced;
int ascii_mode;
int dump_raw_ascii;
int daemon_mode;
static char *inputfile;
char *processor_flags;
static int foreground;
int filter_memory_errors;
static struct config_cred runcred = { .uid = -1U, .gid = -1U };
static int numerrors;
static char pidfile_default[] = PID_FILE;
static char logfile_default[] = LOG_FILE;
static char *pidfile = pidfile_default;
static char *logfile;
static int debug_numerrors;

static void check_cpu(void);


static void disclaimer(void)
{
	Wprintf("Hardware event. This is not a software error.\n");
}

static char *extended_bankname(unsigned bank) 
{
	static char buf[64];
	switch (bank) { 
	case MCE_THERMAL_BANK:
		return "THERMAL EVENT";
	case MCE_TIMEOUT_BANK:
		return "Timeout waiting for exception on other CPUs";
	case K8_MCE_THRESHOLD_BASE ... K8_MCE_THRESHOLD_TOP:
		return k8_bank_name(bank);

		/* add more extended banks here */

	default:
		sprintf(buf, "Undecoded extended event %x", bank);
		return buf;
	} 
}

static char *bankname(unsigned bank) 
{ 
	static char numeric[64];
	if (bank >= MCE_EXTENDED_BANK) 
		return extended_bankname(bank);

	switch (cputype) { 
	case CPU_K8:
		return k8_bank_name(bank);
	CASE_INTEL_CPUS:
		return intel_bank_name(bank);
	/* add banks of other cpu types here */
	default:
		sprintf(numeric, "BANK %d", bank); 
		return numeric;
	}
} 

static void resolveaddr(unsigned long long addr)
{
	if (addr && do_dmi && dmi_forced)
		dmi_decodeaddr(addr);
	/* Should check for PCI resources here too */
}

static int mce_filter(struct mce *m, unsigned recordlen)
{
	if (!filter_bogus) 
		return 1;
	/* Filter out known broken MCEs */
	switch (cputype) {
	case CPU_K8:
		return mce_filter_k8(m);
		/* add more buggy CPUs here */
	CASE_INTEL_CPUS:
		return mce_filter_intel(m, recordlen);
	default:
	case CPU_GENERIC:
		return 1;
	}	
}

static void print_tsc(int cpunum, __u64 tsc, unsigned long time) 
{ 
	int ret = -1;
	char *buf = NULL;

	if (cpumhz_forced) 
		ret = decode_tsc_forced(&buf, cpumhz, tsc);
	else if (!time) 
		ret = decode_tsc_current(&buf, cpunum, cputype, cpumhz, tsc);
	Wprintf("TSC %llx %s", tsc, ret >= 0 && buf ? buf : "");
	free(buf);
}

struct cpuid1 {
	unsigned stepping : 4;
	unsigned model : 4;
	unsigned family : 4;
	unsigned type : 2;
	unsigned res1 : 2;
	unsigned ext_model : 4;
	unsigned ext_family : 8; 
	unsigned res2 : 4;
};

static void parse_cpuid(u32 cpuid, u32 *family, u32 *model)
{
	union { 
		struct cpuid1 c;
		u32 v;
	} c;

	/* Algorithm from IA32 SDM 2a 3-191 */
	c.v = cpuid;
	*family = c.c.family; 
	if (*family == 0xf) 
		*family += c.c.ext_family;
	*model = c.c.model;
	if (*family == 6 || *family == 0xf) 
		*model += c.c.ext_model << 4;
}

static char *cputype_name[] = {
	[CPU_GENERIC] = "generic CPU",
	[CPU_P6OLD] = "Intel PPro/P2/P3/old Xeon",
	[CPU_CORE2] = "Intel Core", /* 65nm and 45nm */
	[CPU_K8] = "AMD K8 and derivates",
	[CPU_P4] = "Intel P4",
	[CPU_NEHALEM] = "Intel Xeon 5500 series / Core i3/5/7 (\"Nehalem/Westmere\")",
	[CPU_DUNNINGTON] = "Intel Xeon 7400 series",
	[CPU_TULSA] = "Intel Xeon 7100 series",
	[CPU_INTEL] = "Intel generic architectural MCA",
	[CPU_XEON75XX] = "Intel Xeon 7500 series",
	[CPU_SANDY_BRIDGE] = "Sandy Bridge", /* Fill in better name */
	[CPU_SANDY_BRIDGE_EP] = "Sandy Bridge EP", /* Fill in better name */
};

static struct config_choice cpu_choices[] = {
	{ "generic", CPU_GENERIC },
	{ "p6old", CPU_P6OLD },
	{ "core2", CPU_CORE2 },
	{ "k8", CPU_K8 },
	{ "p4", CPU_P4 },
	{ "dunnington", CPU_DUNNINGTON },
	{ "xeon74xx", CPU_DUNNINGTON },
	{ "xeon7400", CPU_DUNNINGTON },
	{ "xeon5500", CPU_NEHALEM },
	{ "xeon5200", CPU_CORE2 },
	{ "xeon5000", CPU_P4 },
	{ "xeon5100", CPU_CORE2 },
	{ "xeon3100", CPU_CORE2 },
	{ "xeon3200", CPU_CORE2 },
	{ "core_i7", CPU_NEHALEM },
	{ "core_i5", CPU_NEHALEM },
	{ "core_i3", CPU_NEHALEM },
	{ "nehalem", CPU_NEHALEM },
	{ "westmere", CPU_NEHALEM },
	{ "xeon71xx", CPU_TULSA },
	{ "xeon7100", CPU_TULSA },
	{ "tulsa", CPU_TULSA },
	{ "intel", CPU_INTEL },
	{ "xeon75xx", CPU_XEON75XX },
	{ "xeon7500", CPU_XEON75XX },
	{ "xeon7200", CPU_CORE2 },
	{ "xeon7100", CPU_P4 },
	{ "sandybridge", CPU_SANDY_BRIDGE }, /* Fill in better name */
	{ "sandybridge-ep", CPU_SANDY_BRIDGE_EP }, /* Fill in better name */
	{}
};

static void print_cputypes(void)
{
	struct config_choice *c;
	fprintf(stderr, "Valid CPUs:");
	for (c = cpu_choices; c->name; c++)
		fprintf(stderr, " %s", c->name);
	fputc('\n', stderr);
}

static enum cputype lookup_cputype(char *name)
{
	struct config_choice *c;
	for (c = cpu_choices; c->name; c++) {
		if (!strcasecmp(name, c->name))
			return c->val;
	}
	fprintf(stderr, "Unknown CPU type `%s' specified\n", name);
	print_cputypes();
	exit(1);
}

static char *cpuvendor_name(u32 cpuvendor)
{
	static char *vendor[] = {
		[0] = "Intel",
		[1] = "Cyrix",
		[2] = "AMD",
		[3] = "UMC", 
		[4] = "vendor 4",
		[5] = "Centaur",
		[6] = "vendor 6",
		[7] = "Transmeta",
		[8] = "NSC"
	};
	return (cpuvendor < NELE(vendor)) ? vendor[cpuvendor] : "Unknown vendor";
}

static enum cputype setup_cpuid(u32 cpuvendor, u32 cpuid)
{
	u32 family, model;

	parse_cpuid(cpuid, &family, &model);

	switch (cpuvendor) { 
	case X86_VENDOR_INTEL:
	        return select_intel_cputype(family, model);
	case X86_VENDOR_AMD:
		if (family >= 15 && family <= 17)
			return CPU_K8;
		/* FALL THROUGH */
	default:
		Eprintf("Unknown CPU type vendor %u family %x model %x", 
			cpuvendor, family, model);
		return CPU_GENERIC;
	}
}

static void mce_cpuid(struct mce *m)
{
	static int warned;
	if (m->cpuid) {
		enum cputype t = setup_cpuid(m->cpuvendor, m->cpuid);
		if (!cpu_forced)
			cputype = t;
		else if (t != cputype && t != CPU_GENERIC && !warned) {
			Eprintf("Forced cputype %s does not match cpu type %s from mcelog\n",
				cputype_name[cputype],
				cputype_name[t]);
			warned = 1;
		}
	} else if (cputype == CPU_GENERIC && !cpu_forced) { 
		check_cpu();
	}	
}

static void mce_prepare(struct mce *m)
{
	mce_cpuid(m);
	if (!m->time)
		m->time = time(NULL);
}

static void dump_mce(struct mce *m, unsigned recordlen) 
{
	int n;
	int ismemerr = 0;
	unsigned cpu = m->extcpu ? m->extcpu : m->cpu;

	/* should not happen */
	if (!m->finished)
		Wprintf("not finished?\n");
	Wprintf("CPU %d %s ", cpu, bankname(m->bank));
	if (m->tsc)
		print_tsc(cpu, m->tsc, m->time);
	Wprintf("\n");
	if (m->ip)
		Wprintf("RIP%s %02x:%llx\n", 
		       !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
		       m->cs, m->ip);
	n = 0;
	if (m->status & MCI_STATUS_MISCV)
		n += Wprintf("MISC %llx ", m->misc);
	if (m->status & MCI_STATUS_ADDRV)
		n += Wprintf("ADDR %llx ", m->addr);		
	if (n > 0)
		Wprintf("\n");
	if (m->time) {
		time_t t = m->time;
		Wprintf("TIME %llu %s", m->time, ctime(&t));
	} 
	switch (cputype) { 
	case CPU_K8:
		decode_k8_mc(m, &ismemerr); 
		break;
	CASE_INTEL_CPUS:
		decode_intel_mc(m, cputype, &ismemerr, recordlen);
		break;
	/* add handlers for other CPUs here */
	default:
		break;
	} 
	/* decode all status bits here */
	Wprintf("STATUS %llx MCGSTATUS %llx\n", m->status, m->mcgstatus);
	n = 0;
	if (recordlen >= offsetof(struct mce, cpuid) && m->mcgcap)
		n += Wprintf("MCGCAP %llx ", m->mcgcap);
	if (recordlen >= offsetof(struct mce, apicid))
		n += Wprintf("APICID %x ", m->apicid);
	if (recordlen >= offsetof(struct mce, socketid))
		n += Wprintf("SOCKETID %x ", m->socketid);
	if (n > 0)
		Wprintf("\n");

	if (recordlen >= offsetof(struct mce, cpuid) && m->cpuid) {
		u32 fam, mod;
		parse_cpuid(m->cpuid, &fam, &mod);
		Wprintf("CPUID Vendor %s Family %u Model %u\n",
			cpuvendor_name(m->cpuvendor), 
			fam,
			mod);
	}
	resolveaddr(m->addr);
	if (!ascii_mode && ismemerr && (m->status & MCI_STATUS_ADDRV)) {
		diskdb_resolve_addr(m->addr);
	}
}

static void dump_mce_raw_ascii(struct mce *m, unsigned recordlen)
{
	/* should not happen */
	if (!m->finished)
		Wprintf("not finished?\n");
	Wprintf("CPU %u\n", m->extcpu ? m->extcpu : m->cpu);
	Wprintf("BANK %d\n", m->bank);
	Wprintf("TSC %#llx\n", m->tsc);
	Wprintf("RIP %#02x:%#llx\n", m->cs, m->ip);
	Wprintf("MISC %#llx\n", m->misc);
	Wprintf("ADDR %#llx\n", m->addr);
	Wprintf("STATUS %#llx\n", m->status);
	Wprintf("MCGSTATUS %#llx\n", m->mcgstatus);
	if (recordlen >= offsetof(struct mce, cpuid))
		Wprintf("PROCESSOR %u:%#x\n", m->cpuvendor, m->cpuid);
#define CPRINT(str, field) 				\
	if (recordlen >= offsetof(struct mce, field))	\
		Wprintf(str "\n", m->field)
	CPRINT("TIME %llu", time);
	CPRINT("SOCKETID %u", socketid);
	CPRINT("APICID %u", apicid);
	CPRINT("MCGCAP %#llx", mcgcap);
#undef CPRINT
	Wprintf("\n");
}

void check_cpu(void)
{ 
	enum { 
		VENDOR = 1, 
		FAMILY = 2, 
		MODEL = 4, 
		MHZ = 8, 
		FLAGS = 16, 
		ALL = 0x1f 
	} seen = 0;
	FILE *f;
	static int checked;

	if (checked)
		return;
	checked = 1;

	f = fopen("/proc/cpuinfo","r");
	if (f != NULL) { 
		int family = 0; 
		int model = 0;
		char vendor[64] = { 0 };
		char *line = NULL;
		size_t linelen = 0; 
		double mhz;

		while (getdelim(&line, &linelen, '\n', f) > 0 && seen != ALL) { 
			if (sscanf(line, "vendor_id : %63[^\n]", vendor) == 1) 
				seen |= VENDOR;
			if (sscanf(line, "cpu family : %d", &family) == 1)
				seen |= FAMILY;
			if (sscanf(line, "model : %d", &model) == 1)
				seen |= MODEL;
			/* We use only Mhz of the first CPU, assuming they are the same
			   (there are more sanity checks later to make this not as wrong
			   as it sounds) */
			if (sscanf(line, "cpu MHz : %lf", &mhz) == 1) { 
				if (!cpumhz_forced)
					cpumhz = mhz;
				seen |= MHZ;
			}
			if (!strncmp(line, "flags", 5) && isspace(line[6])) {
				processor_flags = line;
				line = NULL;
				linelen = 0;
				seen |= FLAGS;
			}			      

		} 
		if (seen == ALL) {
			if (cpu_forced) 
				;
			else if (!strcmp(vendor,"AuthenticAMD") && 
			    (family == 15 || family == 16 || family == 17))
				cputype = CPU_K8;
			else if (!strcmp(vendor,"GenuineIntel"))
				cputype = select_intel_cputype(family, model);
			/* Add checks for other CPUs here */	
		} else {
			Eprintf("warning: Cannot parse /proc/cpuinfo\n"); 
		} 
		fclose(f);
		free(line);
	} else
		Eprintf("warning: Cannot open /proc/cpuinfo\n");
} 

static char *skipspace(char *s)
{
	while (isspace(*s))
		++s;
	return s;
}

static char *skipgunk(char *s)
{
	s = skipspace(s);
	if (*s == '<') { 
		s += strcspn(s, ">"); 
		if (*s == '>') 
			++s; 
	}
	s = skipspace(s);
	if (*s == '[') {
		s += strcspn(s, "]");
		if (*s == ']')
			++s;
	}
	return skipspace(s);
}

static void dump_mce_final(struct mce *m, char *symbol, int missing, int recordlen, 
			   int dseen)
{
	m->finished = 1;
	if (!dump_raw_ascii) {
		if (!dseen)
			disclaimer();
		dump_mce(m, recordlen);
		if (symbol[0])
			Wprintf("RIP: %s\n", symbol);
		if (missing) 
			Wprintf("(Fields were incomplete)\n");
	} else
		dump_mce_raw_ascii(m, recordlen);
	flushlog();
}

#define FIELD(f) \
	if (recordlen < endof_field(struct mce, f)) \
		recordlen = endof_field(struct mce, f)

/* Decode ASCII input for fatal messages */
static void decodefatal(FILE *inf)
{
	struct mce m;
	char *line = NULL; 
	size_t linelen = 0;
	int missing; 
	char symbol[100];
	int data;
	int next;
	char *s = NULL;
	unsigned cpuvendor;
	unsigned recordlen;
	int disclaimer_seen;

	ascii_mode = 1;
	if (do_dmi && dmi_forced)
		Wprintf(
 "WARNING: with --dmi mcelog --ascii must run on the same machine with the\n"
 "     same BIOS/memory configuration as where the machine check occurred.\n");

restart:
	missing = 0;
	data = 0;
	next = 0;
	disclaimer_seen = 0;
	recordlen = 0;
	memset(&m, 0, sizeof(struct mce));
	symbol[0] = '\0';
	while (next > 0 || getdelim(&line, &linelen, '\n', inf) > 0) { 
		int n = 0;

		s = next > 0 ? s + next : line;
		s = skipgunk(s);
		next = 0;

		if (!strncmp(s, "CPU", 3)) { 
			unsigned cpu = 0, bank = 0;
			n = sscanf(s,
	       "CPU %u: Machine Check Exception: %16Lx Bank %d: %016Lx%n",
				   &cpu,
				   &m.mcgstatus,
				   &bank,
				   &m.status,
				   &next);
			if (n == 1) {
				n = sscanf(s, "CPU %u BANK %u%n", &cpu, &bank, 
						&next);
				if (n != 2)
					n = sscanf(s, "CPU %u %u%n", &cpu,
						 &bank, &next);
				m.cpu = cpu;
				if (n < 2) 
					missing++;
				else { 
					m.bank = bank;
					FIELD(bank);
				}
			} else if (n <= 0) { 
				missing++;
			} else if (n > 1) {
				FIELD(mcgstatus);
				m.cpu = cpu;
				if (n > 2) {
					m.bank = bank;
					FIELD(bank);
				} else if (n > 3) 
					FIELD(status);
				if (n < 4)
					missing++; 
			}
		} 
		else if (!strncmp(s, "STATUS", 6)) {
			if ((n = sscanf(s,"STATUS %llx%n", &m.status, &next)) < 1)
				missing++;
			else
				FIELD(status);
		}
		else if (!strncmp(s, "MCGSTATUS", 6)) {
			if ((n = sscanf(s,"MCGSTATUS %llx%n", &m.mcgstatus, &next)) < 1)
				missing++;
			else
				FIELD(mcgstatus);
		}
		else if (!strncmp(s, "RIP", 3)) { 
			unsigned cs = 0; 

			if (!strncmp(s, "RIP !INEXACT!", 13))
				s += 13; 
			else
				s += 3; 

			n = sscanf(s, "%02x:<%016Lx> {%100s}%n",
				   &cs,
				   &m.ip, 
				   symbol, &next); 
			m.cs = cs;
			if (n < 2) 
				missing++; 
			else
				FIELD(ip);
		} 
		else if (!strncmp(s, "TSC",3)) { 
			if ((n = sscanf(s, "TSC %llx%n", &m.tsc, &next)) < 1) 
				missing++;
			else
				FIELD(tsc);
		}
		else if (!strncmp(s, "ADDR",4)) { 
			if ((n = sscanf(s, "ADDR %llx%n", &m.addr, &next)) < 1) 
				missing++;
			else
				FIELD(addr);
		}
		else if (!strncmp(s, "MISC",4)) { 
			if ((n = sscanf(s, "MISC %llx%n", &m.misc, &next)) < 1) 
				missing++; 
			else
				FIELD(misc);
		} 
		else if (!strncmp(s, "PROCESSOR", 9)) { 
			if ((n = sscanf(s, "PROCESSOR %u:%x%n", &cpuvendor, &m.cpuid, &next)) < 2)
				missing++;
			else {
				m.cpuvendor = cpuvendor;			
				FIELD(cpuid);
				FIELD(cpuvendor);
			}
		} 
		else if (!strncmp(s, "TIME", 4)) { 
			if ((n = sscanf(s, "TIME %llu%n", &m.time, &next)) < 1)
				missing++;
			else
				FIELD(time);
		} 
		else if (!strncmp(s, "MCGCAP", 6)) {
			if ((n = sscanf(s, "MCGCAP %llx%n", &m.mcgcap, &next)) != 1)
				missing++;
			else
				FIELD(mcgcap);
		} 
		else if (!strncmp(s, "APICID", 6)) {
			if ((n = sscanf(s, "APICID %x%n", &m.apicid, &next)) != 1)
				missing++;
			else
				FIELD(apicid);
		} 
		else if (!strncmp(s, "SOCKETID", 8)) {
			if ((n = sscanf(s, "SOCKETID %u%n", &m.socketid, &next)) != 1)
				missing++;
			else
				FIELD(socketid);
		} 
		else if (strstr(s, "HARDWARE ERROR"))
			disclaimer_seen = 1;
		else if (!strncmp(s, "(XEN)", 5)) {
			char *w; 
			unsigned bank, cpu;

			if (strstr(s, "The hardware reports a non fatal, correctable incident occurred")) {
				w = strstr(s, "CPU");
				if (w && sscanf(w, "CPU %d", &cpu)) {
					m.cpu = cpu;
					FIELD(cpu);
				}
			} else if ((n = sscanf(s, "(XEN) Bank %d: %llx at %llx", 
						&bank, &m.status, &m.addr) >= 1)) {
				m.bank = bank;
				FIELD(bank);	
				if (n >= 2) 
					FIELD(status);
				if (n >= 3)
					FIELD(addr);
			}
		}
		else { 
			s = skipspace(s);
			if (*s && data)
				dump_mce_final(&m, symbol, missing, recordlen, disclaimer_seen); 
			if (!dump_raw_ascii)
				Wprintf("%s", line);
			if (*s && data)
				goto restart;
		} 
		if (n > 0) 
			data = 1;
	} 
	free(line);
	if (data)
		dump_mce_final(&m, symbol, missing, recordlen, disclaimer_seen);
}

static void remove_pidfile(void)
{
	unlink(pidfile);
	if (pidfile != pidfile_default)
		free(pidfile);
}

static void signal_exit(int sig)
{
	remove_pidfile();
	_exit(sig);
}

static void setup_pidfile(char *s)
{
	char cwd[PATH_MAX];
	char *c;

	if (*s != '/') {
		c = getcwd(cwd, PATH_MAX);
		if (!c)
			return;
		asprintf(&pidfile, "%s/%s", cwd, s);
	} else {
		asprintf(&pidfile, "%s", s);
	}

	return;
}

static void write_pidfile(void)
{
	FILE *f;
	atexit(remove_pidfile);
	signal(SIGTERM, signal_exit);
	signal(SIGINT, signal_exit);
	signal(SIGQUIT, signal_exit);
	f = fopen(pidfile, "w");
	if (!f) {
		Eprintf("Cannot open pidfile `%s'", pidfile);
		return;
	}
	fprintf(f, "%u", getpid());
	fclose(f);
}

void usage(void)
{
	fprintf(stderr, 
"Usage:\n"
"  mcelog [options]  [mcelogdevice]\n"
"Decode machine check error records from current kernel.\n"
"  mcelog [options] --daemon\n"
"Run mcelog in daemon mode, waiting for errors from the kernel.\n"
"  mcelog [options] --client\n"
"Query a currently running mcelog daemon for errors\n"
"  mcelog [options] --ascii < log\n"
"  mcelog [options] --ascii --file log\n"
"Decode machine check ASCII output from kernel logs\n"
"Options:\n"  
"--cpu CPU           Set CPU type CPU to decode (see below for valid types)\n"
"--cpumhz MHZ        Set CPU Mhz to decode time (output unreliable, not needed on new kernels)\n"
"--raw		     (with --ascii) Dump in raw ASCII format for machine processing\n"
"--daemon            Run in background waiting for events (needs newer kernel)\n"
"--ignorenodev       Exit silently when the device cannot be opened\n"
"--file filename     With --ascii read machine check log from filename instead of stdin\n"
"--syslog            Log decoded machine checks in syslog (default stdout or syslog for daemon)\n"	     
"--syslog-error	     Log decoded machine checks in syslog with error level\n"
"--no-syslog         Never log anything to syslog\n"
"--logfile filename  Append log output to logfile instead of stdout\n"
"--dmi               Use SMBIOS information to decode DIMMs (needs root)\n"
"--no-dmi            Don't use SMBIOS information\n"
"--dmi-verbose       Dump SMBIOS information (for debugging)\n"
"--filter            Inhibit known bogus events (default on)\n"
"--no-filter         Don't inhibit known broken events\n"
"--config-file filename Read config information from config file instead of " CONFIG_FILENAME "\n"
"--foreground        Keep in foreground (for debugging)\n"
"--num-errors N      Only process N errors (for testing)\n"
"--pidfile file	     Write pid of daemon into file\n"
		);
	diskdb_usage();
	print_cputypes();
	exit(1);
}

enum options { 
	O_LOGFILE = O_COMMON, 
	O_K8,
	O_P4,
	O_GENERIC,
	O_CORE2,
	O_INTEL_CPU,
	O_FILTER,
	O_DMI,
	O_NO_DMI,
	O_DMI_VERBOSE,
	O_SYSLOG,
	O_NO_SYSLOG,
	O_CPUMHZ,
	O_SYSLOG_ERROR,
	O_RAW,
	O_DAEMON,
	O_ASCII,
	O_CLIENT,
	O_VERSION,
	O_CONFIG_FILE,
	O_CPU,
	O_FILE,
	O_FOREGROUND,
	O_NUMERRORS,
	O_PIDFILE,
	O_DEBUG_NUMERRORS,
};

static struct option options[] = {
	{ "logfile", 1, NULL, O_LOGFILE },
	{ "k8", 0, NULL, O_K8 },
	{ "p4", 0, NULL, O_P4 },
	{ "generic", 0, NULL, O_GENERIC },
	{ "core2", 0, NULL, O_CORE2 },
	{ "intel-cpu", 1, NULL, O_INTEL_CPU },
	{ "ignorenodev", 0, &ignore_nodev, 1 },
	{ "filter", 0, &filter_bogus, 1 },
	{ "no-filter", 0, &filter_bogus, 0 },
	{ "dmi", 0, NULL, O_DMI },
	{ "no-dmi", 0, NULL, O_NO_DMI },
	{ "dmi-verbose", 1, NULL, O_DMI_VERBOSE },
	{ "syslog", 0, NULL, O_SYSLOG },
	{ "cpumhz", 1, NULL, O_CPUMHZ },
	{ "syslog-error", 0, NULL, O_SYSLOG_ERROR },
	{ "dump-raw-ascii", 0, &dump_raw_ascii, 1 },
	{ "raw", 0, &dump_raw_ascii, 1 },
	{ "no-syslog", 0, NULL, O_NO_SYSLOG },
	{ "daemon", 0, NULL, O_DAEMON },
	{ "ascii", 0, NULL, O_ASCII },
	{ "file", 1, NULL, O_FILE },
	{ "version", 0, NULL, O_VERSION },
	{ "config-file", 1, NULL, O_CONFIG_FILE },
	{ "cpu", 1, NULL, O_CPU },
	{ "foreground", 0, NULL, O_FOREGROUND },
	{ "client", 0, NULL, O_CLIENT },
	{ "num-errors", 1, NULL, O_NUMERRORS },
	{ "pidfile", 1, NULL, O_PIDFILE },
	{ "debug-numerrors", 0, NULL, O_DEBUG_NUMERRORS }, /* undocumented: for testing */
	DISKDB_OPTIONS
	{}
};

static int modifier(int opt)
{
	int v;

	switch (opt) { 
	case O_LOGFILE:
		logfile = optarg;
		break;
	case O_K8:
		cputype = CPU_K8;
		cpu_forced = 1;
		break;
	case O_P4:
		cputype = CPU_P4;
		cpu_forced = 1;
		break;
	case O_GENERIC:
		cputype = CPU_GENERIC;
		cpu_forced = 1;
		break;
	case O_CORE2:
		cputype = CPU_CORE2;
		cpu_forced = 1;
		break;
	case O_INTEL_CPU: { 
		unsigned fam, mod;
		if (sscanf(optarg, "%i,%i", &fam, &mod) != 2)
			usage();
		cputype = select_intel_cputype(fam, mod);
		if (cputype == CPU_GENERIC) {
			fprintf(stderr, "Unknown Intel CPU\n");
			usage();
		}
		cpu_forced = 1;
		break;
	}
	case O_CPU:
		cputype = lookup_cputype(optarg);
		cpu_forced = 1;
		intel_cpu_init(cputype);
		break;
	case O_DMI:
		do_dmi = 1;
		dmi_forced = 1;
		break;
	case O_NO_DMI:
		dmi_forced = 1;
		do_dmi = 0;
		break;
	case O_DMI_VERBOSE:
		if (sscanf(optarg, "%i", &v) != 1)
			usage();
		dmi_set_verbosity(v);
		break;
	case O_SYSLOG:
		openlog("mcelog", 0, LOG_DAEMON);
		syslog_opt = SYSLOG_ALL|SYSLOG_FORCE;
		break;
	case O_NO_SYSLOG:
		syslog_opt = SYSLOG_FORCE;
		break;
	case O_CPUMHZ:
		cpumhz_forced = 1;
		if (sscanf(optarg, "%lf", &cpumhz) != 1)
			usage();
		break;
	case O_SYSLOG_ERROR:
		syslog_level = LOG_ERR;
		syslog_opt = SYSLOG_ALL|SYSLOG_FORCE;
		break;
	case O_DAEMON:
		daemon_mode = 1;
		if (!logfile && !foreground)
			logfile = logfile_default;
		if (!(syslog_opt & SYSLOG_FORCE))
			syslog_opt = SYSLOG_REMARK|SYSLOG_ERROR;

		break;
	case O_FILE:
		inputfile = optarg;
		break;
	case O_FOREGROUND:
		foreground = 1;	
		if (!(syslog_opt & SYSLOG_FORCE))
			syslog_opt = SYSLOG_FORCE;
		if (logfile == logfile_default)
			logfile = NULL;
		break;
	case O_NUMERRORS:
		numerrors = atoi(optarg);
		break;
	case O_PIDFILE:
		setup_pidfile(optarg);
		break;
	case O_CONFIG_FILE:
		/* parsed in config.c */
		break;
	case O_DEBUG_NUMERRORS:
		debug_numerrors = 1;
		break;
	case 0:
		break;
	default:
		return 0;
	}
	return 1;
} 

static void modifier_finish(void)
{
	if (logfile) {
		if (open_logfile(logfile) < 0) {
			if (daemon_mode && !(syslog_opt & SYSLOG_FORCE))
				syslog_opt = SYSLOG_ALL;
			SYSERRprintf("Cannot open logfile %s", logfile);
			if (!daemon_mode)
				exit(1);
		}
	}			
}

void argsleft(int ac, char **av)
{
	int opt;
		
	while ((opt = getopt_long(ac, av, "", options, NULL)) != -1) { 
		if (modifier(opt) != 1)
			usage();
	}
}

void no_syslog(void)
{
	if (!(syslog_opt & SYSLOG_FORCE))
		syslog_opt = 0;
}

static int combined_modifier(int opt)
{
	int r = modifier(opt);
	if (r == 0)
		r = diskdb_modifier(opt);
	return r;
}

static void general_setup(void)
{
	trigger_setup();
	yellow_setup();
	config_cred("global", "run-credentials", &runcred);
	if (config_bool("global", "filter-memory-errors") == 1)
		filter_memory_errors = 1;
}

static void drop_cred(void)
{
	if (runcred.uid != -1U && runcred.gid == -1U) {
		struct passwd *pw = getpwuid(runcred.uid);
		if (pw)
			runcred.gid = pw->pw_gid;
	}
	if (runcred.gid != -1U) {
		if (setgid(runcred.gid) < 0) 
			SYSERRprintf("Cannot change group to %d", runcred.gid);
	}
	if (runcred.uid != -1U) {
		if (setuid(runcred.uid) < 0)
			SYSERRprintf("Cannot change user to %d", runcred.uid);
	}
}

static void process(int fd, unsigned recordlen, unsigned loglen, char *buf)
{	
	int i; 
	int len;
	int finish = 0;

	if (recordlen == 0) {
		Wprintf("no data in mce record\n");
		return;
	}

	len = read(fd, buf, recordlen * loglen); 
	if (len < 0) {
		SYSERRprintf("mcelog read"); 
		return;
	}

	for (i = 0; (i < len / (int)recordlen) && !finish; i++) { 
		struct mce *mce = (struct mce *)(buf + i*recordlen);
		mce_prepare(mce);
		if (numerrors > 0 && --numerrors == 0)
			finish = 1;
		if (!mce_filter(mce, recordlen)) 
			continue;
		if (!dump_raw_ascii) {
			disclaimer();
			Wprintf("MCE %d\n", i);
			dump_mce(mce, recordlen);
		} else
			dump_mce_raw_ascii(mce, recordlen);
		flushlog();
	}

	if (debug_numerrors && numerrors <= 0)
		finish = 1;

	if (recordlen > sizeof(struct mce))  {
		Eprintf("warning: %lu bytes ignored in each record\n",
				(unsigned long)recordlen - sizeof(struct mce)); 
		Eprintf("consider an update\n"); 
	}

	if (finish)
		exit(0);
}

static void noargs(int ac, char **av)
{
	if (getopt_long(ac, av, "", options, NULL) != -1)
		usage();
}

static void parse_config(char **av)
{
	static const char config_fn[] = CONFIG_FILENAME;
	const char *fn = config_file(av, config_fn);
	if (!fn)
		usage();
	if (parse_config_file(fn) < 0) { 
		/* If it's the default file don't complain if it isn't there */
		if (fn != config_fn) {
			fprintf(stderr, "Cannot open config file %s\n", fn);
			exit(1);
		}
		return;
	}
	config_options(options, combined_modifier);
}

static void ascii_command(int ac, char **av)
{
	FILE *f = stdin;

	argsleft(ac, av);
	if (inputfile) { 
		f = fopen(inputfile, "r");
		if (!f) {		
			fprintf(stderr, "Cannot open input file `%s': %s\n",
				inputfile, strerror(errno));
			exit(1);
		}
		/* f closed by exit */
	}
	no_syslog();
	checkdmi();
	decodefatal(f); 
}

static void client_command(int ac, char **av)
{
	argsleft(ac, av);
	no_syslog();
	// XXX modifiers
	ask_server("dump all bios\n");		
	ask_server("pages\n");
}

struct mcefd_data {
	unsigned loglen;
	unsigned recordlen;
	char *buf;
};

static void process_mcefd(struct pollfd *pfd, void *data)
{
	struct mcefd_data *d = (struct mcefd_data *)data;
	assert((pfd->revents & POLLIN) != 0);
	process(pfd->fd, d->recordlen, d->loglen, d->buf);
}

static void handle_sigusr1(int sig)
{
	reopenlog();
}

int main(int ac, char **av) 
{ 
	struct mcefd_data d = {};
	int opt;
	int fd;

	parse_config(av);

	while ((opt = getopt_long(ac, av, "", options, NULL)) != -1) { 
		if (opt == '?') {
			usage(); 
		} else if (combined_modifier(opt) > 0) {
			continue;
		} else if (opt == O_ASCII) { 
			ascii_command(ac, av);
			exit(0);
		} else if (opt == O_CLIENT) { 
			client_command(ac, av);
			exit(0);
		} else if (opt == O_VERSION) { 
			noargs(ac, av);
			fprintf(stderr, "mcelog %s\n", MCELOG_VERSION);
			exit(0);
		} else if (diskdb_cmd(opt, ac, av)) {
			exit(0);
		} else if (opt == 0)
			break;		    
	} 
	modifier_finish();
	if (av[optind])
		logfn = av[optind++];
	if (av[optind])
		usage();
	checkdmi();
	general_setup();
		
	fd = open(logfn, O_RDONLY); 
	if (fd < 0) {
		if (ignore_nodev) 
			exit(0);
		SYSERRprintf("Cannot open `%s'", logfn);
		exit(1);
	}
	
	if (ioctl(fd, MCE_GET_RECORD_LEN, &d.recordlen) < 0)
		err("MCE_GET_RECORD_LEN");
	if (ioctl(fd, MCE_GET_LOG_LEN, &d.loglen) < 0)
		err("MCE_GET_LOG_LEN");

	d.buf = xalloc(d.recordlen * d.loglen); 
	if (daemon_mode) {
		check_cpu();
		prefill_memdb();
		if (!do_dmi)
			closedmi();
		server_setup();
		page_setup();
		drop_cred();
		register_pollcb(fd, POLLIN, process_mcefd, &d);
		if (!foreground && daemon(0, need_stdout()) < 0)
			err("daemon");
		if (pidfile)
			write_pidfile();
		signal(SIGUSR1, handle_sigusr1);
		event_signal(SIGUSR1);
		eventloop();
	} else {
		process(fd, d.recordlen, d.loglen, d.buf);
	}
	trigger_wait();
		
	exit(0); 
}