xref: /freebsd/sys/x86/x86/mca.c (revision 3157ba21)
1 /*-
2  * Copyright (c) 2009 Advanced Computing Technologies LLC
3  * Written by: John H. Baldwin <jhb@FreeBSD.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 /*
29  * Support for x86 machine check architecture.
30  */
31 
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34 
35 #ifdef __amd64__
36 #define	DEV_APIC
37 #else
38 #include "opt_apic.h"
39 #endif
40 
41 #include <sys/param.h>
42 #include <sys/bus.h>
43 #include <sys/interrupt.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
48 #include <sys/proc.h>
49 #include <sys/sched.h>
50 #include <sys/smp.h>
51 #include <sys/sysctl.h>
52 #include <sys/systm.h>
53 #include <sys/taskqueue.h>
54 #include <machine/intr_machdep.h>
55 #include <machine/apicvar.h>
56 #include <machine/cputypes.h>
57 #include <machine/mca.h>
58 #include <machine/md_var.h>
59 #include <machine/specialreg.h>
60 
61 /* Modes for mca_scan() */
62 enum scan_mode {
63 	POLLED,
64 	MCE,
65 	CMCI,
66 };
67 
68 #ifdef DEV_APIC
69 /*
70  * State maintained for each monitored MCx bank to control the
71  * corrected machine check interrupt threshold.
72  */
73 struct cmc_state {
74 	int	max_threshold;
75 	int	last_intr;
76 };
77 #endif
78 
79 struct mca_internal {
80 	struct mca_record rec;
81 	int		logged;
82 	STAILQ_ENTRY(mca_internal) link;
83 };
84 
85 static MALLOC_DEFINE(M_MCA, "MCA", "Machine Check Architecture");
86 
87 static int mca_count;		/* Number of records stored. */
88 
89 SYSCTL_NODE(_hw, OID_AUTO, mca, CTLFLAG_RD, NULL, "Machine Check Architecture");
90 
91 static int mca_enabled = 1;
92 TUNABLE_INT("hw.mca.enabled", &mca_enabled);
93 SYSCTL_INT(_hw_mca, OID_AUTO, enabled, CTLFLAG_RDTUN, &mca_enabled, 0,
94     "Administrative toggle for machine check support");
95 
96 static int amd10h_L1TP = 1;
97 TUNABLE_INT("hw.mca.amd10h_L1TP", &amd10h_L1TP);
98 SYSCTL_INT(_hw_mca, OID_AUTO, amd10h_L1TP, CTLFLAG_RDTUN, &amd10h_L1TP, 0,
99     "Administrative toggle for logging of level one TLB parity (L1TP) errors");
100 
101 int workaround_erratum383;
102 SYSCTL_INT(_hw_mca, OID_AUTO, erratum383, CTLFLAG_RD, &workaround_erratum383, 0,
103     "Is the workaround for Erratum 383 on AMD Family 10h processors enabled?");
104 
105 static STAILQ_HEAD(, mca_internal) mca_records;
106 static struct callout mca_timer;
107 static int mca_ticks = 3600;	/* Check hourly by default. */
108 static struct task mca_task;
109 static struct mtx mca_lock;
110 
111 #ifdef DEV_APIC
112 static struct cmc_state **cmc_state;	/* Indexed by cpuid, bank */
113 static int cmc_banks;
114 static int cmc_throttle = 60;	/* Time in seconds to throttle CMCI. */
115 #endif
116 
117 static int
118 sysctl_positive_int(SYSCTL_HANDLER_ARGS)
119 {
120 	int error, value;
121 
122 	value = *(int *)arg1;
123 	error = sysctl_handle_int(oidp, &value, 0, req);
124 	if (error || req->newptr == NULL)
125 		return (error);
126 	if (value <= 0)
127 		return (EINVAL);
128 	*(int *)arg1 = value;
129 	return (0);
130 }
131 
132 static int
133 sysctl_mca_records(SYSCTL_HANDLER_ARGS)
134 {
135 	int *name = (int *)arg1;
136 	u_int namelen = arg2;
137 	struct mca_record record;
138 	struct mca_internal *rec;
139 	int i;
140 
141 	if (namelen != 1)
142 		return (EINVAL);
143 
144 	if (name[0] < 0 || name[0] >= mca_count)
145 		return (EINVAL);
146 
147 	mtx_lock_spin(&mca_lock);
148 	if (name[0] >= mca_count) {
149 		mtx_unlock_spin(&mca_lock);
150 		return (EINVAL);
151 	}
152 	i = 0;
153 	STAILQ_FOREACH(rec, &mca_records, link) {
154 		if (i == name[0]) {
155 			record = rec->rec;
156 			break;
157 		}
158 		i++;
159 	}
160 	mtx_unlock_spin(&mca_lock);
161 	return (SYSCTL_OUT(req, &record, sizeof(record)));
162 }
163 
164 static const char *
165 mca_error_ttype(uint16_t mca_error)
166 {
167 
168 	switch ((mca_error & 0x000c) >> 2) {
169 	case 0:
170 		return ("I");
171 	case 1:
172 		return ("D");
173 	case 2:
174 		return ("G");
175 	}
176 	return ("?");
177 }
178 
179 static const char *
180 mca_error_level(uint16_t mca_error)
181 {
182 
183 	switch (mca_error & 0x0003) {
184 	case 0:
185 		return ("L0");
186 	case 1:
187 		return ("L1");
188 	case 2:
189 		return ("L2");
190 	case 3:
191 		return ("LG");
192 	}
193 	return ("L?");
194 }
195 
196 static const char *
197 mca_error_request(uint16_t mca_error)
198 {
199 
200 	switch ((mca_error & 0x00f0) >> 4) {
201 	case 0x0:
202 		return ("ERR");
203 	case 0x1:
204 		return ("RD");
205 	case 0x2:
206 		return ("WR");
207 	case 0x3:
208 		return ("DRD");
209 	case 0x4:
210 		return ("DWR");
211 	case 0x5:
212 		return ("IRD");
213 	case 0x6:
214 		return ("PREFETCH");
215 	case 0x7:
216 		return ("EVICT");
217 	case 0x8:
218 		return ("SNOOP");
219 	}
220 	return ("???");
221 }
222 
223 static const char *
224 mca_error_mmtype(uint16_t mca_error)
225 {
226 
227 	switch ((mca_error & 0x70) >> 4) {
228 	case 0x0:
229 		return ("GEN");
230 	case 0x1:
231 		return ("RD");
232 	case 0x2:
233 		return ("WR");
234 	case 0x3:
235 		return ("AC");
236 	case 0x4:
237 		return ("MS");
238 	}
239 	return ("???");
240 }
241 
242 /* Dump details about a single machine check. */
243 static void __nonnull(1)
244 mca_log(const struct mca_record *rec)
245 {
246 	uint16_t mca_error;
247 
248 	printf("MCA: Bank %d, Status 0x%016llx\n", rec->mr_bank,
249 	    (long long)rec->mr_status);
250 	printf("MCA: Global Cap 0x%016llx, Status 0x%016llx\n",
251 	    (long long)rec->mr_mcg_cap, (long long)rec->mr_mcg_status);
252 	printf("MCA: Vendor \"%s\", ID 0x%x, APIC ID %d\n", cpu_vendor,
253 	    rec->mr_cpu_id, rec->mr_apic_id);
254 	printf("MCA: CPU %d ", rec->mr_cpu);
255 	if (rec->mr_status & MC_STATUS_UC)
256 		printf("UNCOR ");
257 	else {
258 		printf("COR ");
259 		if (rec->mr_mcg_cap & MCG_CAP_TES_P)
260 			printf("(%lld) ", ((long long)rec->mr_status &
261 			    MC_STATUS_COR_COUNT) >> 38);
262 	}
263 	if (rec->mr_status & MC_STATUS_PCC)
264 		printf("PCC ");
265 	if (rec->mr_status & MC_STATUS_OVER)
266 		printf("OVER ");
267 	mca_error = rec->mr_status & MC_STATUS_MCA_ERROR;
268 	switch (mca_error) {
269 		/* Simple error codes. */
270 	case 0x0000:
271 		printf("no error");
272 		break;
273 	case 0x0001:
274 		printf("unclassified error");
275 		break;
276 	case 0x0002:
277 		printf("ucode ROM parity error");
278 		break;
279 	case 0x0003:
280 		printf("external error");
281 		break;
282 	case 0x0004:
283 		printf("FRC error");
284 		break;
285 	case 0x0005:
286 		printf("internal parity error");
287 		break;
288 	case 0x0400:
289 		printf("internal timer error");
290 		break;
291 	default:
292 		if ((mca_error & 0xfc00) == 0x0400) {
293 			printf("internal error %x", mca_error & 0x03ff);
294 			break;
295 		}
296 
297 		/* Compound error codes. */
298 
299 		/* Memory hierarchy error. */
300 		if ((mca_error & 0xeffc) == 0x000c) {
301 			printf("%s memory error", mca_error_level(mca_error));
302 			break;
303 		}
304 
305 		/* TLB error. */
306 		if ((mca_error & 0xeff0) == 0x0010) {
307 			printf("%sTLB %s error", mca_error_ttype(mca_error),
308 			    mca_error_level(mca_error));
309 			break;
310 		}
311 
312 		/* Memory controller error. */
313 		if ((mca_error & 0xef80) == 0x0080) {
314 			printf("%s channel ", mca_error_mmtype(mca_error));
315 			if ((mca_error & 0x000f) != 0x000f)
316 				printf("%d", mca_error & 0x000f);
317 			else
318 				printf("??");
319 			printf(" memory error");
320 			break;
321 		}
322 
323 		/* Cache error. */
324 		if ((mca_error & 0xef00) == 0x0100) {
325 			printf("%sCACHE %s %s error",
326 			    mca_error_ttype(mca_error),
327 			    mca_error_level(mca_error),
328 			    mca_error_request(mca_error));
329 			break;
330 		}
331 
332 		/* Bus and/or Interconnect error. */
333 		if ((mca_error & 0xe800) == 0x0800) {
334 			printf("BUS%s ", mca_error_level(mca_error));
335 			switch ((mca_error & 0x0600) >> 9) {
336 			case 0:
337 				printf("Source");
338 				break;
339 			case 1:
340 				printf("Responder");
341 				break;
342 			case 2:
343 				printf("Observer");
344 				break;
345 			default:
346 				printf("???");
347 				break;
348 			}
349 			printf(" %s ", mca_error_request(mca_error));
350 			switch ((mca_error & 0x000c) >> 2) {
351 			case 0:
352 				printf("Memory");
353 				break;
354 			case 2:
355 				printf("I/O");
356 				break;
357 			case 3:
358 				printf("Other");
359 				break;
360 			default:
361 				printf("???");
362 				break;
363 			}
364 			if (mca_error & 0x0100)
365 				printf(" timed out");
366 			break;
367 		}
368 
369 		printf("unknown error %x", mca_error);
370 		break;
371 	}
372 	printf("\n");
373 	if (rec->mr_status & MC_STATUS_ADDRV)
374 		printf("MCA: Address 0x%llx\n", (long long)rec->mr_addr);
375 	if (rec->mr_status & MC_STATUS_MISCV)
376 		printf("MCA: Misc 0x%llx\n", (long long)rec->mr_misc);
377 }
378 
379 static int __nonnull(2)
380 mca_check_status(int bank, struct mca_record *rec)
381 {
382 	uint64_t status;
383 	u_int p[4];
384 
385 	status = rdmsr(MSR_MC_STATUS(bank));
386 	if (!(status & MC_STATUS_VAL))
387 		return (0);
388 
389 	/* Save exception information. */
390 	rec->mr_status = status;
391 	rec->mr_bank = bank;
392 	rec->mr_addr = 0;
393 	if (status & MC_STATUS_ADDRV)
394 		rec->mr_addr = rdmsr(MSR_MC_ADDR(bank));
395 	rec->mr_misc = 0;
396 	if (status & MC_STATUS_MISCV)
397 		rec->mr_misc = rdmsr(MSR_MC_MISC(bank));
398 	rec->mr_tsc = rdtsc();
399 	rec->mr_apic_id = PCPU_GET(apic_id);
400 	rec->mr_mcg_cap = rdmsr(MSR_MCG_CAP);
401 	rec->mr_mcg_status = rdmsr(MSR_MCG_STATUS);
402 	rec->mr_cpu_id = cpu_id;
403 	rec->mr_cpu_vendor_id = cpu_vendor_id;
404 	rec->mr_cpu = PCPU_GET(cpuid);
405 
406 	/*
407 	 * Clear machine check.  Don't do this for uncorrectable
408 	 * errors so that the BIOS can see them.
409 	 */
410 	if (!(rec->mr_status & (MC_STATUS_PCC | MC_STATUS_UC))) {
411 		wrmsr(MSR_MC_STATUS(bank), 0);
412 		do_cpuid(0, p);
413 	}
414 	return (1);
415 }
416 
417 static void __nonnull(1)
418 mca_record_entry(const struct mca_record *record)
419 {
420 	struct mca_internal *rec;
421 
422 	rec = malloc(sizeof(*rec), M_MCA, M_NOWAIT);
423 	if (rec == NULL) {
424 		printf("MCA: Unable to allocate space for an event.\n");
425 		mca_log(record);
426 		return;
427 	}
428 
429 	rec->rec = *record;
430 	rec->logged = 0;
431 	mtx_lock_spin(&mca_lock);
432 	STAILQ_INSERT_TAIL(&mca_records, rec, link);
433 	mca_count++;
434 	mtx_unlock_spin(&mca_lock);
435 }
436 
437 #ifdef DEV_APIC
438 /*
439  * Update the interrupt threshold for a CMCI.  The strategy is to use
440  * a low trigger that interrupts as soon as the first event occurs.
441  * However, if a steady stream of events arrive, the threshold is
442  * increased until the interrupts are throttled to once every
443  * cmc_throttle seconds or the periodic scan.  If a periodic scan
444  * finds that the threshold is too high, it is lowered.
445  */
446 static void
447 cmci_update(enum scan_mode mode, int bank, int valid, struct mca_record *rec)
448 {
449 	struct cmc_state *cc;
450 	uint64_t ctl;
451 	u_int delta;
452 	int count, limit;
453 
454 	/* Fetch the current limit for this bank. */
455 	cc = &cmc_state[PCPU_GET(cpuid)][bank];
456 	ctl = rdmsr(MSR_MC_CTL2(bank));
457 	count = (rec->mr_status & MC_STATUS_COR_COUNT) >> 38;
458 	delta = (u_int)(ticks - cc->last_intr);
459 
460 	/*
461 	 * If an interrupt was received less than cmc_throttle seconds
462 	 * since the previous interrupt and the count from the current
463 	 * event is greater than or equal to the current threshold,
464 	 * double the threshold up to the max.
465 	 */
466 	if (mode == CMCI && valid) {
467 		limit = ctl & MC_CTL2_THRESHOLD;
468 		if (delta < cmc_throttle && count >= limit &&
469 		    limit < cc->max_threshold) {
470 			limit = min(limit << 1, cc->max_threshold);
471 			ctl &= ~MC_CTL2_THRESHOLD;
472 			ctl |= limit;
473 			wrmsr(MSR_MC_CTL2(bank), limit);
474 		}
475 		cc->last_intr = ticks;
476 		return;
477 	}
478 
479 	/*
480 	 * When the banks are polled, check to see if the threshold
481 	 * should be lowered.
482 	 */
483 	if (mode != POLLED)
484 		return;
485 
486 	/* If a CMCI occured recently, do nothing for now. */
487 	if (delta < cmc_throttle)
488 		return;
489 
490 	/*
491 	 * Compute a new limit based on the average rate of events per
492 	 * cmc_throttle seconds since the last interrupt.
493 	 */
494 	if (valid) {
495 		count = (rec->mr_status & MC_STATUS_COR_COUNT) >> 38;
496 		limit = count * cmc_throttle / delta;
497 		if (limit <= 0)
498 			limit = 1;
499 		else if (limit > cc->max_threshold)
500 			limit = cc->max_threshold;
501 	} else
502 		limit = 1;
503 	if ((ctl & MC_CTL2_THRESHOLD) != limit) {
504 		ctl &= ~MC_CTL2_THRESHOLD;
505 		ctl |= limit;
506 		wrmsr(MSR_MC_CTL2(bank), limit);
507 	}
508 }
509 #endif
510 
511 /*
512  * This scans all the machine check banks of the current CPU to see if
513  * there are any machine checks.  Any non-recoverable errors are
514  * reported immediately via mca_log().  The current thread must be
515  * pinned when this is called.  The 'mode' parameter indicates if we
516  * are being called from the MC exception handler, the CMCI handler,
517  * or the periodic poller.  In the MC exception case this function
518  * returns true if the system is restartable.  Otherwise, it returns a
519  * count of the number of valid MC records found.
520  */
521 static int
522 mca_scan(enum scan_mode mode)
523 {
524 	struct mca_record rec;
525 	uint64_t mcg_cap, ucmask;
526 	int count, i, recoverable, valid;
527 
528 	count = 0;
529 	recoverable = 1;
530 	ucmask = MC_STATUS_UC | MC_STATUS_PCC;
531 
532 	/* When handling a MCE#, treat the OVER flag as non-restartable. */
533 	if (mode == MCE)
534 		ucmask |= MC_STATUS_OVER;
535 	mcg_cap = rdmsr(MSR_MCG_CAP);
536 	for (i = 0; i < (mcg_cap & MCG_CAP_COUNT); i++) {
537 #ifdef DEV_APIC
538 		/*
539 		 * For a CMCI, only check banks this CPU is
540 		 * responsible for.
541 		 */
542 		if (mode == CMCI && !(PCPU_GET(cmci_mask) & 1 << i))
543 			continue;
544 #endif
545 
546 		valid = mca_check_status(i, &rec);
547 		if (valid) {
548 			count++;
549 			if (rec.mr_status & ucmask) {
550 				recoverable = 0;
551 				mca_log(&rec);
552 			}
553 			mca_record_entry(&rec);
554 		}
555 
556 #ifdef DEV_APIC
557 		/*
558 		 * If this is a bank this CPU monitors via CMCI,
559 		 * update the threshold.
560 		 */
561 		if (PCPU_GET(cmci_mask) & 1 << i)
562 			cmci_update(mode, i, valid, &rec);
563 #endif
564 	}
565 	return (mode == MCE ? recoverable : count);
566 }
567 
568 /*
569  * Scan the machine check banks on all CPUs by binding to each CPU in
570  * turn.  If any of the CPUs contained new machine check records, log
571  * them to the console.
572  */
573 static void
574 mca_scan_cpus(void *context, int pending)
575 {
576 	struct mca_internal *mca;
577 	struct thread *td;
578 	int count, cpu;
579 
580 	td = curthread;
581 	count = 0;
582 	thread_lock(td);
583 	CPU_FOREACH(cpu) {
584 		sched_bind(td, cpu);
585 		thread_unlock(td);
586 		count += mca_scan(POLLED);
587 		thread_lock(td);
588 		sched_unbind(td);
589 	}
590 	thread_unlock(td);
591 	if (count != 0) {
592 		mtx_lock_spin(&mca_lock);
593 		STAILQ_FOREACH(mca, &mca_records, link) {
594 			if (!mca->logged) {
595 				mca->logged = 1;
596 				mtx_unlock_spin(&mca_lock);
597 				mca_log(&mca->rec);
598 				mtx_lock_spin(&mca_lock);
599 			}
600 		}
601 		mtx_unlock_spin(&mca_lock);
602 	}
603 }
604 
605 static void
606 mca_periodic_scan(void *arg)
607 {
608 
609 	taskqueue_enqueue(taskqueue_thread, &mca_task);
610 	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan, NULL);
611 }
612 
613 static int
614 sysctl_mca_scan(SYSCTL_HANDLER_ARGS)
615 {
616 	int error, i;
617 
618 	i = 0;
619 	error = sysctl_handle_int(oidp, &i, 0, req);
620 	if (error)
621 		return (error);
622 	if (i)
623 		taskqueue_enqueue(taskqueue_thread, &mca_task);
624 	return (0);
625 }
626 
627 static void
628 mca_startup(void *dummy)
629 {
630 
631 	if (!mca_enabled || !(cpu_feature & CPUID_MCA))
632 		return;
633 
634 	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan,
635 		    NULL);
636 }
637 SYSINIT(mca_startup, SI_SUB_SMP, SI_ORDER_ANY, mca_startup, NULL);
638 
639 #ifdef DEV_APIC
640 static void
641 cmci_setup(uint64_t mcg_cap)
642 {
643 	int i;
644 
645 	cmc_state = malloc((mp_maxid + 1) * sizeof(struct cmc_state **),
646 	    M_MCA, M_WAITOK);
647 	cmc_banks = mcg_cap & MCG_CAP_COUNT;
648 	for (i = 0; i <= mp_maxid; i++)
649 		cmc_state[i] = malloc(sizeof(struct cmc_state) * cmc_banks,
650 		    M_MCA, M_WAITOK | M_ZERO);
651 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
652 	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
653 	    &cmc_throttle, 0, sysctl_positive_int, "I",
654 	    "Interval in seconds to throttle corrected MC interrupts");
655 }
656 #endif
657 
658 static void
659 mca_setup(uint64_t mcg_cap)
660 {
661 
662 	mtx_init(&mca_lock, "mca", NULL, MTX_SPIN);
663 	STAILQ_INIT(&mca_records);
664 	TASK_INIT(&mca_task, 0x8000, mca_scan_cpus, NULL);
665 	callout_init(&mca_timer, CALLOUT_MPSAFE);
666 	SYSCTL_ADD_INT(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
667 	    "count", CTLFLAG_RD, &mca_count, 0, "Record count");
668 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
669 	    "interval", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, &mca_ticks,
670 	    0, sysctl_positive_int, "I",
671 	    "Periodic interval in seconds to scan for machine checks");
672 	SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
673 	    "records", CTLFLAG_RD, sysctl_mca_records, "Machine check records");
674 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
675 	    "force_scan", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
676 	    sysctl_mca_scan, "I", "Force an immediate scan for machine checks");
677 #ifdef DEV_APIC
678 	if (mcg_cap & MCG_CAP_CMCI_P)
679 		cmci_setup(mcg_cap);
680 #endif
681 }
682 
683 #ifdef DEV_APIC
684 /*
685  * See if we should monitor CMCI for this bank.  If CMCI_EN is already
686  * set in MC_CTL2, then another CPU is responsible for this bank, so
687  * ignore it.  If CMCI_EN returns zero after being set, then this bank
688  * does not support CMCI_EN.  If this CPU sets CMCI_EN, then it should
689  * now monitor this bank.
690  */
691 static void
692 cmci_monitor(int i)
693 {
694 	struct cmc_state *cc;
695 	uint64_t ctl;
696 
697 	KASSERT(i < cmc_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
698 
699 	ctl = rdmsr(MSR_MC_CTL2(i));
700 	if (ctl & MC_CTL2_CMCI_EN)
701 		/* Already monitored by another CPU. */
702 		return;
703 
704 	/* Set the threshold to one event for now. */
705 	ctl &= ~MC_CTL2_THRESHOLD;
706 	ctl |= MC_CTL2_CMCI_EN | 1;
707 	wrmsr(MSR_MC_CTL2(i), ctl);
708 	ctl = rdmsr(MSR_MC_CTL2(i));
709 	if (!(ctl & MC_CTL2_CMCI_EN))
710 		/* This bank does not support CMCI. */
711 		return;
712 
713 	cc = &cmc_state[PCPU_GET(cpuid)][i];
714 
715 	/* Determine maximum threshold. */
716 	ctl &= ~MC_CTL2_THRESHOLD;
717 	ctl |= 0x7fff;
718 	wrmsr(MSR_MC_CTL2(i), ctl);
719 	ctl = rdmsr(MSR_MC_CTL2(i));
720 	cc->max_threshold = ctl & MC_CTL2_THRESHOLD;
721 
722 	/* Start off with a threshold of 1. */
723 	ctl &= ~MC_CTL2_THRESHOLD;
724 	ctl |= 1;
725 	wrmsr(MSR_MC_CTL2(i), ctl);
726 
727 	/* Mark this bank as monitored. */
728 	PCPU_SET(cmci_mask, PCPU_GET(cmci_mask) | 1 << i);
729 }
730 #endif
731 
732 /* Must be executed on each CPU. */
733 void
734 mca_init(void)
735 {
736 	uint64_t mcg_cap;
737 	uint64_t ctl, mask;
738 	int skip;
739 	int i;
740 
741 	/* MCE is required. */
742 	if (!mca_enabled || !(cpu_feature & CPUID_MCE))
743 		return;
744 
745 	/*
746 	 * On AMD Family 10h processors, unless logging of level one TLB
747 	 * parity (L1TP) errors is disabled, enable the recommended workaround
748 	 * for Erratum 383.
749 	 */
750 	if (cpu_vendor_id == CPU_VENDOR_AMD &&
751 	    CPUID_TO_FAMILY(cpu_id) == 0x10 && amd10h_L1TP)
752 		workaround_erratum383 = 1;
753 
754 	if (cpu_feature & CPUID_MCA) {
755 		PCPU_SET(cmci_mask, 0);
756 
757 		mcg_cap = rdmsr(MSR_MCG_CAP);
758 		if (mcg_cap & MCG_CAP_CTL_P)
759 			/* Enable MCA features. */
760 			wrmsr(MSR_MCG_CTL, MCG_CTL_ENABLE);
761 		if (PCPU_GET(cpuid) == 0)
762 			mca_setup(mcg_cap);
763 
764 		/*
765 		 * Disable logging of level one TLB parity (L1TP) errors by
766 		 * the data cache as an alternative workaround for AMD Family
767 		 * 10h Erratum 383.  Unlike the recommended workaround, there
768 		 * is no performance penalty to this workaround.  However,
769 		 * L1TP errors will go unreported.
770 		 */
771 		if (cpu_vendor_id == CPU_VENDOR_AMD &&
772 		    CPUID_TO_FAMILY(cpu_id) == 0x10 && !amd10h_L1TP) {
773 			mask = rdmsr(MSR_MC0_CTL_MASK);
774 			if ((mask & (1UL << 5)) == 0)
775 				wrmsr(MSR_MC0_CTL_MASK, mask | (1UL << 5));
776 		}
777 		for (i = 0; i < (mcg_cap & MCG_CAP_COUNT); i++) {
778 			/* By default enable logging of all errors. */
779 			ctl = 0xffffffffffffffffUL;
780 			skip = 0;
781 
782 			if (cpu_vendor_id == CPU_VENDOR_INTEL) {
783 				/*
784 				 * For P6 models before Nehalem MC0_CTL is
785 				 * always enabled and reserved.
786 				 */
787 				if (i == 0 && CPUID_TO_FAMILY(cpu_id) == 0x6
788 				    && CPUID_TO_MODEL(cpu_id) < 0x1a)
789 					skip = 1;
790 			} else if (cpu_vendor_id == CPU_VENDOR_AMD) {
791 				/* BKDG for Family 10h: unset GartTblWkEn. */
792 				if (i == 4 && CPUID_TO_FAMILY(cpu_id) >= 0xf)
793 					ctl &= ~(1UL << 10);
794 			}
795 
796 			if (!skip)
797 				wrmsr(MSR_MC_CTL(i), ctl);
798 
799 #ifdef DEV_APIC
800 			if (mcg_cap & MCG_CAP_CMCI_P)
801 				cmci_monitor(i);
802 #endif
803 
804 			/* Clear all errors. */
805 			wrmsr(MSR_MC_STATUS(i), 0);
806 		}
807 
808 #ifdef DEV_APIC
809 		if (PCPU_GET(cmci_mask) != 0)
810 			lapic_enable_cmc();
811 #endif
812 	}
813 
814 	load_cr4(rcr4() | CR4_MCE);
815 }
816 
817 /*
818  * The machine check registers for the BSP cannot be initialized until
819  * the local APIC is initialized.  This happens at SI_SUB_CPU,
820  * SI_ORDER_SECOND.
821  */
822 static void
823 mca_init_bsp(void *arg __unused)
824 {
825 
826 	mca_init();
827 }
828 SYSINIT(mca_init_bsp, SI_SUB_CPU, SI_ORDER_ANY, mca_init_bsp, NULL);
829 
830 /* Called when a machine check exception fires. */
831 int
832 mca_intr(void)
833 {
834 	uint64_t mcg_status;
835 	int recoverable;
836 
837 	if (!(cpu_feature & CPUID_MCA)) {
838 		/*
839 		 * Just print the values of the old Pentium registers
840 		 * and panic.
841 		 */
842 		printf("MC Type: 0x%jx  Address: 0x%jx\n",
843 		    (uintmax_t)rdmsr(MSR_P5_MC_TYPE),
844 		    (uintmax_t)rdmsr(MSR_P5_MC_ADDR));
845 		return (0);
846 	}
847 
848 	/* Scan the banks and check for any non-recoverable errors. */
849 	recoverable = mca_scan(MCE);
850 	mcg_status = rdmsr(MSR_MCG_STATUS);
851 	if (!(mcg_status & MCG_STATUS_RIPV))
852 		recoverable = 0;
853 
854 	/* Clear MCIP. */
855 	wrmsr(MSR_MCG_STATUS, mcg_status & ~MCG_STATUS_MCIP);
856 	return (recoverable);
857 }
858 
859 #ifdef DEV_APIC
860 /* Called for a CMCI (correctable machine check interrupt). */
861 void
862 cmc_intr(void)
863 {
864 	struct mca_internal *mca;
865 	int count;
866 
867 	/*
868 	 * Serialize MCA bank scanning to prevent collisions from
869 	 * sibling threads.
870 	 */
871 	count = mca_scan(CMCI);
872 
873 	/* If we found anything, log them to the console. */
874 	if (count != 0) {
875 		mtx_lock_spin(&mca_lock);
876 		STAILQ_FOREACH(mca, &mca_records, link) {
877 			if (!mca->logged) {
878 				mca->logged = 1;
879 				mtx_unlock_spin(&mca_lock);
880 				mca_log(&mca->rec);
881 				mtx_lock_spin(&mca_lock);
882 			}
883 		}
884 		mtx_unlock_spin(&mca_lock);
885 	}
886 }
887 #endif
888