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