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