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