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