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() */
63enum scan_mode {
64	POLLED,
65	MCE,
66	CMCI,
67};
68
69#ifdef DEV_APIC
70/*
71 * State maintained for each monitored MCx bank to control the
72 * corrected machine check interrupt threshold.
73 */
74struct cmc_state {
75	int	max_threshold;
76	time_t	last_intr;
77};
78
79struct amd_et_state {
80	int	cur_threshold;
81	time_t	last_intr;
82};
83#endif
84
85struct mca_internal {
86	struct mca_record rec;
87	STAILQ_ENTRY(mca_internal) link;
88};
89
90struct 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
97static MALLOC_DEFINE(M_MCA, "MCA", "Machine Check Architecture");
98
99static volatile int mca_count;	/* Number of records stored. */
100static int mca_banks;		/* Number of per-CPU register banks. */
101static int mca_maxcount = -1;	/* Limit on records stored. (-1 = unlimited) */
102
103static SYSCTL_NODE(_hw, OID_AUTO, mca, CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
104    "Machine Check Architecture");
105
106static int mca_enabled = 1;
107SYSCTL_INT(_hw_mca, OID_AUTO, enabled, CTLFLAG_RDTUN, &mca_enabled, 0,
108    "Administrative toggle for machine check support");
109
110static int log_corrected = 1;
111SYSCTL_INT(_hw_mca, OID_AUTO, log_corrected, CTLFLAG_RWTUN, &log_corrected, 0,
112    "Log corrected errors to the console");
113
114static int amd10h_L1TP = 1;
115SYSCTL_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
118static int intel6h_HSD131;
119SYSCTL_INT(_hw_mca, OID_AUTO, intel6h_HSD131, CTLFLAG_RDTUN, &intel6h_HSD131, 0,
120    "Administrative toggle for logging of spurious corrected errors");
121
122int workaround_erratum383;
123SYSCTL_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
127static STAILQ_HEAD(, mca_internal) mca_freelist;
128static int mca_freecount;
129static STAILQ_HEAD(, mca_internal) mca_records;
130static STAILQ_HEAD(, mca_internal) mca_pending;
131static int mca_ticks = 300;
132static struct taskqueue *mca_tq;
133static struct task mca_resize_task;
134static struct timeout_task mca_scan_task;
135static struct mtx mca_lock;
136
137static unsigned int
138mca_ia32_ctl_reg(int bank)
139{
140	return (MSR_MC_CTL(bank));
141}
142
143static unsigned int
144mca_ia32_status_reg(int bank)
145{
146	return (MSR_MC_STATUS(bank));
147}
148
149static unsigned int
150mca_ia32_addr_reg(int bank)
151{
152	return (MSR_MC_ADDR(bank));
153}
154
155static unsigned int
156mca_ia32_misc_reg(int bank)
157{
158	return (MSR_MC_MISC(bank));
159}
160
161static unsigned int
162mca_smca_ctl_reg(int bank)
163{
164        return (MSR_SMCA_MC_CTL(bank));
165}
166
167static unsigned int
168mca_smca_status_reg(int bank)
169{
170        return (MSR_SMCA_MC_STATUS(bank));
171}
172
173static unsigned int
174mca_smca_addr_reg(int bank)
175{
176        return (MSR_SMCA_MC_ADDR(bank));
177}
178
179static unsigned int
180mca_smca_misc_reg(int bank)
181{
182        return (MSR_SMCA_MC_MISC(bank));
183}
184
185static 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
193static struct cmc_state **cmc_state;		/* Indexed by cpuid, bank. */
194static struct amd_et_state **amd_et_state;	/* Indexed by cpuid, bank. */
195static int cmc_throttle = 60;	/* Time in seconds to throttle CMCI. */
196
197static int amd_elvt = -1;
198
199static inline bool
200amd_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
220static inline bool
221cmci_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
232static inline bool
233tes_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
245static inline bool
246ser_supported(uint64_t mcg_cap)
247{
248
249	return (tes_supported(mcg_cap) && (mcg_cap & MCG_CAP_SER_P) != 0);
250}
251
252static int
253sysctl_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
267static int
268sysctl_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
299static const char *
300mca_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
314static const char *
315mca_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
331static const char *
332mca_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
358static const char *
359mca_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
377static const char *
378mca_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
396static int
397mca_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. */
425static void
426mca_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
618static bool
619mca_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
654static int
655mca_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
700static void
701mca_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
739static void
740mca_resize(void *context, int pending)
741{
742
743	mca_resize_freelist();
744}
745
746static void
747mca_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 */
781static int
782update_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
832static void
833cmci_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
858static void
859amd_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 */
893static int
894mca_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 */
940static void
941mca_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 */
975static void
976mca_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 */
998static void
999mca_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
1022static int
1023sysctl_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
1037static int
1038sysctl_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
1066static void
1067mca_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}
1080SYSINIT(mca_startup, SI_SUB_KICK_SCHEDULER, SI_ORDER_ANY, mca_startup, NULL);
1081
1082#ifdef DEV_APIC
1083static void
1084cmci_setup(void)
1085{
1086	int i;
1087
1088	cmc_state = malloc((mp_maxid + 1) * sizeof(struct cmc_state *), M_MCA,
1089	    M_WAITOK);
1090	for (i = 0; i <= mp_maxid; i++)
1091		cmc_state[i] = malloc(sizeof(struct cmc_state) * mca_banks,
1092		    M_MCA, M_WAITOK | M_ZERO);
1093	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1094	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1095	    &cmc_throttle, 0, sysctl_positive_int, "I",
1096	    "Interval in seconds to throttle corrected MC interrupts");
1097}
1098
1099static void
1100amd_thresholding_setup(void)
1101{
1102	u_int i;
1103
1104	amd_et_state = malloc((mp_maxid + 1) * sizeof(struct amd_et_state *),
1105	    M_MCA, M_WAITOK);
1106	for (i = 0; i <= mp_maxid; i++)
1107		amd_et_state[i] = malloc(sizeof(struct amd_et_state) *
1108		    mca_banks, M_MCA, M_WAITOK | M_ZERO);
1109	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1110	    "cmc_throttle", CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1111	    &cmc_throttle, 0, sysctl_positive_int, "I",
1112	    "Interval in seconds to throttle corrected MC interrupts");
1113}
1114#endif
1115
1116static void
1117mca_setup(uint64_t mcg_cap)
1118{
1119
1120	/*
1121	 * On AMD Family 10h processors, unless logging of level one TLB
1122	 * parity (L1TP) errors is disabled, enable the recommended workaround
1123	 * for Erratum 383.
1124	 */
1125	if (cpu_vendor_id == CPU_VENDOR_AMD &&
1126	    CPUID_TO_FAMILY(cpu_id) == 0x10 && amd10h_L1TP)
1127		workaround_erratum383 = 1;
1128
1129	mca_banks = mcg_cap & MCG_CAP_COUNT;
1130	mtx_init(&mca_lock, "mca", NULL, MTX_SPIN);
1131	STAILQ_INIT(&mca_records);
1132	STAILQ_INIT(&mca_pending);
1133	mca_tq = taskqueue_create_fast("mca", M_WAITOK,
1134	    taskqueue_thread_enqueue, &mca_tq);
1135	TIMEOUT_TASK_INIT(mca_tq, &mca_scan_task, 0, mca_scan_cpus, NULL);
1136	STAILQ_INIT(&mca_freelist);
1137	TASK_INIT(&mca_resize_task, 0, mca_resize, NULL);
1138	mca_resize_freelist();
1139	SYSCTL_ADD_INT(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1140	    "count", CTLFLAG_RD, (int *)(uintptr_t)&mca_count, 0,
1141	    "Record count");
1142	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1143	    "maxcount", CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1144	    &mca_maxcount, 0, sysctl_mca_maxcount, "I",
1145	    "Maximum record count (-1 is unlimited)");
1146	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1147	    "interval", CTLTYPE_INT | CTLFLAG_RWTUN | CTLFLAG_MPSAFE,
1148	    &mca_ticks, 0, sysctl_positive_int, "I",
1149	    "Periodic interval in seconds to scan for machine checks");
1150	SYSCTL_ADD_NODE(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1151	    "records", CTLFLAG_RD | CTLFLAG_MPSAFE, sysctl_mca_records,
1152	    "Machine check records");
1153	SYSCTL_ADD_PROC(NULL, SYSCTL_STATIC_CHILDREN(_hw_mca), OID_AUTO,
1154	    "force_scan", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, NULL, 0,
1155	    sysctl_mca_scan, "I", "Force an immediate scan for machine checks");
1156#ifdef DEV_APIC
1157	if (cmci_supported(mcg_cap))
1158		cmci_setup();
1159	else if (amd_thresholding_supported())
1160		amd_thresholding_setup();
1161#endif
1162}
1163
1164#ifdef DEV_APIC
1165/*
1166 * See if we should monitor CMCI for this bank.  If CMCI_EN is already
1167 * set in MC_CTL2, then another CPU is responsible for this bank, so
1168 * ignore it.  If CMCI_EN returns zero after being set, then this bank
1169 * does not support CMCI_EN.  If this CPU sets CMCI_EN, then it should
1170 * now monitor this bank.
1171 */
1172static void
1173cmci_monitor(int i)
1174{
1175	struct cmc_state *cc;
1176	uint64_t ctl;
1177
1178	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1179
1180	/*
1181	 * It is possible for some APs to report CMCI support even if the BSP
1182	 * does not, apparently due to a BIOS bug.
1183	 */
1184	if (cmc_state == NULL) {
1185		if (bootverbose) {
1186			printf(
1187		    "AP %d (%d,%d) reports CMCI support but the BSP does not\n",
1188			    PCPU_GET(cpuid), PCPU_GET(apic_id),
1189			    PCPU_GET(acpi_id));
1190		}
1191		return;
1192	}
1193
1194	ctl = rdmsr(MSR_MC_CTL2(i));
1195	if (ctl & MC_CTL2_CMCI_EN)
1196		/* Already monitored by another CPU. */
1197		return;
1198
1199	/* Set the threshold to one event for now. */
1200	ctl &= ~MC_CTL2_THRESHOLD;
1201	ctl |= MC_CTL2_CMCI_EN | 1;
1202	wrmsr(MSR_MC_CTL2(i), ctl);
1203	ctl = rdmsr(MSR_MC_CTL2(i));
1204	if (!(ctl & MC_CTL2_CMCI_EN))
1205		/* This bank does not support CMCI. */
1206		return;
1207
1208	cc = &cmc_state[PCPU_GET(cpuid)][i];
1209
1210	/* Determine maximum threshold. */
1211	ctl &= ~MC_CTL2_THRESHOLD;
1212	ctl |= 0x7fff;
1213	wrmsr(MSR_MC_CTL2(i), ctl);
1214	ctl = rdmsr(MSR_MC_CTL2(i));
1215	cc->max_threshold = ctl & MC_CTL2_THRESHOLD;
1216
1217	/* Start off with a threshold of 1. */
1218	ctl &= ~MC_CTL2_THRESHOLD;
1219	ctl |= 1;
1220	wrmsr(MSR_MC_CTL2(i), ctl);
1221
1222	/* Mark this bank as monitored. */
1223	PCPU_SET(cmci_mask, PCPU_GET(cmci_mask) | 1 << i);
1224}
1225
1226/*
1227 * For resume, reset the threshold for any banks we monitor back to
1228 * one and throw away the timestamp of the last interrupt.
1229 */
1230static void
1231cmci_resume(int i)
1232{
1233	struct cmc_state *cc;
1234	uint64_t ctl;
1235
1236	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1237
1238	/* See cmci_monitor(). */
1239	if (cmc_state == NULL)
1240		return;
1241
1242	/* Ignore banks not monitored by this CPU. */
1243	if (!(PCPU_GET(cmci_mask) & 1 << i))
1244		return;
1245
1246	cc = &cmc_state[PCPU_GET(cpuid)][i];
1247	cc->last_intr = 0;
1248	ctl = rdmsr(MSR_MC_CTL2(i));
1249	ctl &= ~MC_CTL2_THRESHOLD;
1250	ctl |= MC_CTL2_CMCI_EN | 1;
1251	wrmsr(MSR_MC_CTL2(i), ctl);
1252}
1253
1254/*
1255 * Apply an AMD ET configuration to the corresponding MSR.
1256 */
1257static void
1258amd_thresholding_start(struct amd_et_state *cc, int bank)
1259{
1260	uint64_t misc;
1261
1262	KASSERT(amd_elvt >= 0, ("ELVT offset is not set"));
1263
1264	misc = rdmsr(mca_msr_ops.misc(bank));
1265
1266	misc &= ~MC_MISC_AMD_INT_MASK;
1267	misc |= MC_MISC_AMD_INT_LVT;
1268
1269	misc &= ~MC_MISC_AMD_LVT_MASK;
1270	misc |= (uint64_t)amd_elvt << MC_MISC_AMD_LVT_SHIFT;
1271
1272	misc &= ~MC_MISC_AMD_CNT_MASK;
1273	misc |= (uint64_t)(MC_MISC_AMD_CNT_MAX - cc->cur_threshold)
1274	    << MC_MISC_AMD_CNT_SHIFT;
1275
1276	misc &= ~MC_MISC_AMD_OVERFLOW;
1277	misc |= MC_MISC_AMD_CNTEN;
1278
1279	wrmsr(mca_msr_ops.misc(bank), misc);
1280}
1281
1282static void
1283amd_thresholding_monitor(int i)
1284{
1285	struct amd_et_state *cc;
1286	uint64_t misc;
1287
1288	/*
1289	 * Kludge: On 10h, banks after 4 are not thresholding but also may have
1290	 * bogus Valid bits.  Skip them.  This is definitely fixed in 15h, but
1291	 * I have not investigated whether it is fixed in earlier models.
1292	 */
1293	if (CPUID_TO_FAMILY(cpu_id) < 0x15 && i >= 5)
1294		return;
1295
1296	/* The counter must be valid and present. */
1297	misc = rdmsr(mca_msr_ops.misc(i));
1298	if ((misc & (MC_MISC_AMD_VAL | MC_MISC_AMD_CNTP)) !=
1299	    (MC_MISC_AMD_VAL | MC_MISC_AMD_CNTP))
1300		return;
1301
1302	/* The register should not be locked. */
1303	if ((misc & MC_MISC_AMD_LOCK) != 0) {
1304		if (bootverbose)
1305			printf("%s: 0x%jx: Bank %d: locked\n", __func__,
1306			    (uintmax_t)misc, i);
1307		return;
1308	}
1309
1310	/*
1311	 * If counter is enabled then either the firmware or another CPU
1312	 * has already claimed it.
1313	 */
1314	if ((misc & MC_MISC_AMD_CNTEN) != 0) {
1315		if (bootverbose)
1316			printf("%s: 0x%jx: Bank %d: already enabled\n",
1317			    __func__, (uintmax_t)misc, i);
1318		return;
1319	}
1320
1321	/*
1322	 * Configure an Extended Interrupt LVT register for reporting
1323	 * counter overflows if that feature is supported and the first
1324	 * extended register is available.
1325	 */
1326	amd_elvt = lapic_enable_mca_elvt();
1327	if (amd_elvt < 0) {
1328		printf("%s: Bank %d: lapic enable mca elvt failed: %d\n",
1329		    __func__, i, amd_elvt);
1330		return;
1331	}
1332
1333	cc = &amd_et_state[PCPU_GET(cpuid)][i];
1334	cc->cur_threshold = 1;
1335	amd_thresholding_start(cc, i);
1336
1337	/* Mark this bank as monitored. */
1338	PCPU_SET(cmci_mask, PCPU_GET(cmci_mask) | 1 << i);
1339}
1340
1341static void
1342amd_thresholding_resume(int i)
1343{
1344	struct amd_et_state *cc;
1345
1346	KASSERT(i < mca_banks, ("CPU %d has more MC banks", PCPU_GET(cpuid)));
1347
1348	/* Ignore banks not monitored by this CPU. */
1349	if (!(PCPU_GET(cmci_mask) & 1 << i))
1350		return;
1351
1352	cc = &amd_et_state[PCPU_GET(cpuid)][i];
1353	cc->last_intr = 0;
1354	cc->cur_threshold = 1;
1355	amd_thresholding_start(cc, i);
1356}
1357#endif
1358
1359/*
1360 * Initializes per-CPU machine check registers and enables corrected
1361 * machine check interrupts.
1362 */
1363static void
1364_mca_init(int boot)
1365{
1366	uint64_t mcg_cap;
1367	uint64_t ctl, mask;
1368	int i, skip, family;
1369
1370	family = CPUID_TO_FAMILY(cpu_id);
1371
1372	/* MCE is required. */
1373	if (!mca_enabled || !(cpu_feature & CPUID_MCE))
1374		return;
1375
1376	if (cpu_feature & CPUID_MCA) {
1377		if (boot)
1378			PCPU_SET(cmci_mask, 0);
1379
1380		mcg_cap = rdmsr(MSR_MCG_CAP);
1381		if (mcg_cap & MCG_CAP_CTL_P)
1382			/* Enable MCA features. */
1383			wrmsr(MSR_MCG_CTL, MCG_CTL_ENABLE);
1384		if (IS_BSP() && boot)
1385			mca_setup(mcg_cap);
1386
1387		/*
1388		 * Disable logging of level one TLB parity (L1TP) errors by
1389		 * the data cache as an alternative workaround for AMD Family
1390		 * 10h Erratum 383.  Unlike the recommended workaround, there
1391		 * is no performance penalty to this workaround.  However,
1392		 * L1TP errors will go unreported.
1393		 */
1394		if (cpu_vendor_id == CPU_VENDOR_AMD && family == 0x10 &&
1395		    !amd10h_L1TP) {
1396			mask = rdmsr(MSR_MC0_CTL_MASK);
1397			if ((mask & (1UL << 5)) == 0)
1398				wrmsr(MSR_MC0_CTL_MASK, mask | (1UL << 5));
1399		}
1400		if (amd_rascap & AMDRAS_SCALABLE_MCA) {
1401			mca_msr_ops.ctl = mca_smca_ctl_reg;
1402			mca_msr_ops.status = mca_smca_status_reg;
1403			mca_msr_ops.addr = mca_smca_addr_reg;
1404			mca_msr_ops.misc = mca_smca_misc_reg;
1405		}
1406
1407		/* Enable local MCE if supported. */
1408		if (cpu_vendor_id == CPU_VENDOR_INTEL &&
1409		    (mcg_cap & MCG_CAP_LMCE_P) &&
1410		    (rdmsr(MSR_IA32_FEATURE_CONTROL) &
1411		     IA32_FEATURE_CONTROL_LMCE_EN))
1412			wrmsr(MSR_MCG_EXT_CTL, rdmsr(MSR_MCG_EXT_CTL) | 1);
1413
1414		/*
1415		 * The cmci_monitor() must not be executed
1416		 * simultaneously by several CPUs.
1417		 */
1418		if (boot)
1419			mtx_lock_spin(&mca_lock);
1420
1421		for (i = 0; i < (mcg_cap & MCG_CAP_COUNT); i++) {
1422			/* By default enable logging of all errors. */
1423			ctl = 0xffffffffffffffffUL;
1424			skip = 0;
1425
1426			if (cpu_vendor_id == CPU_VENDOR_INTEL) {
1427				/*
1428				 * For P6 models before Nehalem MC0_CTL is
1429				 * always enabled and reserved.
1430				 */
1431				if (i == 0 && family == 0x6
1432				    && CPUID_TO_MODEL(cpu_id) < 0x1a)
1433					skip = 1;
1434			} else if (cpu_vendor_id == CPU_VENDOR_AMD) {
1435				/* BKDG for Family 10h: unset GartTblWkEn. */
1436				if (i == MC_AMDNB_BANK && family >= 0xf &&
1437				    family < 0x17)
1438					ctl &= ~(1UL << 10);
1439			}
1440
1441			if (!skip)
1442				wrmsr(mca_msr_ops.ctl(i), ctl);
1443
1444#ifdef DEV_APIC
1445			if (cmci_supported(mcg_cap)) {
1446				if (boot)
1447					cmci_monitor(i);
1448				else
1449					cmci_resume(i);
1450			} else if (amd_thresholding_supported()) {
1451				if (boot)
1452					amd_thresholding_monitor(i);
1453				else
1454					amd_thresholding_resume(i);
1455			}
1456#endif
1457
1458			/* Clear all errors. */
1459			wrmsr(mca_msr_ops.status(i), 0);
1460		}
1461		if (boot)
1462			mtx_unlock_spin(&mca_lock);
1463
1464#ifdef DEV_APIC
1465		if (cmci_supported(mcg_cap) &&
1466		    PCPU_GET(cmci_mask) != 0 && boot)
1467			lapic_enable_cmc();
1468#endif
1469	}
1470
1471	load_cr4(rcr4() | CR4_MCE);
1472}
1473
1474/* Must be executed on each CPU during boot. */
1475void
1476mca_init(void)
1477{
1478
1479	_mca_init(1);
1480}
1481
1482/* Must be executed on each CPU during resume. */
1483void
1484mca_resume(void)
1485{
1486
1487	_mca_init(0);
1488}
1489
1490/*
1491 * The machine check registers for the BSP cannot be initialized until
1492 * the local APIC is initialized.  This happens at SI_SUB_CPU,
1493 * SI_ORDER_SECOND.
1494 */
1495static void
1496mca_init_bsp(void *arg __unused)
1497{
1498
1499	mca_init();
1500}
1501SYSINIT(mca_init_bsp, SI_SUB_CPU, SI_ORDER_ANY, mca_init_bsp, NULL);
1502
1503/* Called when a machine check exception fires. */
1504void
1505mca_intr(void)
1506{
1507	uint64_t mcg_status;
1508	int count;
1509	bool lmcs, recoverable;
1510
1511	if (!(cpu_feature & CPUID_MCA)) {
1512		/*
1513		 * Just print the values of the old Pentium registers
1514		 * and panic.
1515		 */
1516		printf("MC Type: 0x%jx  Address: 0x%jx\n",
1517		    (uintmax_t)rdmsr(MSR_P5_MC_TYPE),
1518		    (uintmax_t)rdmsr(MSR_P5_MC_ADDR));
1519		panic("Machine check exception");
1520	}
1521
1522	/* Scan the banks and check for any non-recoverable errors. */
1523	mcg_status = rdmsr(MSR_MCG_STATUS);
1524	recoverable = (mcg_status & MCG_STATUS_RIPV) != 0;
1525	lmcs = (cpu_vendor_id != CPU_VENDOR_INTEL ||
1526	    (mcg_status & MCG_STATUS_LMCS));
1527	count = mca_scan(MCE, &recoverable);
1528
1529	if (!recoverable) {
1530		/*
1531		 * Only panic if the error was detected local to this CPU.
1532		 * Some errors will assert a machine check on all CPUs, but
1533		 * only certain CPUs will find a valid bank to log.
1534		 */
1535		while (!lmcs && count == 0)
1536			cpu_spinwait();
1537
1538		panic("Unrecoverable machine check exception");
1539	}
1540
1541	/* Clear MCIP. */
1542	wrmsr(MSR_MCG_STATUS, mcg_status & ~MCG_STATUS_MCIP);
1543}
1544
1545#ifdef DEV_APIC
1546/* Called for a CMCI (correctable machine check interrupt). */
1547void
1548cmc_intr(void)
1549{
1550	bool recoverable = true;
1551
1552	/*
1553	 * Serialize MCA bank scanning to prevent collisions from
1554	 * sibling threads.
1555	 *
1556	 * If we found anything, log them to the console.
1557	 */
1558	if (mca_scan(CMCI, &recoverable) != 0)
1559		mca_process_records(CMCI);
1560}
1561#endif
1562