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