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