xref: /freebsd/sys/x86/x86/mca.c (revision 206b73d0)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2009 Hudson River Trading LLC
5  * Written by: John H. Baldwin <jhb@FreeBSD.org>
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 /*
31  * Support for x86 machine check architecture.
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #ifdef __amd64__
38 #define	DEV_APIC
39 #else
40 #include "opt_apic.h"
41 #endif
42 
43 #include <sys/param.h>
44 #include <sys/bus.h>
45 #include <sys/interrupt.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/malloc.h>
49 #include <sys/mutex.h>
50 #include <sys/proc.h>
51 #include <sys/sched.h>
52 #include <sys/smp.h>
53 #include <sys/sysctl.h>
54 #include <sys/systm.h>
55 #include <sys/taskqueue.h>
56 #include <machine/intr_machdep.h>
57 #include <x86/apicvar.h>
58 #include <machine/cpu.h>
59 #include <machine/cputypes.h>
60 #include <x86/mca.h>
61 #include <machine/md_var.h>
62 #include <machine/specialreg.h>
63 
64 /* Modes for mca_scan() */
65 enum scan_mode {
66 	POLLED,
67 	MCE,
68 	CMCI,
69 };
70 
71 #ifdef DEV_APIC
72 /*
73  * State maintained for each monitored MCx bank to control the
74  * corrected machine check interrupt threshold.
75  */
76 struct cmc_state {
77 	int	max_threshold;
78 	time_t	last_intr;
79 };
80 
81 struct amd_et_state {
82 	int	cur_threshold;
83 	time_t	last_intr;
84 };
85 #endif
86 
87 struct mca_internal {
88 	struct mca_record rec;
89 	STAILQ_ENTRY(mca_internal) link;
90 };
91 
92 struct mca_enumerator_ops {
93         unsigned int (*ctl)(int);
94         unsigned int (*status)(int);
95         unsigned int (*addr)(int);
96         unsigned int (*misc)(int);
97 };
98 
99 static MALLOC_DEFINE(M_MCA, "MCA", "Machine Check Architecture");
100 
101 static volatile int mca_count;	/* Number of records stored. */
102 static int mca_banks;		/* Number of per-CPU register banks. */
103 static int mca_maxcount = -1;	/* Limit on records stored. (-1 = unlimited) */
104 
105 static SYSCTL_NODE(_hw, OID_AUTO, mca, CTLFLAG_RD, NULL,
106     "Machine Check Architecture");
107 
108 static int mca_enabled = 1;
109 SYSCTL_INT(_hw_mca, OID_AUTO, enabled, CTLFLAG_RDTUN, &mca_enabled, 0,
110     "Administrative toggle for machine check support");
111 
112 static int amd10h_L1TP = 1;
113 SYSCTL_INT(_hw_mca, OID_AUTO, amd10h_L1TP, CTLFLAG_RDTUN, &amd10h_L1TP, 0,
114     "Administrative toggle for logging of level one TLB parity (L1TP) errors");
115 
116 static int intel6h_HSD131;
117 SYSCTL_INT(_hw_mca, OID_AUTO, intel6h_HSD131, CTLFLAG_RDTUN, &intel6h_HSD131, 0,
118     "Administrative toggle for logging of spurious corrected errors");
119 
120 int workaround_erratum383;
121 SYSCTL_INT(_hw_mca, OID_AUTO, erratum383, CTLFLAG_RDTUN,
122     &workaround_erratum383, 0,
123     "Is the workaround for Erratum 383 on AMD Family 10h processors enabled?");
124 
125 static STAILQ_HEAD(, mca_internal) mca_freelist;
126 static int mca_freecount;
127 static STAILQ_HEAD(, mca_internal) mca_records;
128 static STAILQ_HEAD(, mca_internal) mca_pending;
129 static struct callout mca_timer;
130 static int mca_ticks = 3600;	/* Check hourly by default. */
131 static struct taskqueue *mca_tq;
132 static struct task mca_resize_task, mca_scan_task;
133 static struct mtx mca_lock;
134 
135 static unsigned int
136 mca_ia32_ctl_reg(int bank)
137 {
138 	return (MSR_MC_CTL(bank));
139 }
140 
141 static unsigned int
142 mca_ia32_status_reg(int bank)
143 {
144 	return (MSR_MC_STATUS(bank));
145 }
146 
147 static unsigned int
148 mca_ia32_addr_reg(int bank)
149 {
150 	return (MSR_MC_ADDR(bank));
151 }
152 
153 static unsigned int
154 mca_ia32_misc_reg(int bank)
155 {
156 	return (MSR_MC_MISC(bank));
157 }
158 
159 static unsigned int
160 mca_smca_ctl_reg(int bank)
161 {
162         return (MSR_SMCA_MC_CTL(bank));
163 }
164 
165 static unsigned int
166 mca_smca_status_reg(int bank)
167 {
168         return (MSR_SMCA_MC_STATUS(bank));
169 }
170 
171 static unsigned int
172 mca_smca_addr_reg(int bank)
173 {
174         return (MSR_SMCA_MC_ADDR(bank));
175 }
176 
177 static unsigned int
178 mca_smca_misc_reg(int bank)
179 {
180         return (MSR_SMCA_MC_MISC(bank));
181 }
182 
183 static struct mca_enumerator_ops mca_msr_ops = {
184         .ctl    = mca_ia32_ctl_reg,
185         .status = mca_ia32_status_reg,
186         .addr   = mca_ia32_addr_reg,
187         .misc   = mca_ia32_misc_reg
188 };
189 
190 #ifdef DEV_APIC
191 static struct cmc_state **cmc_state;		/* Indexed by cpuid, bank. */
192 static struct amd_et_state **amd_et_state;	/* Indexed by cpuid, bank. */
193 static int cmc_throttle = 60;	/* Time in seconds to throttle CMCI. */
194 
195 static int amd_elvt = -1;
196 
197 static inline bool
198 amd_thresholding_supported(void)
199 {
200 	if (cpu_vendor_id != CPU_VENDOR_AMD)
201 		return (false);
202 	/*
203 	 * The RASCap register is wholly reserved in families 0x10-0x15 (through model 1F).
204 	 *
205 	 * It begins to be documented in family 0x15 model 30 and family 0x16,
206 	 * but neither of these families documents the ScalableMca bit, which
207 	 * supposedly defines the presence of this feature on family 0x17.
208 	 */
209 	if (CPUID_TO_FAMILY(cpu_id) >= 0x10 && CPUID_TO_FAMILY(cpu_id) <= 0x16)
210 		return (true);
211 	if (CPUID_TO_FAMILY(cpu_id) >= 0x17)
212 		return ((amd_rascap & AMDRAS_SCALABLE_MCA) != 0);
213 	return (false);
214 }
215 #endif
216 
217 static inline bool
218 cmci_supported(uint64_t mcg_cap)
219 {
220 	/*
221 	 * MCG_CAP_CMCI_P bit is reserved in AMD documentation.  Until
222 	 * it is defined, do not use it to check for CMCI support.
223 	 */
224 	if (cpu_vendor_id != CPU_VENDOR_INTEL)
225 		return (false);
226 	return ((mcg_cap & MCG_CAP_CMCI_P) != 0);
227 }
228 
229 static int
230 sysctl_positive_int(SYSCTL_HANDLER_ARGS)
231 {
232 	int error, value;
233 
234 	value = *(int *)arg1;
235 	error = sysctl_handle_int(oidp, &value, 0, req);
236 	if (error || req->newptr == NULL)
237 		return (error);
238 	if (value <= 0)
239 		return (EINVAL);
240 	*(int *)arg1 = value;
241 	return (0);
242 }
243 
244 static int
245 sysctl_mca_records(SYSCTL_HANDLER_ARGS)
246 {
247 	int *name = (int *)arg1;
248 	u_int namelen = arg2;
249 	struct mca_record record;
250 	struct mca_internal *rec;
251 	int i;
252 
253 	if (namelen != 1)
254 		return (EINVAL);
255 
256 	if (name[0] < 0 || name[0] >= mca_count)
257 		return (EINVAL);
258 
259 	mtx_lock_spin(&mca_lock);
260 	if (name[0] >= mca_count) {
261 		mtx_unlock_spin(&mca_lock);
262 		return (EINVAL);
263 	}
264 	i = 0;
265 	STAILQ_FOREACH(rec, &mca_records, link) {
266 		if (i == name[0]) {
267 			record = rec->rec;
268 			break;
269 		}
270 		i++;
271 	}
272 	mtx_unlock_spin(&mca_lock);
273 	return (SYSCTL_OUT(req, &record, sizeof(record)));
274 }
275 
276 static const char *
277 mca_error_ttype(uint16_t mca_error)
278 {
279 
280 	switch ((mca_error & 0x000c) >> 2) {
281 	case 0:
282 		return ("I");
283 	case 1:
284 		return ("D");
285 	case 2:
286 		return ("G");
287 	}
288 	return ("?");
289 }
290 
291 static const char *
292 mca_error_level(uint16_t mca_error)
293 {
294 
295 	switch (mca_error & 0x0003) {
296 	case 0:
297 		return ("L0");
298 	case 1:
299 		return ("L1");
300 	case 2:
301 		return ("L2");
302 	case 3:
303 		return ("LG");
304 	}
305 	return ("L?");
306 }
307 
308 static const char *
309 mca_error_request(uint16_t mca_error)
310 {
311 
312 	switch ((mca_error & 0x00f0) >> 4) {
313 	case 0x0:
314 		return ("ERR");
315 	case 0x1:
316 		return ("RD");
317 	case 0x2:
318 		return ("WR");
319 	case 0x3:
320 		return ("DRD");
321 	case 0x4:
322 		return ("DWR");
323 	case 0x5:
324 		return ("IRD");
325 	case 0x6:
326 		return ("PREFETCH");
327 	case 0x7:
328 		return ("EVICT");
329 	case 0x8:
330 		return ("SNOOP");
331 	}
332 	return ("???");
333 }
334 
335 static const char *
336 mca_error_mmtype(uint16_t mca_error)
337 {
338 
339 	switch ((mca_error & 0x70) >> 4) {
340 	case 0x0:
341 		return ("GEN");
342 	case 0x1:
343 		return ("RD");
344 	case 0x2:
345 		return ("WR");
346 	case 0x3:
347 		return ("AC");
348 	case 0x4:
349 		return ("MS");
350 	}
351 	return ("???");
352 }
353 
354 static int
355 mca_mute(const struct mca_record *rec)
356 {
357 
358 	/*
359 	 * Skip spurious corrected parity errors generated by Intel Haswell-
360 	 * and Broadwell-based CPUs (see HSD131, HSM142, HSW131 and BDM48
361 	 * erratum respectively), unless reporting is enabled.
362 	 * Note that these errors also have been observed with the D0-stepping
363 	 * of Haswell, while at least initially the CPU specification updates
364 	 * suggested only the C0-stepping to be affected.  Similarly, Celeron
365 	 * 2955U with a CPU ID of 0x45 apparently are also concerned with the
366 	 * same problem, with HSM142 only referring to 0x3c and 0x46.
367 	 */
368 	if (cpu_vendor_id == CPU_VENDOR_INTEL &&
369 	    CPUID_TO_FAMILY(cpu_id) == 0x6 &&
370 	    (CPUID_TO_MODEL(cpu_id) == 0x3c ||	/* HSD131, HSM142, HSW131 */
371 	    CPUID_TO_MODEL(cpu_id) == 0x3d ||	/* BDM48 */
372 	    CPUID_TO_MODEL(cpu_id) == 0x45 ||
373 	    CPUID_TO_MODEL(cpu_id) == 0x46) &&	/* HSM142 */
374 	    rec->mr_bank == 0 &&
375 	    (rec->mr_status & 0xa0000000ffffffff) == 0x80000000000f0005 &&
376 	    !intel6h_HSD131)
377 	    	return (1);
378 
379 	return (0);
380 }
381 
382 /* Dump details about a single machine check. */
383 static void
384 mca_log(const struct mca_record *rec)
385 {
386 	uint16_t mca_error;
387 
388 	if (mca_mute(rec))
389 	    	return;
390 
391 	printf("MCA: Bank %d, Status 0x%016llx\n", rec->mr_bank,
392 	    (long long)rec->mr_status);
393 	printf("MCA: Global Cap 0x%016llx, Status 0x%016llx\n",
394 	    (long long)rec->mr_mcg_cap, (long long)rec->mr_mcg_status);
395 	printf("MCA: Vendor \"%s\", ID 0x%x, APIC ID %d\n", cpu_vendor,
396 	    rec->mr_cpu_id, rec->mr_apic_id);
397 	printf("MCA: CPU %d ", rec->mr_cpu);
398 	if (rec->mr_status & MC_STATUS_UC)
399 		printf("UNCOR ");
400 	else {
401 		printf("COR ");
402 		if (cmci_supported(rec->mr_mcg_cap))
403 			printf("(%lld) ", ((long long)rec->mr_status &
404 			    MC_STATUS_COR_COUNT) >> 38);
405 	}
406 	if (rec->mr_status & MC_STATUS_PCC)
407 		printf("PCC ");
408 	if (rec->mr_status & MC_STATUS_OVER)
409 		printf("OVER ");
410 	mca_error = rec->mr_status & MC_STATUS_MCA_ERROR;
411 	switch (mca_error) {
412 		/* Simple error codes. */
413 	case 0x0000:
414 		printf("no error");
415 		break;
416 	case 0x0001:
417 		printf("unclassified error");
418 		break;
419 	case 0x0002:
420 		printf("ucode ROM parity error");
421 		break;
422 	case 0x0003:
423 		printf("external error");
424 		break;
425 	case 0x0004:
426 		printf("FRC error");
427 		break;
428 	case 0x0005:
429 		printf("internal parity error");
430 		break;
431 	case 0x0400:
432 		printf("internal timer error");
433 		break;
434 	default:
435 		if ((mca_error & 0xfc00) == 0x0400) {
436 			printf("internal error %x", mca_error & 0x03ff);
437 			break;
438 		}
439 
440 		/* Compound error codes. */
441 
442 		/* Memory hierarchy error. */
443 		if ((mca_error & 0xeffc) == 0x000c) {
444 			printf("%s memory error", mca_error_level(mca_error));
445 			break;
446 		}
447 
448 		/* TLB error. */
449 		if ((mca_error & 0xeff0) == 0x0010) {
450 			printf("%sTLB %s error", mca_error_ttype(mca_error),
451 			    mca_error_level(mca_error));
452 			break;
453 		}
454 
455 		/* Memory controller error. */
456 		if ((mca_error & 0xef80) == 0x0080) {
457 			printf("%s channel ", mca_error_mmtype(mca_error));
458 			if ((mca_error & 0x000f) != 0x000f)
459 				printf("%d", mca_error & 0x000f);
460 			else
461 				printf("??");
462 			printf(" memory error");
463 			break;
464 		}
465 
466 		/* Cache error. */
467 		if ((mca_error & 0xef00) == 0x0100) {
468 			printf("%sCACHE %s %s error",
469 			    mca_error_ttype(mca_error),
470 			    mca_error_level(mca_error),
471 			    mca_error_request(mca_error));
472 			break;
473 		}
474 
475 		/* Bus and/or Interconnect error. */
476 		if ((mca_error & 0xe800) == 0x0800) {
477 			printf("BUS%s ", mca_error_level(mca_error));
478 			switch ((mca_error & 0x0600) >> 9) {
479 			case 0:
480 				printf("Source");
481 				break;
482 			case 1:
483 				printf("Responder");
484 				break;
485 			case 2:
486 				printf("Observer");
487 				break;
488 			default:
489 				printf("???");
490 				break;
491 			}
492 			printf(" %s ", mca_error_request(mca_error));
493 			switch ((mca_error & 0x000c) >> 2) {
494 			case 0:
495 				printf("Memory");
496 				break;
497 			case 2:
498 				printf("I/O");
499 				break;
500 			case 3:
501 				printf("Other");
502 				break;
503 			default:
504 				printf("???");
505 				break;
506 			}
507 			if (mca_error & 0x0100)
508 				printf(" timed out");
509 			break;
510 		}
511 
512 		printf("unknown error %x", mca_error);
513 		break;
514 	}
515 	printf("\n");
516 	if (rec->mr_status & MC_STATUS_ADDRV)
517 		printf("MCA: Address 0x%llx\n", (long long)rec->mr_addr);
518 	if (rec->mr_status & MC_STATUS_MISCV)
519 		printf("MCA: Misc 0x%llx\n", (long long)rec->mr_misc);
520 }
521 
522 static int
523 mca_check_status(int bank, struct mca_record *rec)
524 {
525 	uint64_t status;
526 	u_int p[4];
527 
528 	status = rdmsr(mca_msr_ops.status(bank));
529 	if (!(status & MC_STATUS_VAL))
530 		return (0);
531 
532 	/* Save exception information. */
533 	rec->mr_status = status;
534 	rec->mr_bank = bank;
535 	rec->mr_addr = 0;
536 	if (status & MC_STATUS_ADDRV)
537 		rec->mr_addr = rdmsr(mca_msr_ops.addr(bank));
538 	rec->mr_misc = 0;
539 	if (status & MC_STATUS_MISCV)
540 		rec->mr_misc = rdmsr(mca_msr_ops.misc(bank));
541 	rec->mr_tsc = rdtsc();
542 	rec->mr_apic_id = PCPU_GET(apic_id);
543 	rec->mr_mcg_cap = rdmsr(MSR_MCG_CAP);
544 	rec->mr_mcg_status = rdmsr(MSR_MCG_STATUS);
545 	rec->mr_cpu_id = cpu_id;
546 	rec->mr_cpu_vendor_id = cpu_vendor_id;
547 	rec->mr_cpu = PCPU_GET(cpuid);
548 
549 	/*
550 	 * Clear machine check.  Don't do this for uncorrectable
551 	 * errors so that the BIOS can see them.
552 	 */
553 	if (!(rec->mr_status & (MC_STATUS_PCC | MC_STATUS_UC))) {
554 		wrmsr(mca_msr_ops.status(bank), 0);
555 		do_cpuid(0, p);
556 	}
557 	return (1);
558 }
559 
560 static void
561 mca_resize_freelist(void)
562 {
563 	struct mca_internal *next, *rec;
564 	STAILQ_HEAD(, mca_internal) tmplist;
565 	int count, i, desired_max, desired_min;
566 
567 	/*
568 	 * Ensure we have at least one record for each bank and one
569 	 * record per CPU, but no more than twice that amount.
570 	 */
571 	desired_min = imax(mp_ncpus, mca_banks);
572 	desired_max = imax(mp_ncpus, mca_banks) * 2;
573 	STAILQ_INIT(&tmplist);
574 	mtx_lock_spin(&mca_lock);
575 	while (mca_freecount > desired_max) {
576 		rec = STAILQ_FIRST(&mca_freelist);
577 		KASSERT(rec != NULL, ("mca_freecount is %d, but list is empty",
578 		    mca_freecount));
579 		STAILQ_REMOVE_HEAD(&mca_freelist, link);
580 		mca_freecount--;
581 		STAILQ_INSERT_TAIL(&tmplist, rec, link);
582 	}
583 	while (mca_freecount < desired_min) {
584 		count = desired_min - mca_freecount;
585 		mtx_unlock_spin(&mca_lock);
586 		for (i = 0; i < count; i++) {
587 			rec = malloc(sizeof(*rec), M_MCA, M_WAITOK);
588 			STAILQ_INSERT_TAIL(&tmplist, rec, link);
589 		}
590 		mtx_lock_spin(&mca_lock);
591 		STAILQ_CONCAT(&mca_freelist, &tmplist);
592 		mca_freecount += count;
593 	}
594 	mtx_unlock_spin(&mca_lock);
595 	STAILQ_FOREACH_SAFE(rec, &tmplist, link, next)
596 		free(rec, M_MCA);
597 }
598 
599 static void
600 mca_resize(void *context, int pending)
601 {
602 
603 	mca_resize_freelist();
604 }
605 
606 static void
607 mca_record_entry(enum scan_mode mode, const struct mca_record *record)
608 {
609 	struct mca_internal *rec;
610 
611 	if (mode == POLLED) {
612 		rec = malloc(sizeof(*rec), M_MCA, M_WAITOK);
613 		mtx_lock_spin(&mca_lock);
614 	} else {
615 		mtx_lock_spin(&mca_lock);
616 		rec = STAILQ_FIRST(&mca_freelist);
617 		if (rec == NULL) {
618 			printf("MCA: Unable to allocate space for an event.\n");
619 			mca_log(record);
620 			mtx_unlock_spin(&mca_lock);
621 			return;
622 		}
623 		STAILQ_REMOVE_HEAD(&mca_freelist, link);
624 		mca_freecount--;
625 	}
626 
627 	rec->rec = *record;
628 	STAILQ_INSERT_TAIL(&mca_pending, rec, link);
629 	mtx_unlock_spin(&mca_lock);
630 }
631 
632 #ifdef DEV_APIC
633 /*
634  * Update the interrupt threshold for a CMCI.  The strategy is to use
635  * a low trigger that interrupts as soon as the first event occurs.
636  * However, if a steady stream of events arrive, the threshold is
637  * increased until the interrupts are throttled to once every
638  * cmc_throttle seconds or the periodic scan.  If a periodic scan
639  * finds that the threshold is too high, it is lowered.
640  */
641 static int
642 update_threshold(enum scan_mode mode, int valid, int last_intr, int count,
643     int cur_threshold, int max_threshold)
644 {
645 	u_int delta;
646 	int limit;
647 
648 	delta = (u_int)(time_uptime - last_intr);
649 	limit = cur_threshold;
650 
651 	/*
652 	 * If an interrupt was received less than cmc_throttle seconds
653 	 * since the previous interrupt and the count from the current
654 	 * event is greater than or equal to the current threshold,
655 	 * double the threshold up to the max.
656 	 */
657 	if (mode == CMCI && valid) {
658 		if (delta < cmc_throttle && count >= limit &&
659 		    limit < max_threshold) {
660 			limit = min(limit << 1, max_threshold);
661 		}
662 		return (limit);
663 	}
664 
665 	/*
666 	 * When the banks are polled, check to see if the threshold
667 	 * should be lowered.
668 	 */
669 	if (mode != POLLED)
670 		return (limit);
671 
672 	/* If a CMCI occured recently, do nothing for now. */
673 	if (delta < cmc_throttle)
674 		return (limit);
675 
676 	/*
677 	 * Compute a new limit based on the average rate of events per
678 	 * cmc_throttle seconds since the last interrupt.
679 	 */
680 	if (valid) {
681 		limit = count * cmc_throttle / delta;
682 		if (limit <= 0)
683 			limit = 1;
684 		else if (limit > max_threshold)
685 			limit = max_threshold;
686 	} else {
687 		limit = 1;
688 	}
689 	return (limit);
690 }
691 
692 static void
693 cmci_update(enum scan_mode mode, int bank, int valid, struct mca_record *rec)
694 {
695 	struct cmc_state *cc;
696 	uint64_t ctl;
697 	int cur_threshold, new_threshold;
698 	int count;
699 
700 	/* Fetch the current limit for this bank. */
701 	cc = &cmc_state[PCPU_GET(cpuid)][bank];
702 	ctl = rdmsr(MSR_MC_CTL2(bank));
703 	count = (rec->mr_status & MC_STATUS_COR_COUNT) >> 38;
704 	cur_threshold = ctl & MC_CTL2_THRESHOLD;
705 
706 	new_threshold = update_threshold(mode, valid, cc->last_intr, count,
707 	    cur_threshold, cc->max_threshold);
708 
709 	if (mode == CMCI && valid)
710 		cc->last_intr = time_uptime;
711 	if (new_threshold != cur_threshold) {
712 		ctl &= ~MC_CTL2_THRESHOLD;
713 		ctl |= new_threshold;
714 		wrmsr(MSR_MC_CTL2(bank), ctl);
715 	}
716 }
717 
718 static void
719 amd_thresholding_update(enum scan_mode mode, int bank, int valid)
720 {
721 	struct amd_et_state *cc;
722 	uint64_t misc;
723 	int new_threshold;
724 	int count;
725 
726 	cc = &amd_et_state[PCPU_GET(cpuid)][bank];
727 	misc = rdmsr(mca_msr_ops.misc(bank));
728 	count = (misc & MC_MISC_AMD_CNT_MASK) >> MC_MISC_AMD_CNT_SHIFT;
729 	count = count - (MC_MISC_AMD_CNT_MAX - cc->cur_threshold);
730 
731 	new_threshold = update_threshold(mode, valid, cc->last_intr, count,
732 	    cc->cur_threshold, MC_MISC_AMD_CNT_MAX);
733 
734 	cc->cur_threshold = new_threshold;
735 	misc &= ~MC_MISC_AMD_CNT_MASK;
736 	misc |= (uint64_t)(MC_MISC_AMD_CNT_MAX - cc->cur_threshold)
737 	    << MC_MISC_AMD_CNT_SHIFT;
738 	misc &= ~MC_MISC_AMD_OVERFLOW;
739 	wrmsr(mca_msr_ops.misc(bank), misc);
740 	if (mode == CMCI && valid)
741 		cc->last_intr = time_uptime;
742 }
743 #endif
744 
745 /*
746  * This scans all the machine check banks of the current CPU to see if
747  * there are any machine checks.  Any non-recoverable errors are
748  * reported immediately via mca_log().  The current thread must be
749  * pinned when this is called.  The 'mode' parameter indicates if we
750  * are being called from the MC exception handler, the CMCI handler,
751  * or the periodic poller.  In the MC exception case this function
752  * returns true if the system is restartable.  Otherwise, it returns a
753  * count of the number of valid MC records found.
754  */
755 static int
756 mca_scan(enum scan_mode mode, int *recoverablep)
757 {
758 	struct mca_record rec;
759 	uint64_t mcg_cap, ucmask;
760 	int count, i, recoverable, valid;
761 
762 	count = 0;
763 	recoverable = 1;
764 	ucmask = MC_STATUS_UC | MC_STATUS_PCC;
765 
766 	/* When handling a MCE#, treat the OVER flag as non-restartable. */
767 	if (mode == MCE)
768 		ucmask |= MC_STATUS_OVER;
769 	mcg_cap = rdmsr(MSR_MCG_CAP);
770 	for (i = 0; i < (mcg_cap & MCG_CAP_COUNT); i++) {
771 #ifdef DEV_APIC
772 		/*
773 		 * For a CMCI, only check banks this CPU is
774 		 * responsible for.
775 		 */
776 		if (mode == CMCI && !(PCPU_GET(cmci_mask) & 1 << i))
777 			continue;
778 #endif
779 
780 		valid = mca_check_status(i, &rec);
781 		if (valid) {
782 			count++;
783 			if (rec.mr_status & ucmask) {
784 				recoverable = 0;
785 				mtx_lock_spin(&mca_lock);
786 				mca_log(&rec);
787 				mtx_unlock_spin(&mca_lock);
788 			}
789 			mca_record_entry(mode, &rec);
790 		}
791 
792 #ifdef DEV_APIC
793 		/*
794 		 * If this is a bank this CPU monitors via CMCI,
795 		 * update the threshold.
796 		 */
797 		if (PCPU_GET(cmci_mask) & 1 << i) {
798 			if (cmc_state != NULL)
799 				cmci_update(mode, i, valid, &rec);
800 			else
801 				amd_thresholding_update(mode, i, valid);
802 		}
803 #endif
804 	}
805 	if (recoverablep != NULL)
806 		*recoverablep = recoverable;
807 	return (count);
808 }
809 
810 /*
811  * Store a new record on the mca_records list while enforcing
812  * mca_maxcount.
813  */
814 static void
815 mca_store_record(struct mca_internal *mca)
816 {
817 
818 	/*
819 	 * If we are storing no records (mca_maxcount == 0),
820 	 * we just free this record.
821 	 *
822 	 * If we are storing records (mca_maxcount != 0) and
823 	 * we have free space on the list, store the record
824 	 * and increment mca_count.
825 	 *
826 	 * If we are storing records and we do not have free
827 	 * space on the list, store the new record at the
828 	 * tail and free the oldest one from the head.
829 	 */
830 	if (mca_maxcount != 0)
831 		STAILQ_INSERT_TAIL(&mca_records, mca, link);
832 	if (mca_maxcount < 0 || mca_count < mca_maxcount)
833 		mca_count++;
834 	else {
835 		if (mca_maxcount != 0) {
836 			mca = STAILQ_FIRST(&mca_records);
837 			STAILQ_REMOVE_HEAD(&mca_records, link);
838 		}
839 		STAILQ_INSERT_TAIL(&mca_freelist, mca, link);
840 		mca_freecount++;
841 	}
842 }
843 
844 /*
845  * Do the work to process machine check records which have just been
846  * gathered. Print any pending logs to the console. Queue them for storage.
847  * Trigger a resizing of the free list.
848  */
849 static void
850 mca_process_records(enum scan_mode mode)
851 {
852 	struct mca_internal *mca;
853 
854 	mtx_lock_spin(&mca_lock);
855 	while ((mca = STAILQ_FIRST(&mca_pending)) != NULL) {
856 		STAILQ_REMOVE_HEAD(&mca_pending, link);
857 		mca_log(&mca->rec);
858 		mca_store_record(mca);
859 	}
860 	mtx_unlock_spin(&mca_lock);
861 	if (mode == POLLED)
862 		mca_resize_freelist();
863 	else if (!cold)
864 		taskqueue_enqueue(mca_tq, &mca_resize_task);
865 }
866 
867 /*
868  * Scan the machine check banks on all CPUs by binding to each CPU in
869  * turn.  If any of the CPUs contained new machine check records, log
870  * them to the console.
871  */
872 static void
873 mca_scan_cpus(void *context, int pending)
874 {
875 	struct thread *td;
876 	int count, cpu;
877 
878 	mca_resize_freelist();
879 	td = curthread;
880 	count = 0;
881 	thread_lock(td);
882 	CPU_FOREACH(cpu) {
883 		sched_bind(td, cpu);
884 		thread_unlock(td);
885 		count += mca_scan(POLLED, NULL);
886 		thread_lock(td);
887 		sched_unbind(td);
888 	}
889 	thread_unlock(td);
890 	if (count != 0)
891 		mca_process_records(POLLED);
892 }
893 
894 static void
895 mca_periodic_scan(void *arg)
896 {
897 
898 	taskqueue_enqueue(mca_tq, &mca_scan_task);
899 	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan, NULL);
900 }
901 
902 static int
903 sysctl_mca_scan(SYSCTL_HANDLER_ARGS)
904 {
905 	int error, i;
906 
907 	i = 0;
908 	error = sysctl_handle_int(oidp, &i, 0, req);
909 	if (error)
910 		return (error);
911 	if (i)
912 		taskqueue_enqueue(mca_tq, &mca_scan_task);
913 	return (0);
914 }
915 
916 static int
917 sysctl_mca_maxcount(SYSCTL_HANDLER_ARGS)
918 {
919 	struct mca_internal *mca;
920 	int error, i;
921 	bool doresize;
922 
923 	i = mca_maxcount;
924 	error = sysctl_handle_int(oidp, &i, 0, req);
925 	if (error || req->newptr == NULL)
926 		return (error);
927 	mtx_lock_spin(&mca_lock);
928 	mca_maxcount = i;
929 	doresize = false;
930 	if (mca_maxcount >= 0)
931 		while (mca_count > mca_maxcount) {
932 			mca = STAILQ_FIRST(&mca_records);
933 			STAILQ_REMOVE_HEAD(&mca_records, link);
934 			mca_count--;
935 			STAILQ_INSERT_TAIL(&mca_freelist, mca, link);
936 			mca_freecount++;
937 			doresize = true;
938 		}
939 	mtx_unlock_spin(&mca_lock);
940 	if (doresize && !cold)
941 		taskqueue_enqueue(mca_tq, &mca_resize_task);
942 	return (error);
943 }
944 
945 static void
946 mca_createtq(void *dummy)
947 {
948 	if (mca_banks <= 0)
949 		return;
950 
951 	mca_tq = taskqueue_create_fast("mca", M_WAITOK,
952 	    taskqueue_thread_enqueue, &mca_tq);
953 	taskqueue_start_threads(&mca_tq, 1, PI_SWI(SWI_TQ), "mca taskq");
954 
955 	/* CMCIs during boot may have claimed items from the freelist. */
956 	mca_resize_freelist();
957 }
958 SYSINIT(mca_createtq, SI_SUB_CONFIGURE, SI_ORDER_ANY, mca_createtq, NULL);
959 
960 static void
961 mca_startup(void *dummy)
962 {
963 
964 	if (mca_banks <= 0)
965 		return;
966 
967 	callout_reset(&mca_timer, mca_ticks * hz, mca_periodic_scan, NULL);
968 }
969 #ifdef EARLY_AP_STARTUP
970 SYSINIT(mca_startup, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, mca_startup, NULL);
971 #else
972 SYSINIT(mca_startup, SI_SUB_SMP, SI_ORDER_ANY, mca_startup, NULL);
973 #endif
974 
975 #ifdef DEV_APIC
976 static void
977 cmci_setup(void)
978 {
979 	int i;
980 
981 	cmc_state = malloc((mp_maxid + 1) * sizeof(struct cmc_state *), M_MCA,
982 	    M_WAITOK);
983 	for (i = 0; i <= mp_maxid; i++)
984 		cmc_state[i] = malloc(sizeof(struct cmc_state) * mca_banks,
985 		    M_MCA, M_WAITOK | M_ZERO);
986 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
987 	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
988 	    &cmc_throttle, 0, sysctl_positive_int, "I",
989 	    "Interval in seconds to throttle corrected MC interrupts");
990 }
991 
992 static void
993 amd_thresholding_setup(void)
994 {
995 	u_int i;
996 
997 	amd_et_state = malloc((mp_maxid + 1) * sizeof(struct amd_et_state *),
998 	    M_MCA, M_WAITOK);
999 	for (i = 0; i <= mp_maxid; i++)
1000 		amd_et_state[i] = malloc(sizeof(struct amd_et_state) *
1001 		    mca_banks, M_MCA, M_WAITOK | M_ZERO);
1002 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1003 	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
1004 	    &cmc_throttle, 0, sysctl_positive_int, "I",
1005 	    "Interval in seconds to throttle corrected MC interrupts");
1006 }
1007 #endif
1008 
1009 static void
1010 mca_setup(uint64_t mcg_cap)
1011 {
1012 
1013 	/*
1014 	 * On AMD Family 10h processors, unless logging of level one TLB
1015 	 * parity (L1TP) errors is disabled, enable the recommended workaround
1016 	 * for Erratum 383.
1017 	 */
1018 	if (cpu_vendor_id == CPU_VENDOR_AMD &&
1019 	    CPUID_TO_FAMILY(cpu_id) == 0x10 && amd10h_L1TP)
1020 		workaround_erratum383 = 1;
1021 
1022 	mca_banks = mcg_cap & MCG_CAP_COUNT;
1023 	mtx_init(&mca_lock, "mca", NULL, MTX_SPIN);
1024 	STAILQ_INIT(&mca_records);
1025 	STAILQ_INIT(&mca_pending);
1026 	TASK_INIT(&mca_scan_task, 0, mca_scan_cpus, NULL);
1027 	callout_init(&mca_timer, 1);
1028 	STAILQ_INIT(&mca_freelist);
1029 	TASK_INIT(&mca_resize_task, 0, mca_resize, NULL);
1030 	mca_resize_freelist();
1031 	SYSCTL_ADD_INT(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1032 	    "count", CTLFLAG_RD, (int *)(uintptr_t)&mca_count, 0,
1033 	    "Record count");
1034 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1035 	    "maxcount", CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1036 	    &mca_maxcount, 0, sysctl_mca_maxcount, "I",
1037 	    "Maximum record count (-1 is unlimited)");
1038 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1039 	    "interval", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, &mca_ticks,
1040 	    0, sysctl_positive_int, "I",
1041 	    "Periodic interval in seconds to scan for machine checks");
1042 	SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1043 	    "records", CTLFLAG_RD, sysctl_mca_records, "Machine check records");
1044 	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1045 	    "force_scan", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
1046 	    sysctl_mca_scan, "I", "Force an immediate scan for machine checks");
1047 #ifdef DEV_APIC
1048 	if (cmci_supported(mcg_cap))
1049 		cmci_setup();
1050 	else if (amd_thresholding_supported())
1051 		amd_thresholding_setup();
1052 #endif
1053 }
1054 
1055 #ifdef DEV_APIC
1056 /*
1057  * See if we should monitor CMCI for this bank.  If CMCI_EN is already
1058  * set in MC_CTL2, then another CPU is responsible for this bank, so
1059  * ignore it.  If CMCI_EN returns zero after being set, then this bank
1060  * does not support CMCI_EN.  If this CPU sets CMCI_EN, then it should
1061  * now monitor this bank.
1062  */
1063 static void
1064 cmci_monitor(int i)
1065 {
1066 	struct cmc_state *cc;
1067 	uint64_t ctl;
1068 
1069 	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1070 
1071 	ctl = rdmsr(MSR_MC_CTL2(i));
1072 	if (ctl & MC_CTL2_CMCI_EN)
1073 		/* Already monitored by another CPU. */
1074 		return;
1075 
1076 	/* Set the threshold to one event for now. */
1077 	ctl &= ~MC_CTL2_THRESHOLD;
1078 	ctl |= MC_CTL2_CMCI_EN | 1;
1079 	wrmsr(MSR_MC_CTL2(i), ctl);
1080 	ctl = rdmsr(MSR_MC_CTL2(i));
1081 	if (!(ctl & MC_CTL2_CMCI_EN))
1082 		/* This bank does not support CMCI. */
1083 		return;
1084 
1085 	cc = &cmc_state[PCPU_GET(cpuid)][i];
1086 
1087 	/* Determine maximum threshold. */
1088 	ctl &= ~MC_CTL2_THRESHOLD;
1089 	ctl |= 0x7fff;
1090 	wrmsr(MSR_MC_CTL2(i), ctl);
1091 	ctl = rdmsr(MSR_MC_CTL2(i));
1092 	cc->max_threshold = ctl & MC_CTL2_THRESHOLD;
1093 
1094 	/* Start off with a threshold of 1. */
1095 	ctl &= ~MC_CTL2_THRESHOLD;
1096 	ctl |= 1;
1097 	wrmsr(MSR_MC_CTL2(i), ctl);
1098 
1099 	/* Mark this bank as monitored. */
1100 	PCPU_SET(cmci_mask, PCPU_GET(cmci_mask) | 1 << i);
1101 }
1102 
1103 /*
1104  * For resume, reset the threshold for any banks we monitor back to
1105  * one and throw away the timestamp of the last interrupt.
1106  */
1107 static void
1108 cmci_resume(int i)
1109 {
1110 	struct cmc_state *cc;
1111 	uint64_t ctl;
1112 
1113 	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1114 
1115 	/* Ignore banks not monitored by this CPU. */
1116 	if (!(PCPU_GET(cmci_mask) & 1 << i))
1117 		return;
1118 
1119 	cc = &cmc_state[PCPU_GET(cpuid)][i];
1120 	cc->last_intr = 0;
1121 	ctl = rdmsr(MSR_MC_CTL2(i));
1122 	ctl &= ~MC_CTL2_THRESHOLD;
1123 	ctl |= MC_CTL2_CMCI_EN | 1;
1124 	wrmsr(MSR_MC_CTL2(i), ctl);
1125 }
1126 
1127 /*
1128  * Apply an AMD ET configuration to the corresponding MSR.
1129  */
1130 static void
1131 amd_thresholding_start(struct amd_et_state *cc, int bank)
1132 {
1133 	uint64_t misc;
1134 
1135 	KASSERT(amd_elvt >= 0, ("ELVT offset is not set"));
1136 
1137 	misc = rdmsr(mca_msr_ops.misc(bank));
1138 
1139 	misc &= ~MC_MISC_AMD_INT_MASK;
1140 	misc |= MC_MISC_AMD_INT_LVT;
1141 
1142 	misc &= ~MC_MISC_AMD_LVT_MASK;
1143 	misc |= (uint64_t)amd_elvt << MC_MISC_AMD_LVT_SHIFT;
1144 
1145 	misc &= ~MC_MISC_AMD_CNT_MASK;
1146 	misc |= (uint64_t)(MC_MISC_AMD_CNT_MAX - cc->cur_threshold)
1147 	    << MC_MISC_AMD_CNT_SHIFT;
1148 
1149 	misc &= ~MC_MISC_AMD_OVERFLOW;
1150 	misc |= MC_MISC_AMD_CNTEN;
1151 
1152 	wrmsr(mca_msr_ops.misc(bank), misc);
1153 }
1154 
1155 static void
1156 amd_thresholding_monitor(int i)
1157 {
1158 	struct amd_et_state *cc;
1159 	uint64_t misc;
1160 
1161 	/*
1162 	 * Kludge: On 10h, banks after 4 are not thresholding but also may have
1163 	 * bogus Valid bits.  Skip them.  This is definitely fixed in 15h, but
1164 	 * I have not investigated whether it is fixed in earlier models.
1165 	 */
1166 	if (CPUID_TO_FAMILY(cpu_id) < 0x15 && i >= 5)
1167 		return;
1168 
1169 	/* The counter must be valid and present. */
1170 	misc = rdmsr(mca_msr_ops.misc(i));
1171 	if ((misc & (MC_MISC_AMD_VAL | MC_MISC_AMD_CNTP)) !=
1172 	    (MC_MISC_AMD_VAL | MC_MISC_AMD_CNTP))
1173 		return;
1174 
1175 	/* The register should not be locked. */
1176 	if ((misc & MC_MISC_AMD_LOCK) != 0) {
1177 		if (bootverbose)
1178 			printf("%s: 0x%jx: Bank %d: locked\n", __func__,
1179 			    (uintmax_t)misc, i);
1180 		return;
1181 	}
1182 
1183 	/*
1184 	 * If counter is enabled then either the firmware or another CPU
1185 	 * has already claimed it.
1186 	 */
1187 	if ((misc & MC_MISC_AMD_CNTEN) != 0) {
1188 		if (bootverbose)
1189 			printf("%s: 0x%jx: Bank %d: already enabled\n",
1190 			    __func__, (uintmax_t)misc, i);
1191 		return;
1192 	}
1193 
1194 	/*
1195 	 * Configure an Extended Interrupt LVT register for reporting
1196 	 * counter overflows if that feature is supported and the first
1197 	 * extended register is available.
1198 	 */
1199 	amd_elvt = lapic_enable_mca_elvt();
1200 	if (amd_elvt < 0) {
1201 		printf("%s: Bank %d: lapic enable mca elvt failed: %d\n",
1202 		    __func__, i, amd_elvt);
1203 		return;
1204 	}
1205 
1206 	/* Re-use Intel CMC support infrastructure. */
1207 	if (bootverbose)
1208 		printf("%s: Starting AMD thresholding on bank %d\n", __func__,
1209 		    i);
1210 
1211 	cc = &amd_et_state[PCPU_GET(cpuid)][i];
1212 	cc->cur_threshold = 1;
1213 	amd_thresholding_start(cc, i);
1214 
1215 	/* Mark this bank as monitored. */
1216 	PCPU_SET(cmci_mask, PCPU_GET(cmci_mask) | 1 << i);
1217 }
1218 
1219 static void
1220 amd_thresholding_resume(int i)
1221 {
1222 	struct amd_et_state *cc;
1223 
1224 	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1225 
1226 	/* Ignore banks not monitored by this CPU. */
1227 	if (!(PCPU_GET(cmci_mask) & 1 << i))
1228 		return;
1229 
1230 	cc = &amd_et_state[PCPU_GET(cpuid)][i];
1231 	cc->last_intr = 0;
1232 	cc->cur_threshold = 1;
1233 	amd_thresholding_start(cc, i);
1234 }
1235 #endif
1236 
1237 /*
1238  * Initializes per-CPU machine check registers and enables corrected
1239  * machine check interrupts.
1240  */
1241 static void
1242 _mca_init(int boot)
1243 {
1244 	uint64_t mcg_cap;
1245 	uint64_t ctl, mask;
1246 	int i, skip, family;
1247 
1248 	family = CPUID_TO_FAMILY(cpu_id);
1249 
1250 	/* MCE is required. */
1251 	if (!mca_enabled || !(cpu_feature & CPUID_MCE))
1252 		return;
1253 
1254 	if (cpu_feature & CPUID_MCA) {
1255 		if (boot)
1256 			PCPU_SET(cmci_mask, 0);
1257 
1258 		mcg_cap = rdmsr(MSR_MCG_CAP);
1259 		if (mcg_cap & MCG_CAP_CTL_P)
1260 			/* Enable MCA features. */
1261 			wrmsr(MSR_MCG_CTL, MCG_CTL_ENABLE);
1262 		if (IS_BSP() && boot)
1263 			mca_setup(mcg_cap);
1264 
1265 		/*
1266 		 * Disable logging of level one TLB parity (L1TP) errors by
1267 		 * the data cache as an alternative workaround for AMD Family
1268 		 * 10h Erratum 383.  Unlike the recommended workaround, there
1269 		 * is no performance penalty to this workaround.  However,
1270 		 * L1TP errors will go unreported.
1271 		 */
1272 		if (cpu_vendor_id == CPU_VENDOR_AMD && family == 0x10 &&
1273 		    !amd10h_L1TP) {
1274 			mask = rdmsr(MSR_MC0_CTL_MASK);
1275 			if ((mask & (1UL << 5)) == 0)
1276 				wrmsr(MSR_MC0_CTL_MASK, mask | (1UL << 5));
1277 		}
1278 		if (amd_rascap & AMDRAS_SCALABLE_MCA) {
1279 			mca_msr_ops.ctl = mca_smca_ctl_reg;
1280 			mca_msr_ops.status = mca_smca_status_reg;
1281 			mca_msr_ops.addr = mca_smca_addr_reg;
1282 			mca_msr_ops.misc = mca_smca_misc_reg;
1283 		}
1284 
1285 		/*
1286 		 * The cmci_monitor() must not be executed
1287 		 * simultaneously by several CPUs.
1288 		 */
1289 		if (boot)
1290 			mtx_lock_spin(&mca_lock);
1291 
1292 		for (i = 0; i < (mcg_cap & MCG_CAP_COUNT); i++) {
1293 			/* By default enable logging of all errors. */
1294 			ctl = 0xffffffffffffffffUL;
1295 			skip = 0;
1296 
1297 			if (cpu_vendor_id == CPU_VENDOR_INTEL) {
1298 				/*
1299 				 * For P6 models before Nehalem MC0_CTL is
1300 				 * always enabled and reserved.
1301 				 */
1302 				if (i == 0 && family == 0x6
1303 				    && CPUID_TO_MODEL(cpu_id) < 0x1a)
1304 					skip = 1;
1305 			} else if (cpu_vendor_id == CPU_VENDOR_AMD) {
1306 				/* BKDG for Family 10h: unset GartTblWkEn. */
1307 				if (i == MC_AMDNB_BANK && family >= 0xf &&
1308 				    family < 0x17)
1309 					ctl &= ~(1UL << 10);
1310 			}
1311 
1312 			if (!skip)
1313 				wrmsr(mca_msr_ops.ctl(i), ctl);
1314 
1315 #ifdef DEV_APIC
1316 			if (cmci_supported(mcg_cap)) {
1317 				if (boot)
1318 					cmci_monitor(i);
1319 				else
1320 					cmci_resume(i);
1321 			} else if (amd_thresholding_supported()) {
1322 				if (boot)
1323 					amd_thresholding_monitor(i);
1324 				else
1325 					amd_thresholding_resume(i);
1326 			}
1327 #endif
1328 
1329 			/* Clear all errors. */
1330 			wrmsr(mca_msr_ops.status(i), 0);
1331 		}
1332 		if (boot)
1333 			mtx_unlock_spin(&mca_lock);
1334 
1335 #ifdef DEV_APIC
1336 		if (!amd_thresholding_supported() &&
1337 		    PCPU_GET(cmci_mask) != 0 && boot)
1338 			lapic_enable_cmc();
1339 #endif
1340 	}
1341 
1342 	load_cr4(rcr4() | CR4_MCE);
1343 }
1344 
1345 /* Must be executed on each CPU during boot. */
1346 void
1347 mca_init(void)
1348 {
1349 
1350 	_mca_init(1);
1351 }
1352 
1353 /* Must be executed on each CPU during resume. */
1354 void
1355 mca_resume(void)
1356 {
1357 
1358 	_mca_init(0);
1359 }
1360 
1361 /*
1362  * The machine check registers for the BSP cannot be initialized until
1363  * the local APIC is initialized.  This happens at SI_SUB_CPU,
1364  * SI_ORDER_SECOND.
1365  */
1366 static void
1367 mca_init_bsp(void *arg __unused)
1368 {
1369 
1370 	mca_init();
1371 }
1372 SYSINIT(mca_init_bsp, SI_SUB_CPU, SI_ORDER_ANY, mca_init_bsp, NULL);
1373 
1374 /* Called when a machine check exception fires. */
1375 void
1376 mca_intr(void)
1377 {
1378 	uint64_t mcg_status;
1379 	int recoverable, count;
1380 
1381 	if (!(cpu_feature & CPUID_MCA)) {
1382 		/*
1383 		 * Just print the values of the old Pentium registers
1384 		 * and panic.
1385 		 */
1386 		printf("MC Type: 0x%jx  Address: 0x%jx\n",
1387 		    (uintmax_t)rdmsr(MSR_P5_MC_TYPE),
1388 		    (uintmax_t)rdmsr(MSR_P5_MC_ADDR));
1389 		panic("Machine check");
1390 	}
1391 
1392 	/* Scan the banks and check for any non-recoverable errors. */
1393 	count = mca_scan(MCE, &recoverable);
1394 	mcg_status = rdmsr(MSR_MCG_STATUS);
1395 	if (!(mcg_status & MCG_STATUS_RIPV))
1396 		recoverable = 0;
1397 
1398 	if (!recoverable) {
1399 		/*
1400 		 * Only panic if the error was detected local to this CPU.
1401 		 * Some errors will assert a machine check on all CPUs, but
1402 		 * only certain CPUs will find a valid bank to log.
1403 		 */
1404 		while (count == 0)
1405 			cpu_spinwait();
1406 
1407 		panic("Unrecoverable machine check exception");
1408 	}
1409 
1410 	/* Clear MCIP. */
1411 	wrmsr(MSR_MCG_STATUS, mcg_status & ~MCG_STATUS_MCIP);
1412 }
1413 
1414 #ifdef DEV_APIC
1415 /* Called for a CMCI (correctable machine check interrupt). */
1416 void
1417 cmc_intr(void)
1418 {
1419 
1420 	/*
1421 	 * Serialize MCA bank scanning to prevent collisions from
1422 	 * sibling threads.
1423 	 *
1424 	 * If we found anything, log them to the console.
1425 	 */
1426 	if (mca_scan(CMCI, NULL) != 0)
1427 		mca_process_records(CMCI);
1428 }
1429 #endif
1430