]> git.karo-electronics.de Git - mv-sheeva.git/blob - arch/x86/kernel/cpu/mcheck/mce.c
2f1c200f05e6d1fee22f17c07957617e2e3d6034
[mv-sheeva.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  * The actual machine check handler. This only handles real
891  * exceptions when something got corrupted coming in through int 18.
892  *
893  * This is executed in NMI context not subject to normal locking rules. This
894  * implies that most kernel services cannot be safely used. Don't even
895  * think about putting a printk in there!
896  *
897  * On Intel systems this is entered on all CPUs in parallel through
898  * MCE broadcast. However some CPUs might be broken beyond repair,
899  * so be always careful when synchronizing with others.
900  */
901 void do_machine_check(struct pt_regs *regs, long error_code)
902 {
903         struct mce m, *final;
904         int i;
905         int worst = 0;
906         int severity;
907         /*
908          * Establish sequential order between the CPUs entering the machine
909          * check handler.
910          */
911         int order;
912         /*
913          * If no_way_out gets set, there is no safe way to recover from this
914          * MCE.  If tolerant is cranked up, we'll try anyway.
915          */
916         int no_way_out = 0;
917         /*
918          * If kill_it gets set, there might be a way to recover from this
919          * error.
920          */
921         int kill_it = 0;
922         DECLARE_BITMAP(toclear, MAX_NR_BANKS);
923         char *msg = "Unknown";
924
925         atomic_inc(&mce_entry);
926
927         percpu_inc(mce_exception_count);
928
929         if (!banks)
930                 goto out;
931
932         mce_gather_info(&m, regs);
933
934         final = &__get_cpu_var(mces_seen);
935         *final = m;
936
937         no_way_out = mce_no_way_out(&m, &msg);
938
939         barrier();
940
941         /*
942          * When no restart IP must always kill or panic.
943          */
944         if (!(m.mcgstatus & MCG_STATUS_RIPV))
945                 kill_it = 1;
946
947         /*
948          * Go through all the banks in exclusion of the other CPUs.
949          * This way we don't report duplicated events on shared banks
950          * because the first one to see it will clear it.
951          */
952         order = mce_start(&no_way_out);
953         for (i = 0; i < banks; i++) {
954                 __clear_bit(i, toclear);
955                 if (!mce_banks[i].ctl)
956                         continue;
957
958                 m.misc = 0;
959                 m.addr = 0;
960                 m.bank = i;
961
962                 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
963                 if ((m.status & MCI_STATUS_VAL) == 0)
964                         continue;
965
966                 /*
967                  * Non uncorrected or non signaled errors are handled by
968                  * machine_check_poll. Leave them alone, unless this panics.
969                  */
970                 if (!(m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
971                         !no_way_out)
972                         continue;
973
974                 /*
975                  * Set taint even when machine check was not enabled.
976                  */
977                 add_taint(TAINT_MACHINE_CHECK);
978
979                 severity = mce_severity(&m, tolerant, NULL);
980
981                 /*
982                  * When machine check was for corrected handler don't touch,
983                  * unless we're panicing.
984                  */
985                 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
986                         continue;
987                 __set_bit(i, toclear);
988                 if (severity == MCE_NO_SEVERITY) {
989                         /*
990                          * Machine check event was not enabled. Clear, but
991                          * ignore.
992                          */
993                         continue;
994                 }
995
996                 /*
997                  * Kill on action required.
998                  */
999                 if (severity == MCE_AR_SEVERITY)
1000                         kill_it = 1;
1001
1002                 mce_read_aux(&m, i);
1003
1004                 /*
1005                  * Action optional error. Queue address for later processing.
1006                  * When the ring overflows we just ignore the AO error.
1007                  * RED-PEN add some logging mechanism when
1008                  * usable_address or mce_add_ring fails.
1009                  * RED-PEN don't ignore overflow for tolerant == 0
1010                  */
1011                 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1012                         mce_ring_add(m.addr >> PAGE_SHIFT);
1013
1014                 mce_log(&m);
1015
1016                 if (severity > worst) {
1017                         *final = m;
1018                         worst = severity;
1019                 }
1020         }
1021
1022         if (!no_way_out)
1023                 mce_clear_state(toclear);
1024
1025         /*
1026          * Do most of the synchronization with other CPUs.
1027          * When there's any problem use only local no_way_out state.
1028          */
1029         if (mce_end(order) < 0)
1030                 no_way_out = worst >= MCE_PANIC_SEVERITY;
1031
1032         /*
1033          * If we have decided that we just CAN'T continue, and the user
1034          * has not set tolerant to an insane level, give up and die.
1035          *
1036          * This is mainly used in the case when the system doesn't
1037          * support MCE broadcasting or it has been disabled.
1038          */
1039         if (no_way_out && tolerant < 3)
1040                 mce_panic("Fatal machine check on current CPU", final, msg);
1041
1042         /*
1043          * If the error seems to be unrecoverable, something should be
1044          * done.  Try to kill as little as possible.  If we can kill just
1045          * one task, do that.  If the user has set the tolerance very
1046          * high, don't try to do anything at all.
1047          */
1048
1049         if (kill_it && tolerant < 3)
1050                 force_sig(SIGBUS, current);
1051
1052         /* notify userspace ASAP */
1053         set_thread_flag(TIF_MCE_NOTIFY);
1054
1055         if (worst > 0)
1056                 mce_report_event(regs);
1057         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1058 out:
1059         atomic_dec(&mce_entry);
1060         sync_core();
1061 }
1062 EXPORT_SYMBOL_GPL(do_machine_check);
1063
1064 #ifndef CONFIG_MEMORY_FAILURE
1065 int memory_failure(unsigned long pfn, int vector, int flags)
1066 {
1067         printk(KERN_ERR "Uncorrected memory error in page 0x%lx ignored\n"
1068                 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n", pfn);
1069
1070         return 0;
1071 }
1072 #endif
1073
1074 /*
1075  * Called after mce notification in process context. This code
1076  * is allowed to sleep. Call the high level VM handler to process
1077  * any corrupted pages.
1078  * Assume that the work queue code only calls this one at a time
1079  * per CPU.
1080  * Note we don't disable preemption, so this code might run on the wrong
1081  * CPU. In this case the event is picked up by the scheduled work queue.
1082  * This is merely a fast path to expedite processing in some common
1083  * cases.
1084  */
1085 void mce_notify_process(void)
1086 {
1087         unsigned long pfn;
1088         mce_notify_irq();
1089         while (mce_ring_get(&pfn))
1090                 memory_failure(pfn, MCE_VECTOR, 0);
1091 }
1092
1093 static void mce_process_work(struct work_struct *dummy)
1094 {
1095         mce_notify_process();
1096 }
1097
1098 #ifdef CONFIG_X86_MCE_INTEL
1099 /***
1100  * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1101  * @cpu: The CPU on which the event occurred.
1102  * @status: Event status information
1103  *
1104  * This function should be called by the thermal interrupt after the
1105  * event has been processed and the decision was made to log the event
1106  * further.
1107  *
1108  * The status parameter will be saved to the 'status' field of 'struct mce'
1109  * and historically has been the register value of the
1110  * MSR_IA32_THERMAL_STATUS (Intel) msr.
1111  */
1112 void mce_log_therm_throt_event(__u64 status)
1113 {
1114         struct mce m;
1115
1116         mce_setup(&m);
1117         m.bank = MCE_THERMAL_BANK;
1118         m.status = status;
1119         mce_log(&m);
1120 }
1121 #endif /* CONFIG_X86_MCE_INTEL */
1122
1123 /*
1124  * Periodic polling timer for "silent" machine check errors.  If the
1125  * poller finds an MCE, poll 2x faster.  When the poller finds no more
1126  * errors, poll 2x slower (up to check_interval seconds).
1127  */
1128 static int check_interval = 5 * 60; /* 5 minutes */
1129
1130 static DEFINE_PER_CPU(int, mce_next_interval); /* in jiffies */
1131 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1132
1133 static void mce_start_timer(unsigned long data)
1134 {
1135         struct timer_list *t = &per_cpu(mce_timer, data);
1136         int *n;
1137
1138         WARN_ON(smp_processor_id() != data);
1139
1140         if (mce_available(__this_cpu_ptr(&cpu_info))) {
1141                 machine_check_poll(MCP_TIMESTAMP,
1142                                 &__get_cpu_var(mce_poll_banks));
1143         }
1144
1145         /*
1146          * Alert userspace if needed.  If we logged an MCE, reduce the
1147          * polling interval, otherwise increase the polling interval.
1148          */
1149         n = &__get_cpu_var(mce_next_interval);
1150         if (mce_notify_irq())
1151                 *n = max(*n/2, HZ/100);
1152         else
1153                 *n = min(*n*2, (int)round_jiffies_relative(check_interval*HZ));
1154
1155         t->expires = jiffies + *n;
1156         add_timer_on(t, smp_processor_id());
1157 }
1158
1159 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1160 static void mce_timer_delete_all(void)
1161 {
1162         int cpu;
1163
1164         for_each_online_cpu(cpu)
1165                 del_timer_sync(&per_cpu(mce_timer, cpu));
1166 }
1167
1168 static void mce_do_trigger(struct work_struct *work)
1169 {
1170         call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1171 }
1172
1173 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1174
1175 /*
1176  * Notify the user(s) about new machine check events.
1177  * Can be called from interrupt context, but not from machine check/NMI
1178  * context.
1179  */
1180 int mce_notify_irq(void)
1181 {
1182         /* Not more than two messages every minute */
1183         static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1184
1185         clear_thread_flag(TIF_MCE_NOTIFY);
1186
1187         if (test_and_clear_bit(0, &mce_need_notify)) {
1188                 /* wake processes polling /dev/mcelog */
1189                 wake_up_interruptible(&mce_chrdev_wait);
1190
1191                 /*
1192                  * There is no risk of missing notifications because
1193                  * work_pending is always cleared before the function is
1194                  * executed.
1195                  */
1196                 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1197                         schedule_work(&mce_trigger_work);
1198
1199                 if (__ratelimit(&ratelimit))
1200                         pr_info(HW_ERR "Machine check events logged\n");
1201
1202                 return 1;
1203         }
1204         return 0;
1205 }
1206 EXPORT_SYMBOL_GPL(mce_notify_irq);
1207
1208 static int __cpuinit __mcheck_cpu_mce_banks_init(void)
1209 {
1210         int i;
1211
1212         mce_banks = kzalloc(banks * sizeof(struct mce_bank), GFP_KERNEL);
1213         if (!mce_banks)
1214                 return -ENOMEM;
1215         for (i = 0; i < banks; i++) {
1216                 struct mce_bank *b = &mce_banks[i];
1217
1218                 b->ctl = -1ULL;
1219                 b->init = 1;
1220         }
1221         return 0;
1222 }
1223
1224 /*
1225  * Initialize Machine Checks for a CPU.
1226  */
1227 static int __cpuinit __mcheck_cpu_cap_init(void)
1228 {
1229         unsigned b;
1230         u64 cap;
1231
1232         rdmsrl(MSR_IA32_MCG_CAP, cap);
1233
1234         b = cap & MCG_BANKCNT_MASK;
1235         if (!banks)
1236                 printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
1237
1238         if (b > MAX_NR_BANKS) {
1239                 printk(KERN_WARNING
1240                        "MCE: Using only %u machine check banks out of %u\n",
1241                         MAX_NR_BANKS, b);
1242                 b = MAX_NR_BANKS;
1243         }
1244
1245         /* Don't support asymmetric configurations today */
1246         WARN_ON(banks != 0 && b != banks);
1247         banks = b;
1248         if (!mce_banks) {
1249                 int err = __mcheck_cpu_mce_banks_init();
1250
1251                 if (err)
1252                         return err;
1253         }
1254
1255         /* Use accurate RIP reporting if available. */
1256         if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1257                 rip_msr = MSR_IA32_MCG_EIP;
1258
1259         if (cap & MCG_SER_P)
1260                 mce_ser = 1;
1261
1262         return 0;
1263 }
1264
1265 static void __mcheck_cpu_init_generic(void)
1266 {
1267         mce_banks_t all_banks;
1268         u64 cap;
1269         int i;
1270
1271         /*
1272          * Log the machine checks left over from the previous reset.
1273          */
1274         bitmap_fill(all_banks, MAX_NR_BANKS);
1275         machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
1276
1277         set_in_cr4(X86_CR4_MCE);
1278
1279         rdmsrl(MSR_IA32_MCG_CAP, cap);
1280         if (cap & MCG_CTL_P)
1281                 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1282
1283         for (i = 0; i < banks; i++) {
1284                 struct mce_bank *b = &mce_banks[i];
1285
1286                 if (!b->init)
1287                         continue;
1288                 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1289                 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1290         }
1291 }
1292
1293 /* Add per CPU specific workarounds here */
1294 static int __cpuinit __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1295 {
1296         if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1297                 pr_info("MCE: unknown CPU type - not enabling MCE support.\n");
1298                 return -EOPNOTSUPP;
1299         }
1300
1301         /* This should be disabled by the BIOS, but isn't always */
1302         if (c->x86_vendor == X86_VENDOR_AMD) {
1303                 if (c->x86 == 15 && banks > 4) {
1304                         /*
1305                          * disable GART TBL walk error reporting, which
1306                          * trips off incorrectly with the IOMMU & 3ware
1307                          * & Cerberus:
1308                          */
1309                         clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1310                 }
1311                 if (c->x86 <= 17 && mce_bootlog < 0) {
1312                         /*
1313                          * Lots of broken BIOS around that don't clear them
1314                          * by default and leave crap in there. Don't log:
1315                          */
1316                         mce_bootlog = 0;
1317                 }
1318                 /*
1319                  * Various K7s with broken bank 0 around. Always disable
1320                  * by default.
1321                  */
1322                  if (c->x86 == 6 && banks > 0)
1323                         mce_banks[0].ctl = 0;
1324         }
1325
1326         if (c->x86_vendor == X86_VENDOR_INTEL) {
1327                 /*
1328                  * SDM documents that on family 6 bank 0 should not be written
1329                  * because it aliases to another special BIOS controlled
1330                  * register.
1331                  * But it's not aliased anymore on model 0x1a+
1332                  * Don't ignore bank 0 completely because there could be a
1333                  * valid event later, merely don't write CTL0.
1334                  */
1335
1336                 if (c->x86 == 6 && c->x86_model < 0x1A && banks > 0)
1337                         mce_banks[0].init = 0;
1338
1339                 /*
1340                  * All newer Intel systems support MCE broadcasting. Enable
1341                  * synchronization with a one second timeout.
1342                  */
1343                 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1344                         monarch_timeout < 0)
1345                         monarch_timeout = USEC_PER_SEC;
1346
1347                 /*
1348                  * There are also broken BIOSes on some Pentium M and
1349                  * earlier systems:
1350                  */
1351                 if (c->x86 == 6 && c->x86_model <= 13 && mce_bootlog < 0)
1352                         mce_bootlog = 0;
1353         }
1354         if (monarch_timeout < 0)
1355                 monarch_timeout = 0;
1356         if (mce_bootlog != 0)
1357                 mce_panic_timeout = 30;
1358
1359         return 0;
1360 }
1361
1362 static int __cpuinit __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1363 {
1364         if (c->x86 != 5)
1365                 return 0;
1366
1367         switch (c->x86_vendor) {
1368         case X86_VENDOR_INTEL:
1369                 intel_p5_mcheck_init(c);
1370                 return 1;
1371                 break;
1372         case X86_VENDOR_CENTAUR:
1373                 winchip_mcheck_init(c);
1374                 return 1;
1375                 break;
1376         }
1377
1378         return 0;
1379 }
1380
1381 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1382 {
1383         switch (c->x86_vendor) {
1384         case X86_VENDOR_INTEL:
1385                 mce_intel_feature_init(c);
1386                 break;
1387         case X86_VENDOR_AMD:
1388                 mce_amd_feature_init(c);
1389                 break;
1390         default:
1391                 break;
1392         }
1393 }
1394
1395 static void __mcheck_cpu_init_timer(void)
1396 {
1397         struct timer_list *t = &__get_cpu_var(mce_timer);
1398         int *n = &__get_cpu_var(mce_next_interval);
1399
1400         setup_timer(t, mce_start_timer, smp_processor_id());
1401
1402         if (mce_ignore_ce)
1403                 return;
1404
1405         *n = check_interval * HZ;
1406         if (!*n)
1407                 return;
1408         t->expires = round_jiffies(jiffies + *n);
1409         add_timer_on(t, smp_processor_id());
1410 }
1411
1412 /* Handle unconfigured int18 (should never happen) */
1413 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1414 {
1415         printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
1416                smp_processor_id());
1417 }
1418
1419 /* Call the installed machine check handler for this CPU setup. */
1420 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1421                                                 unexpected_machine_check;
1422
1423 /*
1424  * Called for each booted CPU to set up machine checks.
1425  * Must be called with preempt off:
1426  */
1427 void __cpuinit mcheck_cpu_init(struct cpuinfo_x86 *c)
1428 {
1429         if (mce_disabled)
1430                 return;
1431
1432         if (__mcheck_cpu_ancient_init(c))
1433                 return;
1434
1435         if (!mce_available(c))
1436                 return;
1437
1438         if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1439                 mce_disabled = 1;
1440                 return;
1441         }
1442
1443         machine_check_vector = do_machine_check;
1444
1445         __mcheck_cpu_init_generic();
1446         __mcheck_cpu_init_vendor(c);
1447         __mcheck_cpu_init_timer();
1448         INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1449         init_irq_work(&__get_cpu_var(mce_irq_work), &mce_irq_work_cb);
1450 }
1451
1452 /*
1453  * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1454  */
1455
1456 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1457 static int mce_chrdev_open_count;       /* #times opened */
1458 static int mce_chrdev_open_exclu;       /* already open exclusive? */
1459
1460 static int mce_chrdev_open(struct inode *inode, struct file *file)
1461 {
1462         spin_lock(&mce_chrdev_state_lock);
1463
1464         if (mce_chrdev_open_exclu ||
1465             (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1466                 spin_unlock(&mce_chrdev_state_lock);
1467
1468                 return -EBUSY;
1469         }
1470
1471         if (file->f_flags & O_EXCL)
1472                 mce_chrdev_open_exclu = 1;
1473         mce_chrdev_open_count++;
1474
1475         spin_unlock(&mce_chrdev_state_lock);
1476
1477         return nonseekable_open(inode, file);
1478 }
1479
1480 static int mce_chrdev_release(struct inode *inode, struct file *file)
1481 {
1482         spin_lock(&mce_chrdev_state_lock);
1483
1484         mce_chrdev_open_count--;
1485         mce_chrdev_open_exclu = 0;
1486
1487         spin_unlock(&mce_chrdev_state_lock);
1488
1489         return 0;
1490 }
1491
1492 static void collect_tscs(void *data)
1493 {
1494         unsigned long *cpu_tsc = (unsigned long *)data;
1495
1496         rdtscll(cpu_tsc[smp_processor_id()]);
1497 }
1498
1499 static int mce_apei_read_done;
1500
1501 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1502 static int __mce_read_apei(char __user **ubuf, size_t usize)
1503 {
1504         int rc;
1505         u64 record_id;
1506         struct mce m;
1507
1508         if (usize < sizeof(struct mce))
1509                 return -EINVAL;
1510
1511         rc = apei_read_mce(&m, &record_id);
1512         /* Error or no more MCE record */
1513         if (rc <= 0) {
1514                 mce_apei_read_done = 1;
1515                 return rc;
1516         }
1517         rc = -EFAULT;
1518         if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1519                 return rc;
1520         /*
1521          * In fact, we should have cleared the record after that has
1522          * been flushed to the disk or sent to network in
1523          * /sbin/mcelog, but we have no interface to support that now,
1524          * so just clear it to avoid duplication.
1525          */
1526         rc = apei_clear_mce(record_id);
1527         if (rc) {
1528                 mce_apei_read_done = 1;
1529                 return rc;
1530         }
1531         *ubuf += sizeof(struct mce);
1532
1533         return 0;
1534 }
1535
1536 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1537                                 size_t usize, loff_t *off)
1538 {
1539         char __user *buf = ubuf;
1540         unsigned long *cpu_tsc;
1541         unsigned prev, next;
1542         int i, err;
1543
1544         cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1545         if (!cpu_tsc)
1546                 return -ENOMEM;
1547
1548         mutex_lock(&mce_chrdev_read_mutex);
1549
1550         if (!mce_apei_read_done) {
1551                 err = __mce_read_apei(&buf, usize);
1552                 if (err || buf != ubuf)
1553                         goto out;
1554         }
1555
1556         next = rcu_dereference_check_mce(mcelog.next);
1557
1558         /* Only supports full reads right now */
1559         err = -EINVAL;
1560         if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1561                 goto out;
1562
1563         err = 0;
1564         prev = 0;
1565         do {
1566                 for (i = prev; i < next; i++) {
1567                         unsigned long start = jiffies;
1568                         struct mce *m = &mcelog.entry[i];
1569
1570                         while (!m->finished) {
1571                                 if (time_after_eq(jiffies, start + 2)) {
1572                                         memset(m, 0, sizeof(*m));
1573                                         goto timeout;
1574                                 }
1575                                 cpu_relax();
1576                         }
1577                         smp_rmb();
1578                         err |= copy_to_user(buf, m, sizeof(*m));
1579                         buf += sizeof(*m);
1580 timeout:
1581                         ;
1582                 }
1583
1584                 memset(mcelog.entry + prev, 0,
1585                        (next - prev) * sizeof(struct mce));
1586                 prev = next;
1587                 next = cmpxchg(&mcelog.next, prev, 0);
1588         } while (next != prev);
1589
1590         synchronize_sched();
1591
1592         /*
1593          * Collect entries that were still getting written before the
1594          * synchronize.
1595          */
1596         on_each_cpu(collect_tscs, cpu_tsc, 1);
1597
1598         for (i = next; i < MCE_LOG_LEN; i++) {
1599                 struct mce *m = &mcelog.entry[i];
1600
1601                 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1602                         err |= copy_to_user(buf, m, sizeof(*m));
1603                         smp_rmb();
1604                         buf += sizeof(*m);
1605                         memset(m, 0, sizeof(*m));
1606                 }
1607         }
1608
1609         if (err)
1610                 err = -EFAULT;
1611
1612 out:
1613         mutex_unlock(&mce_chrdev_read_mutex);
1614         kfree(cpu_tsc);
1615
1616         return err ? err : buf - ubuf;
1617 }
1618
1619 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1620 {
1621         poll_wait(file, &mce_chrdev_wait, wait);
1622         if (rcu_access_index(mcelog.next))
1623                 return POLLIN | POLLRDNORM;
1624         if (!mce_apei_read_done && apei_check_mce())
1625                 return POLLIN | POLLRDNORM;
1626         return 0;
1627 }
1628
1629 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1630                                 unsigned long arg)
1631 {
1632         int __user *p = (int __user *)arg;
1633
1634         if (!capable(CAP_SYS_ADMIN))
1635                 return -EPERM;
1636
1637         switch (cmd) {
1638         case MCE_GET_RECORD_LEN:
1639                 return put_user(sizeof(struct mce), p);
1640         case MCE_GET_LOG_LEN:
1641                 return put_user(MCE_LOG_LEN, p);
1642         case MCE_GETCLEAR_FLAGS: {
1643                 unsigned flags;
1644
1645                 do {
1646                         flags = mcelog.flags;
1647                 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1648
1649                 return put_user(flags, p);
1650         }
1651         default:
1652                 return -ENOTTY;
1653         }
1654 }
1655
1656 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1657                             size_t usize, loff_t *off);
1658
1659 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1660                              const char __user *ubuf,
1661                              size_t usize, loff_t *off))
1662 {
1663         mce_write = fn;
1664 }
1665 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1666
1667 ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1668                          size_t usize, loff_t *off)
1669 {
1670         if (mce_write)
1671                 return mce_write(filp, ubuf, usize, off);
1672         else
1673                 return -EINVAL;
1674 }
1675
1676 static const struct file_operations mce_chrdev_ops = {
1677         .open                   = mce_chrdev_open,
1678         .release                = mce_chrdev_release,
1679         .read                   = mce_chrdev_read,
1680         .write                  = mce_chrdev_write,
1681         .poll                   = mce_chrdev_poll,
1682         .unlocked_ioctl         = mce_chrdev_ioctl,
1683         .llseek                 = no_llseek,
1684 };
1685
1686 static struct miscdevice mce_chrdev_device = {
1687         MISC_MCELOG_MINOR,
1688         "mcelog",
1689         &mce_chrdev_ops,
1690 };
1691
1692 /*
1693  * mce=off Disables machine check
1694  * mce=no_cmci Disables CMCI
1695  * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1696  * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1697  * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1698  *      monarchtimeout is how long to wait for other CPUs on machine
1699  *      check, or 0 to not wait
1700  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1701  * mce=nobootlog Don't log MCEs from before booting.
1702  */
1703 static int __init mcheck_enable(char *str)
1704 {
1705         if (*str == 0) {
1706                 enable_p5_mce();
1707                 return 1;
1708         }
1709         if (*str == '=')
1710                 str++;
1711         if (!strcmp(str, "off"))
1712                 mce_disabled = 1;
1713         else if (!strcmp(str, "no_cmci"))
1714                 mce_cmci_disabled = 1;
1715         else if (!strcmp(str, "dont_log_ce"))
1716                 mce_dont_log_ce = 1;
1717         else if (!strcmp(str, "ignore_ce"))
1718                 mce_ignore_ce = 1;
1719         else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1720                 mce_bootlog = (str[0] == 'b');
1721         else if (isdigit(str[0])) {
1722                 get_option(&str, &tolerant);
1723                 if (*str == ',') {
1724                         ++str;
1725                         get_option(&str, &monarch_timeout);
1726                 }
1727         } else {
1728                 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1729                        str);
1730                 return 0;
1731         }
1732         return 1;
1733 }
1734 __setup("mce", mcheck_enable);
1735
1736 int __init mcheck_init(void)
1737 {
1738         mcheck_intel_therm_init();
1739
1740         return 0;
1741 }
1742
1743 /*
1744  * mce_syscore: PM support
1745  */
1746
1747 /*
1748  * Disable machine checks on suspend and shutdown. We can't really handle
1749  * them later.
1750  */
1751 static int mce_disable_error_reporting(void)
1752 {
1753         int i;
1754
1755         for (i = 0; i < banks; i++) {
1756                 struct mce_bank *b = &mce_banks[i];
1757
1758                 if (b->init)
1759                         wrmsrl(MSR_IA32_MCx_CTL(i), 0);
1760         }
1761         return 0;
1762 }
1763
1764 static int mce_syscore_suspend(void)
1765 {
1766         return mce_disable_error_reporting();
1767 }
1768
1769 static void mce_syscore_shutdown(void)
1770 {
1771         mce_disable_error_reporting();
1772 }
1773
1774 /*
1775  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
1776  * Only one CPU is active at this time, the others get re-added later using
1777  * CPU hotplug:
1778  */
1779 static void mce_syscore_resume(void)
1780 {
1781         __mcheck_cpu_init_generic();
1782         __mcheck_cpu_init_vendor(__this_cpu_ptr(&cpu_info));
1783 }
1784
1785 static struct syscore_ops mce_syscore_ops = {
1786         .suspend        = mce_syscore_suspend,
1787         .shutdown       = mce_syscore_shutdown,
1788         .resume         = mce_syscore_resume,
1789 };
1790
1791 /*
1792  * mce_sysdev: Sysfs support
1793  */
1794
1795 static void mce_cpu_restart(void *data)
1796 {
1797         if (!mce_available(__this_cpu_ptr(&cpu_info)))
1798                 return;
1799         __mcheck_cpu_init_generic();
1800         __mcheck_cpu_init_timer();
1801 }
1802
1803 /* Reinit MCEs after user configuration changes */
1804 static void mce_restart(void)
1805 {
1806         mce_timer_delete_all();
1807         on_each_cpu(mce_cpu_restart, NULL, 1);
1808 }
1809
1810 /* Toggle features for corrected errors */
1811 static void mce_disable_cmci(void *data)
1812 {
1813         if (!mce_available(__this_cpu_ptr(&cpu_info)))
1814                 return;
1815         cmci_clear();
1816 }
1817
1818 static void mce_enable_ce(void *all)
1819 {
1820         if (!mce_available(__this_cpu_ptr(&cpu_info)))
1821                 return;
1822         cmci_reenable();
1823         cmci_recheck();
1824         if (all)
1825                 __mcheck_cpu_init_timer();
1826 }
1827
1828 static struct sysdev_class mce_sysdev_class = {
1829         .name           = "machinecheck",
1830 };
1831
1832 DEFINE_PER_CPU(struct sys_device, mce_sysdev);
1833
1834 __cpuinitdata
1835 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1836
1837 static inline struct mce_bank *attr_to_bank(struct sysdev_attribute *attr)
1838 {
1839         return container_of(attr, struct mce_bank, attr);
1840 }
1841
1842 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1843                          char *buf)
1844 {
1845         return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
1846 }
1847
1848 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1849                         const char *buf, size_t size)
1850 {
1851         u64 new;
1852
1853         if (strict_strtoull(buf, 0, &new) < 0)
1854                 return -EINVAL;
1855
1856         attr_to_bank(attr)->ctl = new;
1857         mce_restart();
1858
1859         return size;
1860 }
1861
1862 static ssize_t
1863 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1864 {
1865         strcpy(buf, mce_helper);
1866         strcat(buf, "\n");
1867         return strlen(mce_helper) + 1;
1868 }
1869
1870 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1871                                 const char *buf, size_t siz)
1872 {
1873         char *p;
1874
1875         strncpy(mce_helper, buf, sizeof(mce_helper));
1876         mce_helper[sizeof(mce_helper)-1] = 0;
1877         p = strchr(mce_helper, '\n');
1878
1879         if (p)
1880                 *p = 0;
1881
1882         return strlen(mce_helper) + !!p;
1883 }
1884
1885 static ssize_t set_ignore_ce(struct sys_device *s,
1886                              struct sysdev_attribute *attr,
1887                              const char *buf, size_t size)
1888 {
1889         u64 new;
1890
1891         if (strict_strtoull(buf, 0, &new) < 0)
1892                 return -EINVAL;
1893
1894         if (mce_ignore_ce ^ !!new) {
1895                 if (new) {
1896                         /* disable ce features */
1897                         mce_timer_delete_all();
1898                         on_each_cpu(mce_disable_cmci, NULL, 1);
1899                         mce_ignore_ce = 1;
1900                 } else {
1901                         /* enable ce features */
1902                         mce_ignore_ce = 0;
1903                         on_each_cpu(mce_enable_ce, (void *)1, 1);
1904                 }
1905         }
1906         return size;
1907 }
1908
1909 static ssize_t set_cmci_disabled(struct sys_device *s,
1910                                  struct sysdev_attribute *attr,
1911                                  const char *buf, size_t size)
1912 {
1913         u64 new;
1914
1915         if (strict_strtoull(buf, 0, &new) < 0)
1916                 return -EINVAL;
1917
1918         if (mce_cmci_disabled ^ !!new) {
1919                 if (new) {
1920                         /* disable cmci */
1921                         on_each_cpu(mce_disable_cmci, NULL, 1);
1922                         mce_cmci_disabled = 1;
1923                 } else {
1924                         /* enable cmci */
1925                         mce_cmci_disabled = 0;
1926                         on_each_cpu(mce_enable_ce, NULL, 1);
1927                 }
1928         }
1929         return size;
1930 }
1931
1932 static ssize_t store_int_with_restart(struct sys_device *s,
1933                                       struct sysdev_attribute *attr,
1934                                       const char *buf, size_t size)
1935 {
1936         ssize_t ret = sysdev_store_int(s, attr, buf, size);
1937         mce_restart();
1938         return ret;
1939 }
1940
1941 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
1942 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
1943 static SYSDEV_INT_ATTR(monarch_timeout, 0644, monarch_timeout);
1944 static SYSDEV_INT_ATTR(dont_log_ce, 0644, mce_dont_log_ce);
1945
1946 static struct sysdev_ext_attribute attr_check_interval = {
1947         _SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
1948                      store_int_with_restart),
1949         &check_interval
1950 };
1951
1952 static struct sysdev_ext_attribute attr_ignore_ce = {
1953         _SYSDEV_ATTR(ignore_ce, 0644, sysdev_show_int, set_ignore_ce),
1954         &mce_ignore_ce
1955 };
1956
1957 static struct sysdev_ext_attribute attr_cmci_disabled = {
1958         _SYSDEV_ATTR(cmci_disabled, 0644, sysdev_show_int, set_cmci_disabled),
1959         &mce_cmci_disabled
1960 };
1961
1962 static struct sysdev_attribute *mce_sysdev_attrs[] = {
1963         &attr_tolerant.attr,
1964         &attr_check_interval.attr,
1965         &attr_trigger,
1966         &attr_monarch_timeout.attr,
1967         &attr_dont_log_ce.attr,
1968         &attr_ignore_ce.attr,
1969         &attr_cmci_disabled.attr,
1970         NULL
1971 };
1972
1973 static cpumask_var_t mce_sysdev_initialized;
1974
1975 /* Per cpu sysdev init. All of the cpus still share the same ctrl bank: */
1976 static __cpuinit int mce_sysdev_create(unsigned int cpu)
1977 {
1978         struct sys_device *sysdev = &per_cpu(mce_sysdev, cpu);
1979         int err;
1980         int i, j;
1981
1982         if (!mce_available(&boot_cpu_data))
1983                 return -EIO;
1984
1985         memset(&sysdev->kobj, 0, sizeof(struct kobject));
1986         sysdev->id  = cpu;
1987         sysdev->cls = &mce_sysdev_class;
1988
1989         err = sysdev_register(sysdev);
1990         if (err)
1991                 return err;
1992
1993         for (i = 0; mce_sysdev_attrs[i]; i++) {
1994                 err = sysdev_create_file(sysdev, mce_sysdev_attrs[i]);
1995                 if (err)
1996                         goto error;
1997         }
1998         for (j = 0; j < banks; j++) {
1999                 err = sysdev_create_file(sysdev, &mce_banks[j].attr);
2000                 if (err)
2001                         goto error2;
2002         }
2003         cpumask_set_cpu(cpu, mce_sysdev_initialized);
2004
2005         return 0;
2006 error2:
2007         while (--j >= 0)
2008                 sysdev_remove_file(sysdev, &mce_banks[j].attr);
2009 error:
2010         while (--i >= 0)
2011                 sysdev_remove_file(sysdev, mce_sysdev_attrs[i]);
2012
2013         sysdev_unregister(sysdev);
2014
2015         return err;
2016 }
2017
2018 static __cpuinit void mce_sysdev_remove(unsigned int cpu)
2019 {
2020         struct sys_device *sysdev = &per_cpu(mce_sysdev, cpu);
2021         int i;
2022
2023         if (!cpumask_test_cpu(cpu, mce_sysdev_initialized))
2024                 return;
2025
2026         for (i = 0; mce_sysdev_attrs[i]; i++)
2027                 sysdev_remove_file(sysdev, mce_sysdev_attrs[i]);
2028
2029         for (i = 0; i < banks; i++)
2030                 sysdev_remove_file(sysdev, &mce_banks[i].attr);
2031
2032         sysdev_unregister(sysdev);
2033         cpumask_clear_cpu(cpu, mce_sysdev_initialized);
2034 }
2035
2036 /* Make sure there are no machine checks on offlined CPUs. */
2037 static void __cpuinit mce_disable_cpu(void *h)
2038 {
2039         unsigned long action = *(unsigned long *)h;
2040         int i;
2041
2042         if (!mce_available(__this_cpu_ptr(&cpu_info)))
2043                 return;
2044
2045         if (!(action & CPU_TASKS_FROZEN))
2046                 cmci_clear();
2047         for (i = 0; i < banks; i++) {
2048                 struct mce_bank *b = &mce_banks[i];
2049
2050                 if (b->init)
2051                         wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2052         }
2053 }
2054
2055 static void __cpuinit mce_reenable_cpu(void *h)
2056 {
2057         unsigned long action = *(unsigned long *)h;
2058         int i;
2059
2060         if (!mce_available(__this_cpu_ptr(&cpu_info)))
2061                 return;
2062
2063         if (!(action & CPU_TASKS_FROZEN))
2064                 cmci_reenable();
2065         for (i = 0; i < banks; i++) {
2066                 struct mce_bank *b = &mce_banks[i];
2067
2068                 if (b->init)
2069                         wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2070         }
2071 }
2072
2073 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2074 static int __cpuinit
2075 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2076 {
2077         unsigned int cpu = (unsigned long)hcpu;
2078         struct timer_list *t = &per_cpu(mce_timer, cpu);
2079
2080         switch (action) {
2081         case CPU_ONLINE:
2082         case CPU_ONLINE_FROZEN:
2083                 mce_sysdev_create(cpu);
2084                 if (threshold_cpu_callback)
2085                         threshold_cpu_callback(action, cpu);
2086                 break;
2087         case CPU_DEAD:
2088         case CPU_DEAD_FROZEN:
2089                 if (threshold_cpu_callback)
2090                         threshold_cpu_callback(action, cpu);
2091                 mce_sysdev_remove(cpu);
2092                 break;
2093         case CPU_DOWN_PREPARE:
2094         case CPU_DOWN_PREPARE_FROZEN:
2095                 del_timer_sync(t);
2096                 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2097                 break;
2098         case CPU_DOWN_FAILED:
2099         case CPU_DOWN_FAILED_FROZEN:
2100                 if (!mce_ignore_ce && check_interval) {
2101                         t->expires = round_jiffies(jiffies +
2102                                            __get_cpu_var(mce_next_interval));
2103                         add_timer_on(t, cpu);
2104                 }
2105                 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2106                 break;
2107         case CPU_POST_DEAD:
2108                 /* intentionally ignoring frozen here */
2109                 cmci_rediscover(cpu);
2110                 break;
2111         }
2112         return NOTIFY_OK;
2113 }
2114
2115 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
2116         .notifier_call = mce_cpu_callback,
2117 };
2118
2119 static __init void mce_init_banks(void)
2120 {
2121         int i;
2122
2123         for (i = 0; i < banks; i++) {
2124                 struct mce_bank *b = &mce_banks[i];
2125                 struct sysdev_attribute *a = &b->attr;
2126
2127                 sysfs_attr_init(&a->attr);
2128                 a->attr.name    = b->attrname;
2129                 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2130
2131                 a->attr.mode    = 0644;
2132                 a->show         = show_bank;
2133                 a->store        = set_bank;
2134         }
2135 }
2136
2137 static __init int mcheck_init_device(void)
2138 {
2139         int err;
2140         int i = 0;
2141
2142         if (!mce_available(&boot_cpu_data))
2143                 return -EIO;
2144
2145         zalloc_cpumask_var(&mce_sysdev_initialized, GFP_KERNEL);
2146
2147         mce_init_banks();
2148
2149         err = sysdev_class_register(&mce_sysdev_class);
2150         if (err)
2151                 return err;
2152
2153         for_each_online_cpu(i) {
2154                 err = mce_sysdev_create(i);
2155                 if (err)
2156                         return err;
2157         }
2158
2159         register_syscore_ops(&mce_syscore_ops);
2160         register_hotcpu_notifier(&mce_cpu_notifier);
2161
2162         /* register character device /dev/mcelog */
2163         misc_register(&mce_chrdev_device);
2164
2165         return err;
2166 }
2167 device_initcall(mcheck_init_device);
2168
2169 /*
2170  * Old style boot options parsing. Only for compatibility.
2171  */
2172 static int __init mcheck_disable(char *str)
2173 {
2174         mce_disabled = 1;
2175         return 1;
2176 }
2177 __setup("nomce", mcheck_disable);
2178
2179 #ifdef CONFIG_DEBUG_FS
2180 struct dentry *mce_get_debugfs_dir(void)
2181 {
2182         static struct dentry *dmce;
2183
2184         if (!dmce)
2185                 dmce = debugfs_create_dir("mce", NULL);
2186
2187         return dmce;
2188 }
2189
2190 static void mce_reset(void)
2191 {
2192         cpu_missing = 0;
2193         atomic_set(&mce_fake_paniced, 0);
2194         atomic_set(&mce_executing, 0);
2195         atomic_set(&mce_callin, 0);
2196         atomic_set(&global_nwo, 0);
2197 }
2198
2199 static int fake_panic_get(void *data, u64 *val)
2200 {
2201         *val = fake_panic;
2202         return 0;
2203 }
2204
2205 static int fake_panic_set(void *data, u64 val)
2206 {
2207         mce_reset();
2208         fake_panic = val;
2209         return 0;
2210 }
2211
2212 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2213                         fake_panic_set, "%llu\n");
2214
2215 static int __init mcheck_debugfs_init(void)
2216 {
2217         struct dentry *dmce, *ffake_panic;
2218
2219         dmce = mce_get_debugfs_dir();
2220         if (!dmce)
2221                 return -ENOMEM;
2222         ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2223                                           &fake_panic_fops);
2224         if (!ffake_panic)
2225                 return -ENOMEM;
2226
2227         return 0;
2228 }
2229 late_initcall(mcheck_debugfs_init);
2230 #endif