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