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