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