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