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