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