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