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