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