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