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