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