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