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