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