EDAC/amd64: Add AMD family 17h model 60h PCI IDs
[linux-2.6-microblaze.git] / arch / x86 / kernel / cpu / mce / core.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Machine check handler.
4  *
5  * K8 parts Copyright 2002,2003 Andi Kleen, SuSE Labs.
6  * Rest from unknown author(s).
7  * 2004 Andi Kleen. Rewrote most of it.
8  * Copyright 2008 Intel Corporation
9  * Author: Andi Kleen
10  */
11
12 #include <linux/thread_info.h>
13 #include <linux/capability.h>
14 #include <linux/miscdevice.h>
15 #include <linux/ratelimit.h>
16 #include <linux/rcupdate.h>
17 #include <linux/kobject.h>
18 #include <linux/uaccess.h>
19 #include <linux/kdebug.h>
20 #include <linux/kernel.h>
21 #include <linux/percpu.h>
22 #include <linux/string.h>
23 #include <linux/device.h>
24 #include <linux/syscore_ops.h>
25 #include <linux/delay.h>
26 #include <linux/ctype.h>
27 #include <linux/sched.h>
28 #include <linux/sysfs.h>
29 #include <linux/types.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/kmod.h>
33 #include <linux/poll.h>
34 #include <linux/nmi.h>
35 #include <linux/cpu.h>
36 #include <linux/ras.h>
37 #include <linux/smp.h>
38 #include <linux/fs.h>
39 #include <linux/mm.h>
40 #include <linux/debugfs.h>
41 #include <linux/irq_work.h>
42 #include <linux/export.h>
43 #include <linux/jump_label.h>
44 #include <linux/set_memory.h>
45
46 #include <asm/intel-family.h>
47 #include <asm/processor.h>
48 #include <asm/traps.h>
49 #include <asm/tlbflush.h>
50 #include <asm/mce.h>
51 #include <asm/msr.h>
52 #include <asm/reboot.h>
53
54 #include "internal.h"
55
56 /* sysfs synchronization */
57 static DEFINE_MUTEX(mce_sysfs_mutex);
58
59 #define CREATE_TRACE_POINTS
60 #include <trace/events/mce.h>
61
62 #define SPINUNIT                100     /* 100ns */
63
64 DEFINE_PER_CPU(unsigned, mce_exception_count);
65
66 DEFINE_PER_CPU_READ_MOSTLY(unsigned int, mce_num_banks);
67
68 struct mce_bank {
69         u64                     ctl;                    /* subevents to enable */
70         bool                    init;                   /* initialise bank? */
71 };
72 static DEFINE_PER_CPU_READ_MOSTLY(struct mce_bank[MAX_NR_BANKS], mce_banks_array);
73
74 #define ATTR_LEN               16
75 /* One object for each MCE bank, shared by all CPUs */
76 struct mce_bank_dev {
77         struct device_attribute attr;                   /* device attribute */
78         char                    attrname[ATTR_LEN];     /* attribute name */
79         u8                      bank;                   /* bank number */
80 };
81 static struct mce_bank_dev mce_bank_devs[MAX_NR_BANKS];
82
83 struct mce_vendor_flags mce_flags __read_mostly;
84
85 struct mca_config mca_cfg __read_mostly = {
86         .bootlog  = -1,
87         /*
88          * Tolerant levels:
89          * 0: always panic on uncorrected errors, log corrected errors
90          * 1: panic or SIGBUS on uncorrected errors, log corrected errors
91          * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
92          * 3: never panic or SIGBUS, log all errors (for testing only)
93          */
94         .tolerant = 1,
95         .monarch_timeout = -1
96 };
97
98 static DEFINE_PER_CPU(struct mce, mces_seen);
99 static unsigned long mce_need_notify;
100 static int cpu_missing;
101
102 /*
103  * MCA banks polled by the period polling timer for corrected events.
104  * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
105  */
106 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
107         [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
108 };
109
110 /*
111  * MCA banks controlled through firmware first for corrected errors.
112  * This is a global list of banks for which we won't enable CMCI and we
113  * won't poll. Firmware controls these banks and is responsible for
114  * reporting corrected errors through GHES. Uncorrected/recoverable
115  * errors are still notified through a machine check.
116  */
117 mce_banks_t mce_banks_ce_disabled;
118
119 static struct work_struct mce_work;
120 static struct irq_work mce_irq_work;
121
122 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
123
124 /*
125  * CPU/chipset specific EDAC code can register a notifier call here to print
126  * MCE errors in a human-readable form.
127  */
128 BLOCKING_NOTIFIER_HEAD(x86_mce_decoder_chain);
129
130 /* Do initial initialization of a struct mce */
131 void mce_setup(struct mce *m)
132 {
133         memset(m, 0, sizeof(struct mce));
134         m->cpu = m->extcpu = smp_processor_id();
135         /* need the internal __ version to avoid deadlocks */
136         m->time = __ktime_get_real_seconds();
137         m->cpuvendor = boot_cpu_data.x86_vendor;
138         m->cpuid = cpuid_eax(1);
139         m->socketid = cpu_data(m->extcpu).phys_proc_id;
140         m->apicid = cpu_data(m->extcpu).initial_apicid;
141         rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
142
143         if (this_cpu_has(X86_FEATURE_INTEL_PPIN))
144                 rdmsrl(MSR_PPIN, m->ppin);
145         else if (this_cpu_has(X86_FEATURE_AMD_PPIN))
146                 rdmsrl(MSR_AMD_PPIN, m->ppin);
147
148         m->microcode = boot_cpu_data.microcode;
149 }
150
151 DEFINE_PER_CPU(struct mce, injectm);
152 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
153
154 void mce_log(struct mce *m)
155 {
156         if (!mce_gen_pool_add(m))
157                 irq_work_queue(&mce_irq_work);
158 }
159 EXPORT_SYMBOL_GPL(mce_log);
160
161 void mce_register_decode_chain(struct notifier_block *nb)
162 {
163         if (WARN_ON(nb->priority > MCE_PRIO_MCELOG && nb->priority < MCE_PRIO_EDAC))
164                 return;
165
166         blocking_notifier_chain_register(&x86_mce_decoder_chain, nb);
167 }
168 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
169
170 void mce_unregister_decode_chain(struct notifier_block *nb)
171 {
172         blocking_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
173 }
174 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
175
176 static inline u32 ctl_reg(int bank)
177 {
178         return MSR_IA32_MCx_CTL(bank);
179 }
180
181 static inline u32 status_reg(int bank)
182 {
183         return MSR_IA32_MCx_STATUS(bank);
184 }
185
186 static inline u32 addr_reg(int bank)
187 {
188         return MSR_IA32_MCx_ADDR(bank);
189 }
190
191 static inline u32 misc_reg(int bank)
192 {
193         return MSR_IA32_MCx_MISC(bank);
194 }
195
196 static inline u32 smca_ctl_reg(int bank)
197 {
198         return MSR_AMD64_SMCA_MCx_CTL(bank);
199 }
200
201 static inline u32 smca_status_reg(int bank)
202 {
203         return MSR_AMD64_SMCA_MCx_STATUS(bank);
204 }
205
206 static inline u32 smca_addr_reg(int bank)
207 {
208         return MSR_AMD64_SMCA_MCx_ADDR(bank);
209 }
210
211 static inline u32 smca_misc_reg(int bank)
212 {
213         return MSR_AMD64_SMCA_MCx_MISC(bank);
214 }
215
216 struct mca_msr_regs msr_ops = {
217         .ctl    = ctl_reg,
218         .status = status_reg,
219         .addr   = addr_reg,
220         .misc   = misc_reg
221 };
222
223 static void __print_mce(struct mce *m)
224 {
225         pr_emerg(HW_ERR "CPU %d: Machine Check%s: %Lx Bank %d: %016Lx\n",
226                  m->extcpu,
227                  (m->mcgstatus & MCG_STATUS_MCIP ? " Exception" : ""),
228                  m->mcgstatus, m->bank, m->status);
229
230         if (m->ip) {
231                 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
232                         !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
233                         m->cs, m->ip);
234
235                 if (m->cs == __KERNEL_CS)
236                         pr_cont("{%pS}", (void *)(unsigned long)m->ip);
237                 pr_cont("\n");
238         }
239
240         pr_emerg(HW_ERR "TSC %llx ", m->tsc);
241         if (m->addr)
242                 pr_cont("ADDR %llx ", m->addr);
243         if (m->misc)
244                 pr_cont("MISC %llx ", m->misc);
245
246         if (mce_flags.smca) {
247                 if (m->synd)
248                         pr_cont("SYND %llx ", m->synd);
249                 if (m->ipid)
250                         pr_cont("IPID %llx ", m->ipid);
251         }
252
253         pr_cont("\n");
254
255         /*
256          * Note this output is parsed by external tools and old fields
257          * should not be changed.
258          */
259         pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
260                 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
261                 m->microcode);
262 }
263
264 static void print_mce(struct mce *m)
265 {
266         __print_mce(m);
267
268         if (m->cpuvendor != X86_VENDOR_AMD && m->cpuvendor != X86_VENDOR_HYGON)
269                 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
270 }
271
272 #define PANIC_TIMEOUT 5 /* 5 seconds */
273
274 static atomic_t mce_panicked;
275
276 static int fake_panic;
277 static atomic_t mce_fake_panicked;
278
279 /* Panic in progress. Enable interrupts and wait for final IPI */
280 static void wait_for_panic(void)
281 {
282         long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
283
284         preempt_disable();
285         local_irq_enable();
286         while (timeout-- > 0)
287                 udelay(1);
288         if (panic_timeout == 0)
289                 panic_timeout = mca_cfg.panic_timeout;
290         panic("Panicing machine check CPU died");
291 }
292
293 static void mce_panic(const char *msg, struct mce *final, char *exp)
294 {
295         int apei_err = 0;
296         struct llist_node *pending;
297         struct mce_evt_llist *l;
298
299         if (!fake_panic) {
300                 /*
301                  * Make sure only one CPU runs in machine check panic
302                  */
303                 if (atomic_inc_return(&mce_panicked) > 1)
304                         wait_for_panic();
305                 barrier();
306
307                 bust_spinlocks(1);
308                 console_verbose();
309         } else {
310                 /* Don't log too much for fake panic */
311                 if (atomic_inc_return(&mce_fake_panicked) > 1)
312                         return;
313         }
314         pending = mce_gen_pool_prepare_records();
315         /* First print corrected ones that are still unlogged */
316         llist_for_each_entry(l, pending, llnode) {
317                 struct mce *m = &l->mce;
318                 if (!(m->status & MCI_STATUS_UC)) {
319                         print_mce(m);
320                         if (!apei_err)
321                                 apei_err = apei_write_mce(m);
322                 }
323         }
324         /* Now print uncorrected but with the final one last */
325         llist_for_each_entry(l, pending, llnode) {
326                 struct mce *m = &l->mce;
327                 if (!(m->status & MCI_STATUS_UC))
328                         continue;
329                 if (!final || mce_cmp(m, final)) {
330                         print_mce(m);
331                         if (!apei_err)
332                                 apei_err = apei_write_mce(m);
333                 }
334         }
335         if (final) {
336                 print_mce(final);
337                 if (!apei_err)
338                         apei_err = apei_write_mce(final);
339         }
340         if (cpu_missing)
341                 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
342         if (exp)
343                 pr_emerg(HW_ERR "Machine check: %s\n", exp);
344         if (!fake_panic) {
345                 if (panic_timeout == 0)
346                         panic_timeout = mca_cfg.panic_timeout;
347                 panic(msg);
348         } else
349                 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
350 }
351
352 /* Support code for software error injection */
353
354 static int msr_to_offset(u32 msr)
355 {
356         unsigned bank = __this_cpu_read(injectm.bank);
357
358         if (msr == mca_cfg.rip_msr)
359                 return offsetof(struct mce, ip);
360         if (msr == msr_ops.status(bank))
361                 return offsetof(struct mce, status);
362         if (msr == msr_ops.addr(bank))
363                 return offsetof(struct mce, addr);
364         if (msr == msr_ops.misc(bank))
365                 return offsetof(struct mce, misc);
366         if (msr == MSR_IA32_MCG_STATUS)
367                 return offsetof(struct mce, mcgstatus);
368         return -1;
369 }
370
371 /* MSR access wrappers used for error injection */
372 static u64 mce_rdmsrl(u32 msr)
373 {
374         u64 v;
375
376         if (__this_cpu_read(injectm.finished)) {
377                 int offset = msr_to_offset(msr);
378
379                 if (offset < 0)
380                         return 0;
381                 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
382         }
383
384         if (rdmsrl_safe(msr, &v)) {
385                 WARN_ONCE(1, "mce: Unable to read MSR 0x%x!\n", msr);
386                 /*
387                  * Return zero in case the access faulted. This should
388                  * not happen normally but can happen if the CPU does
389                  * something weird, or if the code is buggy.
390                  */
391                 v = 0;
392         }
393
394         return v;
395 }
396
397 static void mce_wrmsrl(u32 msr, u64 v)
398 {
399         if (__this_cpu_read(injectm.finished)) {
400                 int offset = msr_to_offset(msr);
401
402                 if (offset >= 0)
403                         *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
404                 return;
405         }
406         wrmsrl(msr, v);
407 }
408
409 /*
410  * Collect all global (w.r.t. this processor) status about this machine
411  * check into our "mce" struct so that we can use it later to assess
412  * the severity of the problem as we read per-bank specific details.
413  */
414 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
415 {
416         mce_setup(m);
417
418         m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
419         if (regs) {
420                 /*
421                  * Get the address of the instruction at the time of
422                  * the machine check error.
423                  */
424                 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
425                         m->ip = regs->ip;
426                         m->cs = regs->cs;
427
428                         /*
429                          * When in VM86 mode make the cs look like ring 3
430                          * always. This is a lie, but it's better than passing
431                          * the additional vm86 bit around everywhere.
432                          */
433                         if (v8086_mode(regs))
434                                 m->cs |= 3;
435                 }
436                 /* Use accurate RIP reporting if available. */
437                 if (mca_cfg.rip_msr)
438                         m->ip = mce_rdmsrl(mca_cfg.rip_msr);
439         }
440 }
441
442 int mce_available(struct cpuinfo_x86 *c)
443 {
444         if (mca_cfg.disabled)
445                 return 0;
446         return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
447 }
448
449 static void mce_schedule_work(void)
450 {
451         if (!mce_gen_pool_empty())
452                 schedule_work(&mce_work);
453 }
454
455 static void mce_irq_work_cb(struct irq_work *entry)
456 {
457         mce_schedule_work();
458 }
459
460 /*
461  * Check if the address reported by the CPU is in a format we can parse.
462  * It would be possible to add code for most other cases, but all would
463  * be somewhat complicated (e.g. segment offset would require an instruction
464  * parser). So only support physical addresses up to page granuality for now.
465  */
466 int mce_usable_address(struct mce *m)
467 {
468         if (!(m->status & MCI_STATUS_ADDRV))
469                 return 0;
470
471         /* Checks after this one are Intel/Zhaoxin-specific: */
472         if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL &&
473             boot_cpu_data.x86_vendor != X86_VENDOR_ZHAOXIN)
474                 return 1;
475
476         if (!(m->status & MCI_STATUS_MISCV))
477                 return 0;
478
479         if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
480                 return 0;
481
482         if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
483                 return 0;
484
485         return 1;
486 }
487 EXPORT_SYMBOL_GPL(mce_usable_address);
488
489 bool mce_is_memory_error(struct mce *m)
490 {
491         switch (m->cpuvendor) {
492         case X86_VENDOR_AMD:
493         case X86_VENDOR_HYGON:
494                 return amd_mce_is_memory_error(m);
495
496         case X86_VENDOR_INTEL:
497         case X86_VENDOR_ZHAOXIN:
498                 /*
499                  * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
500                  *
501                  * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
502                  * indicating a memory error. Bit 8 is used for indicating a
503                  * cache hierarchy error. The combination of bit 2 and bit 3
504                  * is used for indicating a `generic' cache hierarchy error
505                  * But we can't just blindly check the above bits, because if
506                  * bit 11 is set, then it is a bus/interconnect error - and
507                  * either way the above bits just gives more detail on what
508                  * bus/interconnect error happened. Note that bit 12 can be
509                  * ignored, as it's the "filter" bit.
510                  */
511                 return (m->status & 0xef80) == BIT(7) ||
512                        (m->status & 0xef00) == BIT(8) ||
513                        (m->status & 0xeffc) == 0xc;
514
515         default:
516                 return false;
517         }
518 }
519 EXPORT_SYMBOL_GPL(mce_is_memory_error);
520
521 bool mce_is_correctable(struct mce *m)
522 {
523         if (m->cpuvendor == X86_VENDOR_AMD && m->status & MCI_STATUS_DEFERRED)
524                 return false;
525
526         if (m->cpuvendor == X86_VENDOR_HYGON && m->status & MCI_STATUS_DEFERRED)
527                 return false;
528
529         if (m->status & MCI_STATUS_UC)
530                 return false;
531
532         return true;
533 }
534 EXPORT_SYMBOL_GPL(mce_is_correctable);
535
536 static int mce_early_notifier(struct notifier_block *nb, unsigned long val,
537                               void *data)
538 {
539         struct mce *m = (struct mce *)data;
540
541         if (!m)
542                 return NOTIFY_DONE;
543
544         /* Emit the trace record: */
545         trace_mce_record(m);
546
547         set_bit(0, &mce_need_notify);
548
549         mce_notify_irq();
550
551         return NOTIFY_DONE;
552 }
553
554 static struct notifier_block early_nb = {
555         .notifier_call  = mce_early_notifier,
556         .priority       = MCE_PRIO_EARLY,
557 };
558
559 static int uc_decode_notifier(struct notifier_block *nb, unsigned long val,
560                               void *data)
561 {
562         struct mce *mce = (struct mce *)data;
563         unsigned long pfn;
564
565         if (!mce || !mce_usable_address(mce))
566                 return NOTIFY_DONE;
567
568         if (mce->severity != MCE_AO_SEVERITY &&
569             mce->severity != MCE_DEFERRED_SEVERITY)
570                 return NOTIFY_DONE;
571
572         pfn = mce->addr >> PAGE_SHIFT;
573         if (!memory_failure(pfn, 0)) {
574                 set_mce_nospec(pfn);
575                 mce->kflags |= MCE_HANDLED_UC;
576         }
577
578         return NOTIFY_OK;
579 }
580
581 static struct notifier_block mce_uc_nb = {
582         .notifier_call  = uc_decode_notifier,
583         .priority       = MCE_PRIO_UC,
584 };
585
586 static int mce_default_notifier(struct notifier_block *nb, unsigned long val,
587                                 void *data)
588 {
589         struct mce *m = (struct mce *)data;
590
591         if (!m)
592                 return NOTIFY_DONE;
593
594         if (mca_cfg.print_all || !m->kflags)
595                 __print_mce(m);
596
597         return NOTIFY_DONE;
598 }
599
600 static struct notifier_block mce_default_nb = {
601         .notifier_call  = mce_default_notifier,
602         /* lowest prio, we want it to run last. */
603         .priority       = MCE_PRIO_LOWEST,
604 };
605
606 /*
607  * Read ADDR and MISC registers.
608  */
609 static void mce_read_aux(struct mce *m, int i)
610 {
611         if (m->status & MCI_STATUS_MISCV)
612                 m->misc = mce_rdmsrl(msr_ops.misc(i));
613
614         if (m->status & MCI_STATUS_ADDRV) {
615                 m->addr = mce_rdmsrl(msr_ops.addr(i));
616
617                 /*
618                  * Mask the reported address by the reported granularity.
619                  */
620                 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
621                         u8 shift = MCI_MISC_ADDR_LSB(m->misc);
622                         m->addr >>= shift;
623                         m->addr <<= shift;
624                 }
625
626                 /*
627                  * Extract [55:<lsb>] where lsb is the least significant
628                  * *valid* bit of the address bits.
629                  */
630                 if (mce_flags.smca) {
631                         u8 lsb = (m->addr >> 56) & 0x3f;
632
633                         m->addr &= GENMASK_ULL(55, lsb);
634                 }
635         }
636
637         if (mce_flags.smca) {
638                 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
639
640                 if (m->status & MCI_STATUS_SYNDV)
641                         m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
642         }
643 }
644
645 DEFINE_PER_CPU(unsigned, mce_poll_count);
646
647 /*
648  * Poll for corrected events or events that happened before reset.
649  * Those are just logged through /dev/mcelog.
650  *
651  * This is executed in standard interrupt context.
652  *
653  * Note: spec recommends to panic for fatal unsignalled
654  * errors here. However this would be quite problematic --
655  * we would need to reimplement the Monarch handling and
656  * it would mess up the exclusion between exception handler
657  * and poll handler -- * so we skip this for now.
658  * These cases should not happen anyways, or only when the CPU
659  * is already totally * confused. In this case it's likely it will
660  * not fully execute the machine check handler either.
661  */
662 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
663 {
664         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
665         bool error_seen = false;
666         struct mce m;
667         int i;
668
669         this_cpu_inc(mce_poll_count);
670
671         mce_gather_info(&m, NULL);
672
673         if (flags & MCP_TIMESTAMP)
674                 m.tsc = rdtsc();
675
676         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
677                 if (!mce_banks[i].ctl || !test_bit(i, *b))
678                         continue;
679
680                 m.misc = 0;
681                 m.addr = 0;
682                 m.bank = i;
683
684                 barrier();
685                 m.status = mce_rdmsrl(msr_ops.status(i));
686
687                 /* If this entry is not valid, ignore it */
688                 if (!(m.status & MCI_STATUS_VAL))
689                         continue;
690
691                 /*
692                  * If we are logging everything (at CPU online) or this
693                  * is a corrected error, then we must log it.
694                  */
695                 if ((flags & MCP_UC) || !(m.status & MCI_STATUS_UC))
696                         goto log_it;
697
698                 /*
699                  * Newer Intel systems that support software error
700                  * recovery need to make additional checks. Other
701                  * CPUs should skip over uncorrected errors, but log
702                  * everything else.
703                  */
704                 if (!mca_cfg.ser) {
705                         if (m.status & MCI_STATUS_UC)
706                                 continue;
707                         goto log_it;
708                 }
709
710                 /* Log "not enabled" (speculative) errors */
711                 if (!(m.status & MCI_STATUS_EN))
712                         goto log_it;
713
714                 /*
715                  * Log UCNA (SDM: 15.6.3 "UCR Error Classification")
716                  * UC == 1 && PCC == 0 && S == 0
717                  */
718                 if (!(m.status & MCI_STATUS_PCC) && !(m.status & MCI_STATUS_S))
719                         goto log_it;
720
721                 /*
722                  * Skip anything else. Presumption is that our read of this
723                  * bank is racing with a machine check. Leave the log alone
724                  * for do_machine_check() to deal with it.
725                  */
726                 continue;
727
728 log_it:
729                 error_seen = true;
730
731                 if (flags & MCP_DONTLOG)
732                         goto clear_it;
733
734                 mce_read_aux(&m, i);
735                 m.severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
736                 /*
737                  * Don't get the IP here because it's unlikely to
738                  * have anything to do with the actual error location.
739                  */
740
741                 if (mca_cfg.dont_log_ce && !mce_usable_address(&m))
742                         goto clear_it;
743
744                 mce_log(&m);
745
746 clear_it:
747                 /*
748                  * Clear state for this bank.
749                  */
750                 mce_wrmsrl(msr_ops.status(i), 0);
751         }
752
753         /*
754          * Don't clear MCG_STATUS here because it's only defined for
755          * exceptions.
756          */
757
758         sync_core();
759
760         return error_seen;
761 }
762 EXPORT_SYMBOL_GPL(machine_check_poll);
763
764 /*
765  * Do a quick check if any of the events requires a panic.
766  * This decides if we keep the events around or clear them.
767  */
768 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
769                           struct pt_regs *regs)
770 {
771         char *tmp = *msg;
772         int i;
773
774         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
775                 m->status = mce_rdmsrl(msr_ops.status(i));
776                 if (!(m->status & MCI_STATUS_VAL))
777                         continue;
778
779                 __set_bit(i, validp);
780                 if (quirk_no_way_out)
781                         quirk_no_way_out(i, m, regs);
782
783                 m->bank = i;
784                 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
785                         mce_read_aux(m, i);
786                         *msg = tmp;
787                         return 1;
788                 }
789         }
790         return 0;
791 }
792
793 /*
794  * Variable to establish order between CPUs while scanning.
795  * Each CPU spins initially until executing is equal its number.
796  */
797 static atomic_t mce_executing;
798
799 /*
800  * Defines order of CPUs on entry. First CPU becomes Monarch.
801  */
802 static atomic_t mce_callin;
803
804 /*
805  * Check if a timeout waiting for other CPUs happened.
806  */
807 static int mce_timed_out(u64 *t, const char *msg)
808 {
809         /*
810          * The others already did panic for some reason.
811          * Bail out like in a timeout.
812          * rmb() to tell the compiler that system_state
813          * might have been modified by someone else.
814          */
815         rmb();
816         if (atomic_read(&mce_panicked))
817                 wait_for_panic();
818         if (!mca_cfg.monarch_timeout)
819                 goto out;
820         if ((s64)*t < SPINUNIT) {
821                 if (mca_cfg.tolerant <= 1)
822                         mce_panic(msg, NULL, NULL);
823                 cpu_missing = 1;
824                 return 1;
825         }
826         *t -= SPINUNIT;
827 out:
828         touch_nmi_watchdog();
829         return 0;
830 }
831
832 /*
833  * The Monarch's reign.  The Monarch is the CPU who entered
834  * the machine check handler first. It waits for the others to
835  * raise the exception too and then grades them. When any
836  * error is fatal panic. Only then let the others continue.
837  *
838  * The other CPUs entering the MCE handler will be controlled by the
839  * Monarch. They are called Subjects.
840  *
841  * This way we prevent any potential data corruption in a unrecoverable case
842  * and also makes sure always all CPU's errors are examined.
843  *
844  * Also this detects the case of a machine check event coming from outer
845  * space (not detected by any CPUs) In this case some external agent wants
846  * us to shut down, so panic too.
847  *
848  * The other CPUs might still decide to panic if the handler happens
849  * in a unrecoverable place, but in this case the system is in a semi-stable
850  * state and won't corrupt anything by itself. It's ok to let the others
851  * continue for a bit first.
852  *
853  * All the spin loops have timeouts; when a timeout happens a CPU
854  * typically elects itself to be Monarch.
855  */
856 static void mce_reign(void)
857 {
858         int cpu;
859         struct mce *m = NULL;
860         int global_worst = 0;
861         char *msg = NULL;
862         char *nmsg = NULL;
863
864         /*
865          * This CPU is the Monarch and the other CPUs have run
866          * through their handlers.
867          * Grade the severity of the errors of all the CPUs.
868          */
869         for_each_possible_cpu(cpu) {
870                 int severity = mce_severity(&per_cpu(mces_seen, cpu),
871                                             mca_cfg.tolerant,
872                                             &nmsg, true);
873                 if (severity > global_worst) {
874                         msg = nmsg;
875                         global_worst = severity;
876                         m = &per_cpu(mces_seen, cpu);
877                 }
878         }
879
880         /*
881          * Cannot recover? Panic here then.
882          * This dumps all the mces in the log buffer and stops the
883          * other CPUs.
884          */
885         if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
886                 mce_panic("Fatal machine check", m, msg);
887
888         /*
889          * For UC somewhere we let the CPU who detects it handle it.
890          * Also must let continue the others, otherwise the handling
891          * CPU could deadlock on a lock.
892          */
893
894         /*
895          * No machine check event found. Must be some external
896          * source or one CPU is hung. Panic.
897          */
898         if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
899                 mce_panic("Fatal machine check from unknown source", NULL, NULL);
900
901         /*
902          * Now clear all the mces_seen so that they don't reappear on
903          * the next mce.
904          */
905         for_each_possible_cpu(cpu)
906                 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
907 }
908
909 static atomic_t global_nwo;
910
911 /*
912  * Start of Monarch synchronization. This waits until all CPUs have
913  * entered the exception handler and then determines if any of them
914  * saw a fatal event that requires panic. Then it executes them
915  * in the entry order.
916  * TBD double check parallel CPU hotunplug
917  */
918 static int mce_start(int *no_way_out)
919 {
920         int order;
921         int cpus = num_online_cpus();
922         u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
923
924         if (!timeout)
925                 return -1;
926
927         atomic_add(*no_way_out, &global_nwo);
928         /*
929          * Rely on the implied barrier below, such that global_nwo
930          * is updated before mce_callin.
931          */
932         order = atomic_inc_return(&mce_callin);
933
934         /*
935          * Wait for everyone.
936          */
937         while (atomic_read(&mce_callin) != cpus) {
938                 if (mce_timed_out(&timeout,
939                                   "Timeout: Not all CPUs entered broadcast exception handler")) {
940                         atomic_set(&global_nwo, 0);
941                         return -1;
942                 }
943                 ndelay(SPINUNIT);
944         }
945
946         /*
947          * mce_callin should be read before global_nwo
948          */
949         smp_rmb();
950
951         if (order == 1) {
952                 /*
953                  * Monarch: Starts executing now, the others wait.
954                  */
955                 atomic_set(&mce_executing, 1);
956         } else {
957                 /*
958                  * Subject: Now start the scanning loop one by one in
959                  * the original callin order.
960                  * This way when there are any shared banks it will be
961                  * only seen by one CPU before cleared, avoiding duplicates.
962                  */
963                 while (atomic_read(&mce_executing) < order) {
964                         if (mce_timed_out(&timeout,
965                                           "Timeout: Subject CPUs unable to finish machine check processing")) {
966                                 atomic_set(&global_nwo, 0);
967                                 return -1;
968                         }
969                         ndelay(SPINUNIT);
970                 }
971         }
972
973         /*
974          * Cache the global no_way_out state.
975          */
976         *no_way_out = atomic_read(&global_nwo);
977
978         return order;
979 }
980
981 /*
982  * Synchronize between CPUs after main scanning loop.
983  * This invokes the bulk of the Monarch processing.
984  */
985 static int mce_end(int order)
986 {
987         int ret = -1;
988         u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
989
990         if (!timeout)
991                 goto reset;
992         if (order < 0)
993                 goto reset;
994
995         /*
996          * Allow others to run.
997          */
998         atomic_inc(&mce_executing);
999
1000         if (order == 1) {
1001                 /* CHECKME: Can this race with a parallel hotplug? */
1002                 int cpus = num_online_cpus();
1003
1004                 /*
1005                  * Monarch: Wait for everyone to go through their scanning
1006                  * loops.
1007                  */
1008                 while (atomic_read(&mce_executing) <= cpus) {
1009                         if (mce_timed_out(&timeout,
1010                                           "Timeout: Monarch CPU unable to finish machine check processing"))
1011                                 goto reset;
1012                         ndelay(SPINUNIT);
1013                 }
1014
1015                 mce_reign();
1016                 barrier();
1017                 ret = 0;
1018         } else {
1019                 /*
1020                  * Subject: Wait for Monarch to finish.
1021                  */
1022                 while (atomic_read(&mce_executing) != 0) {
1023                         if (mce_timed_out(&timeout,
1024                                           "Timeout: Monarch CPU did not finish machine check processing"))
1025                                 goto reset;
1026                         ndelay(SPINUNIT);
1027                 }
1028
1029                 /*
1030                  * Don't reset anything. That's done by the Monarch.
1031                  */
1032                 return 0;
1033         }
1034
1035         /*
1036          * Reset all global state.
1037          */
1038 reset:
1039         atomic_set(&global_nwo, 0);
1040         atomic_set(&mce_callin, 0);
1041         barrier();
1042
1043         /*
1044          * Let others run again.
1045          */
1046         atomic_set(&mce_executing, 0);
1047         return ret;
1048 }
1049
1050 static void mce_clear_state(unsigned long *toclear)
1051 {
1052         int i;
1053
1054         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1055                 if (test_bit(i, toclear))
1056                         mce_wrmsrl(msr_ops.status(i), 0);
1057         }
1058 }
1059
1060 static int do_memory_failure(struct mce *m)
1061 {
1062         int flags = MF_ACTION_REQUIRED;
1063         int ret;
1064
1065         pr_err("Uncorrected hardware memory error in user-access at %llx", m->addr);
1066         if (!(m->mcgstatus & MCG_STATUS_RIPV))
1067                 flags |= MF_MUST_KILL;
1068         ret = memory_failure(m->addr >> PAGE_SHIFT, flags);
1069         if (ret)
1070                 pr_err("Memory error not recovered");
1071         else
1072                 set_mce_nospec(m->addr >> PAGE_SHIFT);
1073         return ret;
1074 }
1075
1076
1077 /*
1078  * Cases where we avoid rendezvous handler timeout:
1079  * 1) If this CPU is offline.
1080  *
1081  * 2) If crashing_cpu was set, e.g. we're entering kdump and we need to
1082  *  skip those CPUs which remain looping in the 1st kernel - see
1083  *  crash_nmi_callback().
1084  *
1085  * Note: there still is a small window between kexec-ing and the new,
1086  * kdump kernel establishing a new #MC handler where a broadcasted MCE
1087  * might not get handled properly.
1088  */
1089 static bool __mc_check_crashing_cpu(int cpu)
1090 {
1091         if (cpu_is_offline(cpu) ||
1092             (crashing_cpu != -1 && crashing_cpu != cpu)) {
1093                 u64 mcgstatus;
1094
1095                 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1096
1097                 if (boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN) {
1098                         if (mcgstatus & MCG_STATUS_LMCES)
1099                                 return false;
1100                 }
1101
1102                 if (mcgstatus & MCG_STATUS_RIPV) {
1103                         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1104                         return true;
1105                 }
1106         }
1107         return false;
1108 }
1109
1110 static void __mc_scan_banks(struct mce *m, struct mce *final,
1111                             unsigned long *toclear, unsigned long *valid_banks,
1112                             int no_way_out, int *worst)
1113 {
1114         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1115         struct mca_config *cfg = &mca_cfg;
1116         int severity, i;
1117
1118         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1119                 __clear_bit(i, toclear);
1120                 if (!test_bit(i, valid_banks))
1121                         continue;
1122
1123                 if (!mce_banks[i].ctl)
1124                         continue;
1125
1126                 m->misc = 0;
1127                 m->addr = 0;
1128                 m->bank = i;
1129
1130                 m->status = mce_rdmsrl(msr_ops.status(i));
1131                 if (!(m->status & MCI_STATUS_VAL))
1132                         continue;
1133
1134                 /*
1135                  * Corrected or non-signaled errors are handled by
1136                  * machine_check_poll(). Leave them alone, unless this panics.
1137                  */
1138                 if (!(m->status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1139                         !no_way_out)
1140                         continue;
1141
1142                 /* Set taint even when machine check was not enabled. */
1143                 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1144
1145                 severity = mce_severity(m, cfg->tolerant, NULL, true);
1146
1147                 /*
1148                  * When machine check was for corrected/deferred handler don't
1149                  * touch, unless we're panicking.
1150                  */
1151                 if ((severity == MCE_KEEP_SEVERITY ||
1152                      severity == MCE_UCNA_SEVERITY) && !no_way_out)
1153                         continue;
1154
1155                 __set_bit(i, toclear);
1156
1157                 /* Machine check event was not enabled. Clear, but ignore. */
1158                 if (severity == MCE_NO_SEVERITY)
1159                         continue;
1160
1161                 mce_read_aux(m, i);
1162
1163                 /* assuming valid severity level != 0 */
1164                 m->severity = severity;
1165
1166                 mce_log(m);
1167
1168                 if (severity > *worst) {
1169                         *final = *m;
1170                         *worst = severity;
1171                 }
1172         }
1173
1174         /* mce_clear_state will clear *final, save locally for use later */
1175         *m = *final;
1176 }
1177
1178 /*
1179  * The actual machine check handler. This only handles real
1180  * exceptions when something got corrupted coming in through int 18.
1181  *
1182  * This is executed in NMI context not subject to normal locking rules. This
1183  * implies that most kernel services cannot be safely used. Don't even
1184  * think about putting a printk in there!
1185  *
1186  * On Intel systems this is entered on all CPUs in parallel through
1187  * MCE broadcast. However some CPUs might be broken beyond repair,
1188  * so be always careful when synchronizing with others.
1189  *
1190  * Tracing and kprobes are disabled: if we interrupted a kernel context
1191  * with IF=1, we need to minimize stack usage.  There are also recursion
1192  * issues: if the machine check was due to a failure of the memory
1193  * backing the user stack, tracing that reads the user stack will cause
1194  * potentially infinite recursion.
1195  */
1196 void notrace do_machine_check(struct pt_regs *regs, long error_code)
1197 {
1198         DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1199         DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1200         struct mca_config *cfg = &mca_cfg;
1201         int cpu = smp_processor_id();
1202         struct mce m, *final;
1203         char *msg = NULL;
1204         int worst = 0;
1205
1206         /*
1207          * Establish sequential order between the CPUs entering the machine
1208          * check handler.
1209          */
1210         int order = -1;
1211
1212         /*
1213          * If no_way_out gets set, there is no safe way to recover from this
1214          * MCE.  If mca_cfg.tolerant is cranked up, we'll try anyway.
1215          */
1216         int no_way_out = 0;
1217
1218         /*
1219          * If kill_it gets set, there might be a way to recover from this
1220          * error.
1221          */
1222         int kill_it = 0;
1223
1224         /*
1225          * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1226          * on Intel.
1227          */
1228         int lmce = 1;
1229
1230         if (__mc_check_crashing_cpu(cpu))
1231                 return;
1232
1233         ist_enter(regs);
1234
1235         this_cpu_inc(mce_exception_count);
1236
1237         mce_gather_info(&m, regs);
1238         m.tsc = rdtsc();
1239
1240         final = this_cpu_ptr(&mces_seen);
1241         *final = m;
1242
1243         memset(valid_banks, 0, sizeof(valid_banks));
1244         no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1245
1246         barrier();
1247
1248         /*
1249          * When no restart IP might need to kill or panic.
1250          * Assume the worst for now, but if we find the
1251          * severity is MCE_AR_SEVERITY we have other options.
1252          */
1253         if (!(m.mcgstatus & MCG_STATUS_RIPV))
1254                 kill_it = 1;
1255
1256         /*
1257          * Check if this MCE is signaled to only this logical processor,
1258          * on Intel, Zhaoxin only.
1259          */
1260         if (m.cpuvendor == X86_VENDOR_INTEL ||
1261             m.cpuvendor == X86_VENDOR_ZHAOXIN)
1262                 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1263
1264         /*
1265          * Local machine check may already know that we have to panic.
1266          * Broadcast machine check begins rendezvous in mce_start()
1267          * Go through all banks in exclusion of the other CPUs. This way we
1268          * don't report duplicated events on shared banks because the first one
1269          * to see it will clear it.
1270          */
1271         if (lmce) {
1272                 if (no_way_out)
1273                         mce_panic("Fatal local machine check", &m, msg);
1274         } else {
1275                 order = mce_start(&no_way_out);
1276         }
1277
1278         __mc_scan_banks(&m, final, toclear, valid_banks, no_way_out, &worst);
1279
1280         if (!no_way_out)
1281                 mce_clear_state(toclear);
1282
1283         /*
1284          * Do most of the synchronization with other CPUs.
1285          * When there's any problem use only local no_way_out state.
1286          */
1287         if (!lmce) {
1288                 if (mce_end(order) < 0)
1289                         no_way_out = worst >= MCE_PANIC_SEVERITY;
1290         } else {
1291                 /*
1292                  * If there was a fatal machine check we should have
1293                  * already called mce_panic earlier in this function.
1294                  * Since we re-read the banks, we might have found
1295                  * something new. Check again to see if we found a
1296                  * fatal error. We call "mce_severity()" again to
1297                  * make sure we have the right "msg".
1298                  */
1299                 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3) {
1300                         mce_severity(&m, cfg->tolerant, &msg, true);
1301                         mce_panic("Local fatal machine check!", &m, msg);
1302                 }
1303         }
1304
1305         /*
1306          * If tolerant is at an insane level we drop requests to kill
1307          * processes and continue even when there is no way out.
1308          */
1309         if (cfg->tolerant == 3)
1310                 kill_it = 0;
1311         else if (no_way_out)
1312                 mce_panic("Fatal machine check on current CPU", &m, msg);
1313
1314         if (worst > 0)
1315                 irq_work_queue(&mce_irq_work);
1316
1317         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1318
1319         sync_core();
1320
1321         if (worst != MCE_AR_SEVERITY && !kill_it)
1322                 goto out_ist;
1323
1324         /* Fault was in user mode and we need to take some action */
1325         if ((m.cs & 3) == 3) {
1326                 ist_begin_non_atomic(regs);
1327                 local_irq_enable();
1328
1329                 if (kill_it || do_memory_failure(&m))
1330                         force_sig(SIGBUS);
1331                 local_irq_disable();
1332                 ist_end_non_atomic();
1333         } else {
1334                 /*
1335                  * Handle an MCE which has happened in kernel space but from
1336                  * which the kernel can recover: ex_has_fault_handler() has
1337                  * already verified that the rIP at which the error happened is
1338                  * a rIP from which the kernel can recover (by jumping to
1339                  * recovery code specified in _ASM_EXTABLE_FAULT()) and the
1340                  * corresponding exception handler which would do that is the
1341                  * proper one.
1342                  */
1343                 if (m.kflags & MCE_IN_KERNEL_RECOV) {
1344                         if (!fixup_exception(regs, X86_TRAP_MC, error_code, 0))
1345                                 mce_panic("Failed kernel mode recovery", &m, msg);
1346                 }
1347         }
1348
1349 out_ist:
1350         ist_exit(regs);
1351 }
1352 EXPORT_SYMBOL_GPL(do_machine_check);
1353 NOKPROBE_SYMBOL(do_machine_check);
1354
1355 #ifndef CONFIG_MEMORY_FAILURE
1356 int memory_failure(unsigned long pfn, int flags)
1357 {
1358         /* mce_severity() should not hand us an ACTION_REQUIRED error */
1359         BUG_ON(flags & MF_ACTION_REQUIRED);
1360         pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1361                "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1362                pfn);
1363
1364         return 0;
1365 }
1366 #endif
1367
1368 /*
1369  * Periodic polling timer for "silent" machine check errors.  If the
1370  * poller finds an MCE, poll 2x faster.  When the poller finds no more
1371  * errors, poll 2x slower (up to check_interval seconds).
1372  */
1373 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1374
1375 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1376 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1377
1378 static unsigned long mce_adjust_timer_default(unsigned long interval)
1379 {
1380         return interval;
1381 }
1382
1383 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1384
1385 static void __start_timer(struct timer_list *t, unsigned long interval)
1386 {
1387         unsigned long when = jiffies + interval;
1388         unsigned long flags;
1389
1390         local_irq_save(flags);
1391
1392         if (!timer_pending(t) || time_before(when, t->expires))
1393                 mod_timer(t, round_jiffies(when));
1394
1395         local_irq_restore(flags);
1396 }
1397
1398 static void mce_timer_fn(struct timer_list *t)
1399 {
1400         struct timer_list *cpu_t = this_cpu_ptr(&mce_timer);
1401         unsigned long iv;
1402
1403         WARN_ON(cpu_t != t);
1404
1405         iv = __this_cpu_read(mce_next_interval);
1406
1407         if (mce_available(this_cpu_ptr(&cpu_info))) {
1408                 machine_check_poll(0, this_cpu_ptr(&mce_poll_banks));
1409
1410                 if (mce_intel_cmci_poll()) {
1411                         iv = mce_adjust_timer(iv);
1412                         goto done;
1413                 }
1414         }
1415
1416         /*
1417          * Alert userspace if needed. If we logged an MCE, reduce the polling
1418          * interval, otherwise increase the polling interval.
1419          */
1420         if (mce_notify_irq())
1421                 iv = max(iv / 2, (unsigned long) HZ/100);
1422         else
1423                 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1424
1425 done:
1426         __this_cpu_write(mce_next_interval, iv);
1427         __start_timer(t, iv);
1428 }
1429
1430 /*
1431  * Ensure that the timer is firing in @interval from now.
1432  */
1433 void mce_timer_kick(unsigned long interval)
1434 {
1435         struct timer_list *t = this_cpu_ptr(&mce_timer);
1436         unsigned long iv = __this_cpu_read(mce_next_interval);
1437
1438         __start_timer(t, interval);
1439
1440         if (interval < iv)
1441                 __this_cpu_write(mce_next_interval, interval);
1442 }
1443
1444 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1445 static void mce_timer_delete_all(void)
1446 {
1447         int cpu;
1448
1449         for_each_online_cpu(cpu)
1450                 del_timer_sync(&per_cpu(mce_timer, cpu));
1451 }
1452
1453 /*
1454  * Notify the user(s) about new machine check events.
1455  * Can be called from interrupt context, but not from machine check/NMI
1456  * context.
1457  */
1458 int mce_notify_irq(void)
1459 {
1460         /* Not more than two messages every minute */
1461         static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1462
1463         if (test_and_clear_bit(0, &mce_need_notify)) {
1464                 mce_work_trigger();
1465
1466                 if (__ratelimit(&ratelimit))
1467                         pr_info(HW_ERR "Machine check events logged\n");
1468
1469                 return 1;
1470         }
1471         return 0;
1472 }
1473 EXPORT_SYMBOL_GPL(mce_notify_irq);
1474
1475 static void __mcheck_cpu_mce_banks_init(void)
1476 {
1477         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1478         u8 n_banks = this_cpu_read(mce_num_banks);
1479         int i;
1480
1481         for (i = 0; i < n_banks; i++) {
1482                 struct mce_bank *b = &mce_banks[i];
1483
1484                 /*
1485                  * Init them all, __mcheck_cpu_apply_quirks() is going to apply
1486                  * the required vendor quirks before
1487                  * __mcheck_cpu_init_clear_banks() does the final bank setup.
1488                  */
1489                 b->ctl = -1ULL;
1490                 b->init = 1;
1491         }
1492 }
1493
1494 /*
1495  * Initialize Machine Checks for a CPU.
1496  */
1497 static void __mcheck_cpu_cap_init(void)
1498 {
1499         u64 cap;
1500         u8 b;
1501
1502         rdmsrl(MSR_IA32_MCG_CAP, cap);
1503
1504         b = cap & MCG_BANKCNT_MASK;
1505
1506         if (b > MAX_NR_BANKS) {
1507                 pr_warn("CPU%d: Using only %u machine check banks out of %u\n",
1508                         smp_processor_id(), MAX_NR_BANKS, b);
1509                 b = MAX_NR_BANKS;
1510         }
1511
1512         this_cpu_write(mce_num_banks, b);
1513
1514         __mcheck_cpu_mce_banks_init();
1515
1516         /* Use accurate RIP reporting if available. */
1517         if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1518                 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1519
1520         if (cap & MCG_SER_P)
1521                 mca_cfg.ser = 1;
1522 }
1523
1524 static void __mcheck_cpu_init_generic(void)
1525 {
1526         enum mcp_flags m_fl = 0;
1527         mce_banks_t all_banks;
1528         u64 cap;
1529
1530         if (!mca_cfg.bootlog)
1531                 m_fl = MCP_DONTLOG;
1532
1533         /*
1534          * Log the machine checks left over from the previous reset.
1535          */
1536         bitmap_fill(all_banks, MAX_NR_BANKS);
1537         machine_check_poll(MCP_UC | m_fl, &all_banks);
1538
1539         cr4_set_bits(X86_CR4_MCE);
1540
1541         rdmsrl(MSR_IA32_MCG_CAP, cap);
1542         if (cap & MCG_CTL_P)
1543                 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1544 }
1545
1546 static void __mcheck_cpu_init_clear_banks(void)
1547 {
1548         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1549         int i;
1550
1551         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1552                 struct mce_bank *b = &mce_banks[i];
1553
1554                 if (!b->init)
1555                         continue;
1556                 wrmsrl(msr_ops.ctl(i), b->ctl);
1557                 wrmsrl(msr_ops.status(i), 0);
1558         }
1559 }
1560
1561 /*
1562  * Do a final check to see if there are any unused/RAZ banks.
1563  *
1564  * This must be done after the banks have been initialized and any quirks have
1565  * been applied.
1566  *
1567  * Do not call this from any user-initiated flows, e.g. CPU hotplug or sysfs.
1568  * Otherwise, a user who disables a bank will not be able to re-enable it
1569  * without a system reboot.
1570  */
1571 static void __mcheck_cpu_check_banks(void)
1572 {
1573         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1574         u64 msrval;
1575         int i;
1576
1577         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1578                 struct mce_bank *b = &mce_banks[i];
1579
1580                 if (!b->init)
1581                         continue;
1582
1583                 rdmsrl(msr_ops.ctl(i), msrval);
1584                 b->init = !!msrval;
1585         }
1586 }
1587
1588 /*
1589  * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1590  * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1591  * Vol 3B Table 15-20). But this confuses both the code that determines
1592  * whether the machine check occurred in kernel or user mode, and also
1593  * the severity assessment code. Pretend that EIPV was set, and take the
1594  * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1595  */
1596 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1597 {
1598         if (bank != 0)
1599                 return;
1600         if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1601                 return;
1602         if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1603                           MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1604                           MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1605                           MCACOD)) !=
1606                          (MCI_STATUS_UC|MCI_STATUS_EN|
1607                           MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1608                           MCI_STATUS_AR|MCACOD_INSTR))
1609                 return;
1610
1611         m->mcgstatus |= MCG_STATUS_EIPV;
1612         m->ip = regs->ip;
1613         m->cs = regs->cs;
1614 }
1615
1616 /* Add per CPU specific workarounds here */
1617 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1618 {
1619         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1620         struct mca_config *cfg = &mca_cfg;
1621
1622         if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1623                 pr_info("unknown CPU type - not enabling MCE support\n");
1624                 return -EOPNOTSUPP;
1625         }
1626
1627         /* This should be disabled by the BIOS, but isn't always */
1628         if (c->x86_vendor == X86_VENDOR_AMD) {
1629                 if (c->x86 == 15 && this_cpu_read(mce_num_banks) > 4) {
1630                         /*
1631                          * disable GART TBL walk error reporting, which
1632                          * trips off incorrectly with the IOMMU & 3ware
1633                          * & Cerberus:
1634                          */
1635                         clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1636                 }
1637                 if (c->x86 < 0x11 && cfg->bootlog < 0) {
1638                         /*
1639                          * Lots of broken BIOS around that don't clear them
1640                          * by default and leave crap in there. Don't log:
1641                          */
1642                         cfg->bootlog = 0;
1643                 }
1644                 /*
1645                  * Various K7s with broken bank 0 around. Always disable
1646                  * by default.
1647                  */
1648                 if (c->x86 == 6 && this_cpu_read(mce_num_banks) > 0)
1649                         mce_banks[0].ctl = 0;
1650
1651                 /*
1652                  * overflow_recov is supported for F15h Models 00h-0fh
1653                  * even though we don't have a CPUID bit for it.
1654                  */
1655                 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1656                         mce_flags.overflow_recov = 1;
1657
1658         }
1659
1660         if (c->x86_vendor == X86_VENDOR_INTEL) {
1661                 /*
1662                  * SDM documents that on family 6 bank 0 should not be written
1663                  * because it aliases to another special BIOS controlled
1664                  * register.
1665                  * But it's not aliased anymore on model 0x1a+
1666                  * Don't ignore bank 0 completely because there could be a
1667                  * valid event later, merely don't write CTL0.
1668                  */
1669
1670                 if (c->x86 == 6 && c->x86_model < 0x1A && this_cpu_read(mce_num_banks) > 0)
1671                         mce_banks[0].init = 0;
1672
1673                 /*
1674                  * All newer Intel systems support MCE broadcasting. Enable
1675                  * synchronization with a one second timeout.
1676                  */
1677                 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1678                         cfg->monarch_timeout < 0)
1679                         cfg->monarch_timeout = USEC_PER_SEC;
1680
1681                 /*
1682                  * There are also broken BIOSes on some Pentium M and
1683                  * earlier systems:
1684                  */
1685                 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1686                         cfg->bootlog = 0;
1687
1688                 if (c->x86 == 6 && c->x86_model == 45)
1689                         quirk_no_way_out = quirk_sandybridge_ifu;
1690         }
1691
1692         if (c->x86_vendor == X86_VENDOR_ZHAOXIN) {
1693                 /*
1694                  * All newer Zhaoxin CPUs support MCE broadcasting. Enable
1695                  * synchronization with a one second timeout.
1696                  */
1697                 if (c->x86 > 6 || (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1698                         if (cfg->monarch_timeout < 0)
1699                                 cfg->monarch_timeout = USEC_PER_SEC;
1700                 }
1701         }
1702
1703         if (cfg->monarch_timeout < 0)
1704                 cfg->monarch_timeout = 0;
1705         if (cfg->bootlog != 0)
1706                 cfg->panic_timeout = 30;
1707
1708         return 0;
1709 }
1710
1711 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1712 {
1713         if (c->x86 != 5)
1714                 return 0;
1715
1716         switch (c->x86_vendor) {
1717         case X86_VENDOR_INTEL:
1718                 intel_p5_mcheck_init(c);
1719                 return 1;
1720                 break;
1721         case X86_VENDOR_CENTAUR:
1722                 winchip_mcheck_init(c);
1723                 return 1;
1724                 break;
1725         default:
1726                 return 0;
1727         }
1728
1729         return 0;
1730 }
1731
1732 /*
1733  * Init basic CPU features needed for early decoding of MCEs.
1734  */
1735 static void __mcheck_cpu_init_early(struct cpuinfo_x86 *c)
1736 {
1737         if (c->x86_vendor == X86_VENDOR_AMD || c->x86_vendor == X86_VENDOR_HYGON) {
1738                 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1739                 mce_flags.succor         = !!cpu_has(c, X86_FEATURE_SUCCOR);
1740                 mce_flags.smca           = !!cpu_has(c, X86_FEATURE_SMCA);
1741                 mce_flags.amd_threshold  = 1;
1742
1743                 if (mce_flags.smca) {
1744                         msr_ops.ctl     = smca_ctl_reg;
1745                         msr_ops.status  = smca_status_reg;
1746                         msr_ops.addr    = smca_addr_reg;
1747                         msr_ops.misc    = smca_misc_reg;
1748                 }
1749         }
1750 }
1751
1752 static void mce_centaur_feature_init(struct cpuinfo_x86 *c)
1753 {
1754         struct mca_config *cfg = &mca_cfg;
1755
1756          /*
1757           * All newer Centaur CPUs support MCE broadcasting. Enable
1758           * synchronization with a one second timeout.
1759           */
1760         if ((c->x86 == 6 && c->x86_model == 0xf && c->x86_stepping >= 0xe) ||
1761              c->x86 > 6) {
1762                 if (cfg->monarch_timeout < 0)
1763                         cfg->monarch_timeout = USEC_PER_SEC;
1764         }
1765 }
1766
1767 static void mce_zhaoxin_feature_init(struct cpuinfo_x86 *c)
1768 {
1769         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1770
1771         /*
1772          * These CPUs have MCA bank 8 which reports only one error type called
1773          * SVAD (System View Address Decoder). The reporting of that error is
1774          * controlled by IA32_MC8.CTL.0.
1775          *
1776          * If enabled, prefetching on these CPUs will cause SVAD MCE when
1777          * virtual machines start and result in a system  panic. Always disable
1778          * bank 8 SVAD error by default.
1779          */
1780         if ((c->x86 == 7 && c->x86_model == 0x1b) ||
1781             (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1782                 if (this_cpu_read(mce_num_banks) > 8)
1783                         mce_banks[8].ctl = 0;
1784         }
1785
1786         intel_init_cmci();
1787         intel_init_lmce();
1788         mce_adjust_timer = cmci_intel_adjust_timer;
1789 }
1790
1791 static void mce_zhaoxin_feature_clear(struct cpuinfo_x86 *c)
1792 {
1793         intel_clear_lmce();
1794 }
1795
1796 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1797 {
1798         switch (c->x86_vendor) {
1799         case X86_VENDOR_INTEL:
1800                 mce_intel_feature_init(c);
1801                 mce_adjust_timer = cmci_intel_adjust_timer;
1802                 break;
1803
1804         case X86_VENDOR_AMD: {
1805                 mce_amd_feature_init(c);
1806                 break;
1807                 }
1808
1809         case X86_VENDOR_HYGON:
1810                 mce_hygon_feature_init(c);
1811                 break;
1812
1813         case X86_VENDOR_CENTAUR:
1814                 mce_centaur_feature_init(c);
1815                 break;
1816
1817         case X86_VENDOR_ZHAOXIN:
1818                 mce_zhaoxin_feature_init(c);
1819                 break;
1820
1821         default:
1822                 break;
1823         }
1824 }
1825
1826 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1827 {
1828         switch (c->x86_vendor) {
1829         case X86_VENDOR_INTEL:
1830                 mce_intel_feature_clear(c);
1831                 break;
1832
1833         case X86_VENDOR_ZHAOXIN:
1834                 mce_zhaoxin_feature_clear(c);
1835                 break;
1836
1837         default:
1838                 break;
1839         }
1840 }
1841
1842 static void mce_start_timer(struct timer_list *t)
1843 {
1844         unsigned long iv = check_interval * HZ;
1845
1846         if (mca_cfg.ignore_ce || !iv)
1847                 return;
1848
1849         this_cpu_write(mce_next_interval, iv);
1850         __start_timer(t, iv);
1851 }
1852
1853 static void __mcheck_cpu_setup_timer(void)
1854 {
1855         struct timer_list *t = this_cpu_ptr(&mce_timer);
1856
1857         timer_setup(t, mce_timer_fn, TIMER_PINNED);
1858 }
1859
1860 static void __mcheck_cpu_init_timer(void)
1861 {
1862         struct timer_list *t = this_cpu_ptr(&mce_timer);
1863
1864         timer_setup(t, mce_timer_fn, TIMER_PINNED);
1865         mce_start_timer(t);
1866 }
1867
1868 bool filter_mce(struct mce *m)
1869 {
1870         if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1871                 return amd_filter_mce(m);
1872         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
1873                 return intel_filter_mce(m);
1874
1875         return false;
1876 }
1877
1878 /* Handle unconfigured int18 (should never happen) */
1879 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1880 {
1881         pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1882                smp_processor_id());
1883 }
1884
1885 /* Call the installed machine check handler for this CPU setup. */
1886 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1887                                                 unexpected_machine_check;
1888
1889 dotraplinkage notrace void do_mce(struct pt_regs *regs, long error_code)
1890 {
1891         machine_check_vector(regs, error_code);
1892 }
1893 NOKPROBE_SYMBOL(do_mce);
1894
1895 /*
1896  * Called for each booted CPU to set up machine checks.
1897  * Must be called with preempt off:
1898  */
1899 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1900 {
1901         if (mca_cfg.disabled)
1902                 return;
1903
1904         if (__mcheck_cpu_ancient_init(c))
1905                 return;
1906
1907         if (!mce_available(c))
1908                 return;
1909
1910         __mcheck_cpu_cap_init();
1911
1912         if (__mcheck_cpu_apply_quirks(c) < 0) {
1913                 mca_cfg.disabled = 1;
1914                 return;
1915         }
1916
1917         if (mce_gen_pool_init()) {
1918                 mca_cfg.disabled = 1;
1919                 pr_emerg("Couldn't allocate MCE records pool!\n");
1920                 return;
1921         }
1922
1923         machine_check_vector = do_machine_check;
1924
1925         __mcheck_cpu_init_early(c);
1926         __mcheck_cpu_init_generic();
1927         __mcheck_cpu_init_vendor(c);
1928         __mcheck_cpu_init_clear_banks();
1929         __mcheck_cpu_check_banks();
1930         __mcheck_cpu_setup_timer();
1931 }
1932
1933 /*
1934  * Called for each booted CPU to clear some machine checks opt-ins
1935  */
1936 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1937 {
1938         if (mca_cfg.disabled)
1939                 return;
1940
1941         if (!mce_available(c))
1942                 return;
1943
1944         /*
1945          * Possibly to clear general settings generic to x86
1946          * __mcheck_cpu_clear_generic(c);
1947          */
1948         __mcheck_cpu_clear_vendor(c);
1949
1950 }
1951
1952 static void __mce_disable_bank(void *arg)
1953 {
1954         int bank = *((int *)arg);
1955         __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1956         cmci_disable_bank(bank);
1957 }
1958
1959 void mce_disable_bank(int bank)
1960 {
1961         if (bank >= this_cpu_read(mce_num_banks)) {
1962                 pr_warn(FW_BUG
1963                         "Ignoring request to disable invalid MCA bank %d.\n",
1964                         bank);
1965                 return;
1966         }
1967         set_bit(bank, mce_banks_ce_disabled);
1968         on_each_cpu(__mce_disable_bank, &bank, 1);
1969 }
1970
1971 /*
1972  * mce=off Disables machine check
1973  * mce=no_cmci Disables CMCI
1974  * mce=no_lmce Disables LMCE
1975  * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1976  * mce=print_all Print all machine check logs to console
1977  * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1978  * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1979  *      monarchtimeout is how long to wait for other CPUs on machine
1980  *      check, or 0 to not wait
1981  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD Fam10h
1982         and older.
1983  * mce=nobootlog Don't log MCEs from before booting.
1984  * mce=bios_cmci_threshold Don't program the CMCI threshold
1985  * mce=recovery force enable memcpy_mcsafe()
1986  */
1987 static int __init mcheck_enable(char *str)
1988 {
1989         struct mca_config *cfg = &mca_cfg;
1990
1991         if (*str == 0) {
1992                 enable_p5_mce();
1993                 return 1;
1994         }
1995         if (*str == '=')
1996                 str++;
1997         if (!strcmp(str, "off"))
1998                 cfg->disabled = 1;
1999         else if (!strcmp(str, "no_cmci"))
2000                 cfg->cmci_disabled = true;
2001         else if (!strcmp(str, "no_lmce"))
2002                 cfg->lmce_disabled = 1;
2003         else if (!strcmp(str, "dont_log_ce"))
2004                 cfg->dont_log_ce = true;
2005         else if (!strcmp(str, "print_all"))
2006                 cfg->print_all = true;
2007         else if (!strcmp(str, "ignore_ce"))
2008                 cfg->ignore_ce = true;
2009         else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2010                 cfg->bootlog = (str[0] == 'b');
2011         else if (!strcmp(str, "bios_cmci_threshold"))
2012                 cfg->bios_cmci_threshold = 1;
2013         else if (!strcmp(str, "recovery"))
2014                 cfg->recovery = 1;
2015         else if (isdigit(str[0])) {
2016                 if (get_option(&str, &cfg->tolerant) == 2)
2017                         get_option(&str, &(cfg->monarch_timeout));
2018         } else {
2019                 pr_info("mce argument %s ignored. Please use /sys\n", str);
2020                 return 0;
2021         }
2022         return 1;
2023 }
2024 __setup("mce", mcheck_enable);
2025
2026 int __init mcheck_init(void)
2027 {
2028         mcheck_intel_therm_init();
2029         mce_register_decode_chain(&early_nb);
2030         mce_register_decode_chain(&mce_uc_nb);
2031         mce_register_decode_chain(&mce_default_nb);
2032         mcheck_vendor_init_severity();
2033
2034         INIT_WORK(&mce_work, mce_gen_pool_process);
2035         init_irq_work(&mce_irq_work, mce_irq_work_cb);
2036
2037         return 0;
2038 }
2039
2040 /*
2041  * mce_syscore: PM support
2042  */
2043
2044 /*
2045  * Disable machine checks on suspend and shutdown. We can't really handle
2046  * them later.
2047  */
2048 static void mce_disable_error_reporting(void)
2049 {
2050         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2051         int i;
2052
2053         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2054                 struct mce_bank *b = &mce_banks[i];
2055
2056                 if (b->init)
2057                         wrmsrl(msr_ops.ctl(i), 0);
2058         }
2059         return;
2060 }
2061
2062 static void vendor_disable_error_reporting(void)
2063 {
2064         /*
2065          * Don't clear on Intel or AMD or Hygon or Zhaoxin CPUs. Some of these
2066          * MSRs are socket-wide. Disabling them for just a single offlined CPU
2067          * is bad, since it will inhibit reporting for all shared resources on
2068          * the socket like the last level cache (LLC), the integrated memory
2069          * controller (iMC), etc.
2070          */
2071         if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL ||
2072             boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ||
2073             boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
2074             boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN)
2075                 return;
2076
2077         mce_disable_error_reporting();
2078 }
2079
2080 static int mce_syscore_suspend(void)
2081 {
2082         vendor_disable_error_reporting();
2083         return 0;
2084 }
2085
2086 static void mce_syscore_shutdown(void)
2087 {
2088         vendor_disable_error_reporting();
2089 }
2090
2091 /*
2092  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2093  * Only one CPU is active at this time, the others get re-added later using
2094  * CPU hotplug:
2095  */
2096 static void mce_syscore_resume(void)
2097 {
2098         __mcheck_cpu_init_generic();
2099         __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2100         __mcheck_cpu_init_clear_banks();
2101 }
2102
2103 static struct syscore_ops mce_syscore_ops = {
2104         .suspend        = mce_syscore_suspend,
2105         .shutdown       = mce_syscore_shutdown,
2106         .resume         = mce_syscore_resume,
2107 };
2108
2109 /*
2110  * mce_device: Sysfs support
2111  */
2112
2113 static void mce_cpu_restart(void *data)
2114 {
2115         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2116                 return;
2117         __mcheck_cpu_init_generic();
2118         __mcheck_cpu_init_clear_banks();
2119         __mcheck_cpu_init_timer();
2120 }
2121
2122 /* Reinit MCEs after user configuration changes */
2123 static void mce_restart(void)
2124 {
2125         mce_timer_delete_all();
2126         on_each_cpu(mce_cpu_restart, NULL, 1);
2127 }
2128
2129 /* Toggle features for corrected errors */
2130 static void mce_disable_cmci(void *data)
2131 {
2132         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2133                 return;
2134         cmci_clear();
2135 }
2136
2137 static void mce_enable_ce(void *all)
2138 {
2139         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2140                 return;
2141         cmci_reenable();
2142         cmci_recheck();
2143         if (all)
2144                 __mcheck_cpu_init_timer();
2145 }
2146
2147 static struct bus_type mce_subsys = {
2148         .name           = "machinecheck",
2149         .dev_name       = "machinecheck",
2150 };
2151
2152 DEFINE_PER_CPU(struct device *, mce_device);
2153
2154 static inline struct mce_bank_dev *attr_to_bank(struct device_attribute *attr)
2155 {
2156         return container_of(attr, struct mce_bank_dev, attr);
2157 }
2158
2159 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2160                          char *buf)
2161 {
2162         u8 bank = attr_to_bank(attr)->bank;
2163         struct mce_bank *b;
2164
2165         if (bank >= per_cpu(mce_num_banks, s->id))
2166                 return -EINVAL;
2167
2168         b = &per_cpu(mce_banks_array, s->id)[bank];
2169
2170         if (!b->init)
2171                 return -ENODEV;
2172
2173         return sprintf(buf, "%llx\n", b->ctl);
2174 }
2175
2176 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2177                         const char *buf, size_t size)
2178 {
2179         u8 bank = attr_to_bank(attr)->bank;
2180         struct mce_bank *b;
2181         u64 new;
2182
2183         if (kstrtou64(buf, 0, &new) < 0)
2184                 return -EINVAL;
2185
2186         if (bank >= per_cpu(mce_num_banks, s->id))
2187                 return -EINVAL;
2188
2189         b = &per_cpu(mce_banks_array, s->id)[bank];
2190
2191         if (!b->init)
2192                 return -ENODEV;
2193
2194         b->ctl = new;
2195         mce_restart();
2196
2197         return size;
2198 }
2199
2200 static ssize_t set_ignore_ce(struct device *s,
2201                              struct device_attribute *attr,
2202                              const char *buf, size_t size)
2203 {
2204         u64 new;
2205
2206         if (kstrtou64(buf, 0, &new) < 0)
2207                 return -EINVAL;
2208
2209         mutex_lock(&mce_sysfs_mutex);
2210         if (mca_cfg.ignore_ce ^ !!new) {
2211                 if (new) {
2212                         /* disable ce features */
2213                         mce_timer_delete_all();
2214                         on_each_cpu(mce_disable_cmci, NULL, 1);
2215                         mca_cfg.ignore_ce = true;
2216                 } else {
2217                         /* enable ce features */
2218                         mca_cfg.ignore_ce = false;
2219                         on_each_cpu(mce_enable_ce, (void *)1, 1);
2220                 }
2221         }
2222         mutex_unlock(&mce_sysfs_mutex);
2223
2224         return size;
2225 }
2226
2227 static ssize_t set_cmci_disabled(struct device *s,
2228                                  struct device_attribute *attr,
2229                                  const char *buf, size_t size)
2230 {
2231         u64 new;
2232
2233         if (kstrtou64(buf, 0, &new) < 0)
2234                 return -EINVAL;
2235
2236         mutex_lock(&mce_sysfs_mutex);
2237         if (mca_cfg.cmci_disabled ^ !!new) {
2238                 if (new) {
2239                         /* disable cmci */
2240                         on_each_cpu(mce_disable_cmci, NULL, 1);
2241                         mca_cfg.cmci_disabled = true;
2242                 } else {
2243                         /* enable cmci */
2244                         mca_cfg.cmci_disabled = false;
2245                         on_each_cpu(mce_enable_ce, NULL, 1);
2246                 }
2247         }
2248         mutex_unlock(&mce_sysfs_mutex);
2249
2250         return size;
2251 }
2252
2253 static ssize_t store_int_with_restart(struct device *s,
2254                                       struct device_attribute *attr,
2255                                       const char *buf, size_t size)
2256 {
2257         unsigned long old_check_interval = check_interval;
2258         ssize_t ret = device_store_ulong(s, attr, buf, size);
2259
2260         if (check_interval == old_check_interval)
2261                 return ret;
2262
2263         mutex_lock(&mce_sysfs_mutex);
2264         mce_restart();
2265         mutex_unlock(&mce_sysfs_mutex);
2266
2267         return ret;
2268 }
2269
2270 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2271 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2272 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2273 static DEVICE_BOOL_ATTR(print_all, 0644, mca_cfg.print_all);
2274
2275 static struct dev_ext_attribute dev_attr_check_interval = {
2276         __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2277         &check_interval
2278 };
2279
2280 static struct dev_ext_attribute dev_attr_ignore_ce = {
2281         __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2282         &mca_cfg.ignore_ce
2283 };
2284
2285 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2286         __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2287         &mca_cfg.cmci_disabled
2288 };
2289
2290 static struct device_attribute *mce_device_attrs[] = {
2291         &dev_attr_tolerant.attr,
2292         &dev_attr_check_interval.attr,
2293 #ifdef CONFIG_X86_MCELOG_LEGACY
2294         &dev_attr_trigger,
2295 #endif
2296         &dev_attr_monarch_timeout.attr,
2297         &dev_attr_dont_log_ce.attr,
2298         &dev_attr_print_all.attr,
2299         &dev_attr_ignore_ce.attr,
2300         &dev_attr_cmci_disabled.attr,
2301         NULL
2302 };
2303
2304 static cpumask_var_t mce_device_initialized;
2305
2306 static void mce_device_release(struct device *dev)
2307 {
2308         kfree(dev);
2309 }
2310
2311 /* Per CPU device init. All of the CPUs still share the same bank device: */
2312 static int mce_device_create(unsigned int cpu)
2313 {
2314         struct device *dev;
2315         int err;
2316         int i, j;
2317
2318         if (!mce_available(&boot_cpu_data))
2319                 return -EIO;
2320
2321         dev = per_cpu(mce_device, cpu);
2322         if (dev)
2323                 return 0;
2324
2325         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2326         if (!dev)
2327                 return -ENOMEM;
2328         dev->id  = cpu;
2329         dev->bus = &mce_subsys;
2330         dev->release = &mce_device_release;
2331
2332         err = device_register(dev);
2333         if (err) {
2334                 put_device(dev);
2335                 return err;
2336         }
2337
2338         for (i = 0; mce_device_attrs[i]; i++) {
2339                 err = device_create_file(dev, mce_device_attrs[i]);
2340                 if (err)
2341                         goto error;
2342         }
2343         for (j = 0; j < per_cpu(mce_num_banks, cpu); j++) {
2344                 err = device_create_file(dev, &mce_bank_devs[j].attr);
2345                 if (err)
2346                         goto error2;
2347         }
2348         cpumask_set_cpu(cpu, mce_device_initialized);
2349         per_cpu(mce_device, cpu) = dev;
2350
2351         return 0;
2352 error2:
2353         while (--j >= 0)
2354                 device_remove_file(dev, &mce_bank_devs[j].attr);
2355 error:
2356         while (--i >= 0)
2357                 device_remove_file(dev, mce_device_attrs[i]);
2358
2359         device_unregister(dev);
2360
2361         return err;
2362 }
2363
2364 static void mce_device_remove(unsigned int cpu)
2365 {
2366         struct device *dev = per_cpu(mce_device, cpu);
2367         int i;
2368
2369         if (!cpumask_test_cpu(cpu, mce_device_initialized))
2370                 return;
2371
2372         for (i = 0; mce_device_attrs[i]; i++)
2373                 device_remove_file(dev, mce_device_attrs[i]);
2374
2375         for (i = 0; i < per_cpu(mce_num_banks, cpu); i++)
2376                 device_remove_file(dev, &mce_bank_devs[i].attr);
2377
2378         device_unregister(dev);
2379         cpumask_clear_cpu(cpu, mce_device_initialized);
2380         per_cpu(mce_device, cpu) = NULL;
2381 }
2382
2383 /* Make sure there are no machine checks on offlined CPUs. */
2384 static void mce_disable_cpu(void)
2385 {
2386         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2387                 return;
2388
2389         if (!cpuhp_tasks_frozen)
2390                 cmci_clear();
2391
2392         vendor_disable_error_reporting();
2393 }
2394
2395 static void mce_reenable_cpu(void)
2396 {
2397         struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2398         int i;
2399
2400         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2401                 return;
2402
2403         if (!cpuhp_tasks_frozen)
2404                 cmci_reenable();
2405         for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2406                 struct mce_bank *b = &mce_banks[i];
2407
2408                 if (b->init)
2409                         wrmsrl(msr_ops.ctl(i), b->ctl);
2410         }
2411 }
2412
2413 static int mce_cpu_dead(unsigned int cpu)
2414 {
2415         mce_intel_hcpu_update(cpu);
2416
2417         /* intentionally ignoring frozen here */
2418         if (!cpuhp_tasks_frozen)
2419                 cmci_rediscover();
2420         return 0;
2421 }
2422
2423 static int mce_cpu_online(unsigned int cpu)
2424 {
2425         struct timer_list *t = this_cpu_ptr(&mce_timer);
2426         int ret;
2427
2428         mce_device_create(cpu);
2429
2430         ret = mce_threshold_create_device(cpu);
2431         if (ret) {
2432                 mce_device_remove(cpu);
2433                 return ret;
2434         }
2435         mce_reenable_cpu();
2436         mce_start_timer(t);
2437         return 0;
2438 }
2439
2440 static int mce_cpu_pre_down(unsigned int cpu)
2441 {
2442         struct timer_list *t = this_cpu_ptr(&mce_timer);
2443
2444         mce_disable_cpu();
2445         del_timer_sync(t);
2446         mce_threshold_remove_device(cpu);
2447         mce_device_remove(cpu);
2448         return 0;
2449 }
2450
2451 static __init void mce_init_banks(void)
2452 {
2453         int i;
2454
2455         for (i = 0; i < MAX_NR_BANKS; i++) {
2456                 struct mce_bank_dev *b = &mce_bank_devs[i];
2457                 struct device_attribute *a = &b->attr;
2458
2459                 b->bank = i;
2460
2461                 sysfs_attr_init(&a->attr);
2462                 a->attr.name    = b->attrname;
2463                 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2464
2465                 a->attr.mode    = 0644;
2466                 a->show         = show_bank;
2467                 a->store        = set_bank;
2468         }
2469 }
2470
2471 /*
2472  * When running on XEN, this initcall is ordered against the XEN mcelog
2473  * initcall:
2474  *
2475  *   device_initcall(xen_late_init_mcelog);
2476  *   device_initcall_sync(mcheck_init_device);
2477  */
2478 static __init int mcheck_init_device(void)
2479 {
2480         int err;
2481
2482         /*
2483          * Check if we have a spare virtual bit. This will only become
2484          * a problem if/when we move beyond 5-level page tables.
2485          */
2486         MAYBE_BUILD_BUG_ON(__VIRTUAL_MASK_SHIFT >= 63);
2487
2488         if (!mce_available(&boot_cpu_data)) {
2489                 err = -EIO;
2490                 goto err_out;
2491         }
2492
2493         if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2494                 err = -ENOMEM;
2495                 goto err_out;
2496         }
2497
2498         mce_init_banks();
2499
2500         err = subsys_system_register(&mce_subsys, NULL);
2501         if (err)
2502                 goto err_out_mem;
2503
2504         err = cpuhp_setup_state(CPUHP_X86_MCE_DEAD, "x86/mce:dead", NULL,
2505                                 mce_cpu_dead);
2506         if (err)
2507                 goto err_out_mem;
2508
2509         /*
2510          * Invokes mce_cpu_online() on all CPUs which are online when
2511          * the state is installed.
2512          */
2513         err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/mce:online",
2514                                 mce_cpu_online, mce_cpu_pre_down);
2515         if (err < 0)
2516                 goto err_out_online;
2517
2518         register_syscore_ops(&mce_syscore_ops);
2519
2520         return 0;
2521
2522 err_out_online:
2523         cpuhp_remove_state(CPUHP_X86_MCE_DEAD);
2524
2525 err_out_mem:
2526         free_cpumask_var(mce_device_initialized);
2527
2528 err_out:
2529         pr_err("Unable to init MCE device (rc: %d)\n", err);
2530
2531         return err;
2532 }
2533 device_initcall_sync(mcheck_init_device);
2534
2535 /*
2536  * Old style boot options parsing. Only for compatibility.
2537  */
2538 static int __init mcheck_disable(char *str)
2539 {
2540         mca_cfg.disabled = 1;
2541         return 1;
2542 }
2543 __setup("nomce", mcheck_disable);
2544
2545 #ifdef CONFIG_DEBUG_FS
2546 struct dentry *mce_get_debugfs_dir(void)
2547 {
2548         static struct dentry *dmce;
2549
2550         if (!dmce)
2551                 dmce = debugfs_create_dir("mce", NULL);
2552
2553         return dmce;
2554 }
2555
2556 static void mce_reset(void)
2557 {
2558         cpu_missing = 0;
2559         atomic_set(&mce_fake_panicked, 0);
2560         atomic_set(&mce_executing, 0);
2561         atomic_set(&mce_callin, 0);
2562         atomic_set(&global_nwo, 0);
2563 }
2564
2565 static int fake_panic_get(void *data, u64 *val)
2566 {
2567         *val = fake_panic;
2568         return 0;
2569 }
2570
2571 static int fake_panic_set(void *data, u64 val)
2572 {
2573         mce_reset();
2574         fake_panic = val;
2575         return 0;
2576 }
2577
2578 DEFINE_DEBUGFS_ATTRIBUTE(fake_panic_fops, fake_panic_get, fake_panic_set,
2579                          "%llu\n");
2580
2581 static void __init mcheck_debugfs_init(void)
2582 {
2583         struct dentry *dmce;
2584
2585         dmce = mce_get_debugfs_dir();
2586         debugfs_create_file_unsafe("fake_panic", 0444, dmce, NULL,
2587                                    &fake_panic_fops);
2588 }
2589 #else
2590 static void __init mcheck_debugfs_init(void) { }
2591 #endif
2592
2593 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2594 EXPORT_SYMBOL_GPL(mcsafe_key);
2595
2596 static int __init mcheck_late_init(void)
2597 {
2598         if (mca_cfg.recovery)
2599                 static_branch_inc(&mcsafe_key);
2600
2601         mcheck_debugfs_init();
2602
2603         /*
2604          * Flush out everything that has been logged during early boot, now that
2605          * everything has been initialized (workqueues, decoders, ...).
2606          */
2607         mce_schedule_work();
2608
2609         return 0;
2610 }
2611 late_initcall(mcheck_late_init);