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