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