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