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