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