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