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