1217816278584ef06e5aab3787b5a5c1f6448be2
[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/ctype.h>
25 #include <linux/sched.h>
26 #include <linux/sysfs.h>
27 #include <linux/types.h>
28 #include <linux/init.h>
29 #include <linux/kmod.h>
30 #include <linux/poll.h>
31 #include <linux/cpu.h>
32 #include <linux/smp.h>
33 #include <linux/fs.h>
34
35 #include <asm/processor.h>
36 #include <asm/hw_irq.h>
37 #include <asm/apic.h>
38 #include <asm/idle.h>
39 #include <asm/ipi.h>
40 #include <asm/mce.h>
41 #include <asm/msr.h>
42
43 #include "mce-internal.h"
44 #include "mce.h"
45
46 /* Handle unconfigured int18 (should never happen) */
47 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
48 {
49         printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
50                smp_processor_id());
51 }
52
53 /* Call the installed machine check handler for this CPU setup. */
54 void (*machine_check_vector)(struct pt_regs *, long error_code) =
55                                                 unexpected_machine_check;
56
57 int                             mce_disabled;
58
59 #ifdef CONFIG_X86_NEW_MCE
60
61 #define MISC_MCELOG_MINOR       227
62
63 atomic_t mce_entry;
64
65 DEFINE_PER_CPU(unsigned, mce_exception_count);
66
67 /*
68  * Tolerant levels:
69  *   0: always panic on uncorrected errors, log corrected errors
70  *   1: panic or SIGBUS on uncorrected errors, log corrected errors
71  *   2: SIGBUS or log uncorrected errors (if possible), log corrected errors
72  *   3: never panic or SIGBUS, log all errors (for testing only)
73  */
74 static int                      tolerant = 1;
75 static int                      banks;
76 static u64                      *bank;
77 static unsigned long            notify_user;
78 static int                      rip_msr;
79 static int                      mce_bootlog = -1;
80
81 static char                     trigger[128];
82 static char                     *trigger_argv[2] = { trigger, NULL };
83
84 static unsigned long            dont_init_banks;
85
86 static DECLARE_WAIT_QUEUE_HEAD(mce_wait);
87
88 /* MCA banks polled by the period polling timer for corrected events */
89 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
90         [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
91 };
92
93 static inline int skip_bank_init(int i)
94 {
95         return i < BITS_PER_LONG && test_bit(i, &dont_init_banks);
96 }
97
98 /* Do initial initialization of a struct mce */
99 void mce_setup(struct mce *m)
100 {
101         memset(m, 0, sizeof(struct mce));
102         m->cpu = m->extcpu = smp_processor_id();
103         rdtscll(m->tsc);
104         /* We hope get_seconds stays lockless */
105         m->time = get_seconds();
106         m->cpuvendor = boot_cpu_data.x86_vendor;
107         m->cpuid = cpuid_eax(1);
108 #ifdef CONFIG_SMP
109         m->socketid = cpu_data(m->extcpu).phys_proc_id;
110 #endif
111         m->apicid = cpu_data(m->extcpu).initial_apicid;
112         rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
113 }
114
115 DEFINE_PER_CPU(struct mce, injectm);
116 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
117
118 /*
119  * Lockless MCE logging infrastructure.
120  * This avoids deadlocks on printk locks without having to break locks. Also
121  * separate MCEs from kernel messages to avoid bogus bug reports.
122  */
123
124 static struct mce_log mcelog = {
125         .signature      = MCE_LOG_SIGNATURE,
126         .len            = MCE_LOG_LEN,
127         .recordlen      = sizeof(struct mce),
128 };
129
130 void mce_log(struct mce *mce)
131 {
132         unsigned next, entry;
133
134         mce->finished = 0;
135         wmb();
136         for (;;) {
137                 entry = rcu_dereference(mcelog.next);
138                 for (;;) {
139                         /*
140                          * When the buffer fills up discard new entries.
141                          * Assume that the earlier errors are the more
142                          * interesting ones:
143                          */
144                         if (entry >= MCE_LOG_LEN) {
145                                 set_bit(MCE_OVERFLOW,
146                                         (unsigned long *)&mcelog.flags);
147                                 return;
148                         }
149                         /* Old left over entry. Skip: */
150                         if (mcelog.entry[entry].finished) {
151                                 entry++;
152                                 continue;
153                         }
154                         break;
155                 }
156                 smp_rmb();
157                 next = entry + 1;
158                 if (cmpxchg(&mcelog.next, entry, next) == entry)
159                         break;
160         }
161         memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
162         wmb();
163         mcelog.entry[entry].finished = 1;
164         wmb();
165
166         mce->finished = 1;
167         set_bit(0, &notify_user);
168 }
169
170 static void print_mce(struct mce *m)
171 {
172         printk(KERN_EMERG "\n"
173                KERN_EMERG "HARDWARE ERROR\n"
174                KERN_EMERG
175                "CPU %d: Machine Check Exception: %16Lx Bank %d: %016Lx\n",
176                m->extcpu, m->mcgstatus, m->bank, m->status);
177         if (m->ip) {
178                 printk(KERN_EMERG "RIP%s %02x:<%016Lx> ",
179                        !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
180                        m->cs, m->ip);
181                 if (m->cs == __KERNEL_CS)
182                         print_symbol("{%s}", m->ip);
183                 printk("\n");
184         }
185         printk(KERN_EMERG "TSC %llx ", m->tsc);
186         if (m->addr)
187                 printk("ADDR %llx ", m->addr);
188         if (m->misc)
189                 printk("MISC %llx ", m->misc);
190         printk("\n");
191         printk(KERN_EMERG "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x\n",
192                         m->cpuvendor, m->cpuid, m->time, m->socketid,
193                         m->apicid);
194         printk(KERN_EMERG "This is not a software problem!\n");
195         printk(KERN_EMERG "Run through mcelog --ascii to decode "
196                "and contact your hardware vendor\n");
197 }
198
199 static void mce_panic(char *msg, struct mce *final, char *exp)
200 {
201         int i;
202
203         bust_spinlocks(1);
204         console_verbose();
205         /* First print corrected ones that are still unlogged */
206         for (i = 0; i < MCE_LOG_LEN; i++) {
207                 struct mce *m = &mcelog.entry[i];
208                 if ((m->status & MCI_STATUS_VAL) &&
209                         !(m->status & MCI_STATUS_UC))
210                         print_mce(m);
211         }
212         /* Now print uncorrected but with the final one last */
213         for (i = 0; i < MCE_LOG_LEN; i++) {
214                 struct mce *m = &mcelog.entry[i];
215                 if (!(m->status & MCI_STATUS_VAL))
216                         continue;
217                 if (!final || memcmp(m, final, sizeof(struct mce)))
218                         print_mce(m);
219         }
220         if (final)
221                 print_mce(final);
222         if (exp)
223                 printk(KERN_EMERG "Machine check: %s\n", exp);
224         panic(msg);
225 }
226
227 /* Support code for software error injection */
228
229 static int msr_to_offset(u32 msr)
230 {
231         unsigned bank = __get_cpu_var(injectm.bank);
232         if (msr == rip_msr)
233                 return offsetof(struct mce, ip);
234         if (msr == MSR_IA32_MC0_STATUS + bank*4)
235                 return offsetof(struct mce, status);
236         if (msr == MSR_IA32_MC0_ADDR + bank*4)
237                 return offsetof(struct mce, addr);
238         if (msr == MSR_IA32_MC0_MISC + bank*4)
239                 return offsetof(struct mce, misc);
240         if (msr == MSR_IA32_MCG_STATUS)
241                 return offsetof(struct mce, mcgstatus);
242         return -1;
243 }
244
245 /* MSR access wrappers used for error injection */
246 static u64 mce_rdmsrl(u32 msr)
247 {
248         u64 v;
249         if (__get_cpu_var(injectm).finished) {
250                 int offset = msr_to_offset(msr);
251                 if (offset < 0)
252                         return 0;
253                 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
254         }
255         rdmsrl(msr, v);
256         return v;
257 }
258
259 static void mce_wrmsrl(u32 msr, u64 v)
260 {
261         if (__get_cpu_var(injectm).finished) {
262                 int offset = msr_to_offset(msr);
263                 if (offset >= 0)
264                         *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
265                 return;
266         }
267         wrmsrl(msr, v);
268 }
269
270 int mce_available(struct cpuinfo_x86 *c)
271 {
272         if (mce_disabled)
273                 return 0;
274         return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
275 }
276
277 static inline void mce_get_rip(struct mce *m, struct pt_regs *regs)
278 {
279         if (regs && (m->mcgstatus & MCG_STATUS_RIPV)) {
280                 m->ip = regs->ip;
281                 m->cs = regs->cs;
282         } else {
283                 m->ip = 0;
284                 m->cs = 0;
285         }
286         if (rip_msr) {
287                 /* Assume the RIP in the MSR is exact. Is this true? */
288                 m->mcgstatus |= MCG_STATUS_EIPV;
289                 m->ip = mce_rdmsrl(rip_msr);
290                 m->cs = 0;
291         }
292 }
293
294 #ifdef CONFIG_X86_LOCAL_APIC 
295 /*
296  * Called after interrupts have been reenabled again
297  * when a MCE happened during an interrupts off region
298  * in the kernel.
299  */
300 asmlinkage void smp_mce_self_interrupt(struct pt_regs *regs)
301 {
302         ack_APIC_irq();
303         exit_idle();
304         irq_enter();
305         mce_notify_user();
306         irq_exit();
307 }
308 #endif
309
310 static void mce_report_event(struct pt_regs *regs)
311 {
312         if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
313                 mce_notify_user();
314                 return;
315         }
316
317 #ifdef CONFIG_X86_LOCAL_APIC
318         /*
319          * Without APIC do not notify. The event will be picked
320          * up eventually.
321          */
322         if (!cpu_has_apic)
323                 return;
324
325         /*
326          * When interrupts are disabled we cannot use
327          * kernel services safely. Trigger an self interrupt
328          * through the APIC to instead do the notification
329          * after interrupts are reenabled again.
330          */
331         apic->send_IPI_self(MCE_SELF_VECTOR);
332
333         /*
334          * Wait for idle afterwards again so that we don't leave the
335          * APIC in a non idle state because the normal APIC writes
336          * cannot exclude us.
337          */
338         apic_wait_icr_idle();
339 #endif
340 }
341
342 DEFINE_PER_CPU(unsigned, mce_poll_count);
343
344 /*
345  * Poll for corrected events or events that happened before reset.
346  * Those are just logged through /dev/mcelog.
347  *
348  * This is executed in standard interrupt context.
349  */
350 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
351 {
352         struct mce m;
353         int i;
354
355         __get_cpu_var(mce_poll_count)++;
356
357         mce_setup(&m);
358
359         m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
360         for (i = 0; i < banks; i++) {
361                 if (!bank[i] || !test_bit(i, *b))
362                         continue;
363
364                 m.misc = 0;
365                 m.addr = 0;
366                 m.bank = i;
367                 m.tsc = 0;
368
369                 barrier();
370                 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
371                 if (!(m.status & MCI_STATUS_VAL))
372                         continue;
373
374                 /*
375                  * Uncorrected events are handled by the exception handler
376                  * when it is enabled. But when the exception is disabled log
377                  * everything.
378                  *
379                  * TBD do the same check for MCI_STATUS_EN here?
380                  */
381                 if ((m.status & MCI_STATUS_UC) && !(flags & MCP_UC))
382                         continue;
383
384                 if (m.status & MCI_STATUS_MISCV)
385                         m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
386                 if (m.status & MCI_STATUS_ADDRV)
387                         m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
388
389                 if (!(flags & MCP_TIMESTAMP))
390                         m.tsc = 0;
391                 /*
392                  * Don't get the IP here because it's unlikely to
393                  * have anything to do with the actual error location.
394                  */
395                 if (!(flags & MCP_DONTLOG)) {
396                         mce_log(&m);
397                         add_taint(TAINT_MACHINE_CHECK);
398                 }
399
400                 /*
401                  * Clear state for this bank.
402                  */
403                 mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
404         }
405
406         /*
407          * Don't clear MCG_STATUS here because it's only defined for
408          * exceptions.
409          */
410
411         sync_core();
412 }
413 EXPORT_SYMBOL_GPL(machine_check_poll);
414
415 /*
416  * Do a quick check if any of the events requires a panic.
417  * This decides if we keep the events around or clear them.
418  */
419 static int mce_no_way_out(struct mce *m, char **msg)
420 {
421         int i;
422
423         for (i = 0; i < banks; i++) {
424                 m->status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
425                 if (mce_severity(m, tolerant, msg) >= MCE_PANIC_SEVERITY)
426                         return 1;
427         }
428         return 0;
429 }
430
431 /*
432  * The actual machine check handler. This only handles real
433  * exceptions when something got corrupted coming in through int 18.
434  *
435  * This is executed in NMI context not subject to normal locking rules. This
436  * implies that most kernel services cannot be safely used. Don't even
437  * think about putting a printk in there!
438  */
439 void do_machine_check(struct pt_regs *regs, long error_code)
440 {
441         struct mce m, panicm;
442         int panicm_found = 0;
443         int i;
444         /*
445          * If no_way_out gets set, there is no safe way to recover from this
446          * MCE.  If tolerant is cranked up, we'll try anyway.
447          */
448         int no_way_out = 0;
449         /*
450          * If kill_it gets set, there might be a way to recover from this
451          * error.
452          */
453         int kill_it = 0;
454         DECLARE_BITMAP(toclear, MAX_NR_BANKS);
455         char *msg = "Unknown";
456
457         atomic_inc(&mce_entry);
458
459         __get_cpu_var(mce_exception_count)++;
460
461         if (notify_die(DIE_NMI, "machine check", regs, error_code,
462                            18, SIGKILL) == NOTIFY_STOP)
463                 goto out;
464         if (!banks)
465                 goto out;
466
467         mce_setup(&m);
468
469         m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
470         no_way_out = mce_no_way_out(&m, &msg);
471
472         barrier();
473
474         for (i = 0; i < banks; i++) {
475                 __clear_bit(i, toclear);
476                 if (!bank[i])
477                         continue;
478
479                 m.misc = 0;
480                 m.addr = 0;
481                 m.bank = i;
482
483                 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
484                 if ((m.status & MCI_STATUS_VAL) == 0)
485                         continue;
486
487                 /*
488                  * Non uncorrected errors are handled by machine_check_poll
489                  * Leave them alone, unless this panics.
490                  */
491                 if ((m.status & MCI_STATUS_UC) == 0 && !no_way_out)
492                         continue;
493
494                 /*
495                  * Set taint even when machine check was not enabled.
496                  */
497                 add_taint(TAINT_MACHINE_CHECK);
498
499                 __set_bit(i, toclear);
500
501                 if (m.status & MCI_STATUS_EN) {
502                         /*
503                          * If this error was uncorrectable and there was
504                          * an overflow, we're in trouble.  If no overflow,
505                          * we might get away with just killing a task.
506                          */
507                         if (m.status & MCI_STATUS_UC)
508                                 kill_it = 1;
509                 } else {
510                         /*
511                          * Machine check event was not enabled. Clear, but
512                          * ignore.
513                          */
514                         continue;
515                 }
516
517                 if (m.status & MCI_STATUS_MISCV)
518                         m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
519                 if (m.status & MCI_STATUS_ADDRV)
520                         m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
521
522                 mce_get_rip(&m, regs);
523                 mce_log(&m);
524
525                 /*
526                  * Did this bank cause the exception?
527                  *
528                  * Assume that the bank with uncorrectable errors did it,
529                  * and that there is only a single one:
530                  */
531                 if ((m.status & MCI_STATUS_UC) &&
532                                         (m.status & MCI_STATUS_EN)) {
533                         panicm = m;
534                         panicm_found = 1;
535                 }
536         }
537
538         /*
539          * If we didn't find an uncorrectable error, pick
540          * the last one (shouldn't happen, just being safe).
541          */
542         if (!panicm_found)
543                 panicm = m;
544
545         /*
546          * If we have decided that we just CAN'T continue, and the user
547          * has not set tolerant to an insane level, give up and die.
548          */
549         if (no_way_out && tolerant < 3)
550                 mce_panic("Machine check", &panicm, msg);
551
552         /*
553          * If the error seems to be unrecoverable, something should be
554          * done.  Try to kill as little as possible.  If we can kill just
555          * one task, do that.  If the user has set the tolerance very
556          * high, don't try to do anything at all.
557          */
558         if (kill_it && tolerant < 3) {
559                 int user_space = 0;
560
561                 /*
562                  * If the EIPV bit is set, it means the saved IP is the
563                  * instruction which caused the MCE.
564                  */
565                 if (m.mcgstatus & MCG_STATUS_EIPV)
566                         user_space = panicm.ip && (panicm.cs & 3);
567
568                 /*
569                  * If we know that the error was in user space, send a
570                  * SIGBUS.  Otherwise, panic if tolerance is low.
571                  *
572                  * force_sig() takes an awful lot of locks and has a slight
573                  * risk of deadlocking.
574                  */
575                 if (user_space) {
576                         force_sig(SIGBUS, current);
577                 } else if (panic_on_oops || tolerant < 2) {
578                         mce_panic("Uncorrected machine check", &panicm, msg);
579                 }
580         }
581
582         /* notify userspace ASAP */
583         set_thread_flag(TIF_MCE_NOTIFY);
584
585         mce_report_event(regs);
586
587         /* the last thing we do is clear state */
588         for (i = 0; i < banks; i++) {
589                 if (test_bit(i, toclear))
590                         mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
591         }
592         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
593 out:
594         atomic_dec(&mce_entry);
595         sync_core();
596 }
597 EXPORT_SYMBOL_GPL(do_machine_check);
598
599 #ifdef CONFIG_X86_MCE_INTEL
600 /***
601  * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
602  * @cpu: The CPU on which the event occurred.
603  * @status: Event status information
604  *
605  * This function should be called by the thermal interrupt after the
606  * event has been processed and the decision was made to log the event
607  * further.
608  *
609  * The status parameter will be saved to the 'status' field of 'struct mce'
610  * and historically has been the register value of the
611  * MSR_IA32_THERMAL_STATUS (Intel) msr.
612  */
613 void mce_log_therm_throt_event(__u64 status)
614 {
615         struct mce m;
616
617         mce_setup(&m);
618         m.bank = MCE_THERMAL_BANK;
619         m.status = status;
620         mce_log(&m);
621 }
622 #endif /* CONFIG_X86_MCE_INTEL */
623
624 /*
625  * Periodic polling timer for "silent" machine check errors.  If the
626  * poller finds an MCE, poll 2x faster.  When the poller finds no more
627  * errors, poll 2x slower (up to check_interval seconds).
628  */
629 static int check_interval = 5 * 60; /* 5 minutes */
630
631 static DEFINE_PER_CPU(int, next_interval); /* in jiffies */
632 static DEFINE_PER_CPU(struct timer_list, mce_timer);
633
634 static void mcheck_timer(unsigned long data)
635 {
636         struct timer_list *t = &per_cpu(mce_timer, data);
637         int *n;
638
639         WARN_ON(smp_processor_id() != data);
640
641         if (mce_available(&current_cpu_data)) {
642                 machine_check_poll(MCP_TIMESTAMP,
643                                 &__get_cpu_var(mce_poll_banks));
644         }
645
646         /*
647          * Alert userspace if needed.  If we logged an MCE, reduce the
648          * polling interval, otherwise increase the polling interval.
649          */
650         n = &__get_cpu_var(next_interval);
651         if (mce_notify_user())
652                 *n = max(*n/2, HZ/100);
653         else
654                 *n = min(*n*2, (int)round_jiffies_relative(check_interval*HZ));
655
656         t->expires = jiffies + *n;
657         add_timer(t);
658 }
659
660 static void mce_do_trigger(struct work_struct *work)
661 {
662         call_usermodehelper(trigger, trigger_argv, NULL, UMH_NO_WAIT);
663 }
664
665 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
666
667 /*
668  * Notify the user(s) about new machine check events.
669  * Can be called from interrupt context, but not from machine check/NMI
670  * context.
671  */
672 int mce_notify_user(void)
673 {
674         /* Not more than two messages every minute */
675         static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
676
677         clear_thread_flag(TIF_MCE_NOTIFY);
678
679         if (test_and_clear_bit(0, &notify_user)) {
680                 wake_up_interruptible(&mce_wait);
681
682                 /*
683                  * There is no risk of missing notifications because
684                  * work_pending is always cleared before the function is
685                  * executed.
686                  */
687                 if (trigger[0] && !work_pending(&mce_trigger_work))
688                         schedule_work(&mce_trigger_work);
689
690                 if (__ratelimit(&ratelimit))
691                         printk(KERN_INFO "Machine check events logged\n");
692
693                 return 1;
694         }
695         return 0;
696 }
697 EXPORT_SYMBOL_GPL(mce_notify_user);
698
699 /*
700  * Initialize Machine Checks for a CPU.
701  */
702 static int mce_cap_init(void)
703 {
704         unsigned b;
705         u64 cap;
706
707         rdmsrl(MSR_IA32_MCG_CAP, cap);
708
709         b = cap & MCG_BANKCNT_MASK;
710         printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
711
712         if (b > MAX_NR_BANKS) {
713                 printk(KERN_WARNING
714                        "MCE: Using only %u machine check banks out of %u\n",
715                         MAX_NR_BANKS, b);
716                 b = MAX_NR_BANKS;
717         }
718
719         /* Don't support asymmetric configurations today */
720         WARN_ON(banks != 0 && b != banks);
721         banks = b;
722         if (!bank) {
723                 bank = kmalloc(banks * sizeof(u64), GFP_KERNEL);
724                 if (!bank)
725                         return -ENOMEM;
726                 memset(bank, 0xff, banks * sizeof(u64));
727         }
728
729         /* Use accurate RIP reporting if available. */
730         if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
731                 rip_msr = MSR_IA32_MCG_EIP;
732
733         return 0;
734 }
735
736 static void mce_init(void)
737 {
738         mce_banks_t all_banks;
739         u64 cap;
740         int i;
741
742         /*
743          * Log the machine checks left over from the previous reset.
744          */
745         bitmap_fill(all_banks, MAX_NR_BANKS);
746         machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
747
748         set_in_cr4(X86_CR4_MCE);
749
750         rdmsrl(MSR_IA32_MCG_CAP, cap);
751         if (cap & MCG_CTL_P)
752                 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
753
754         for (i = 0; i < banks; i++) {
755                 if (skip_bank_init(i))
756                         continue;
757                 wrmsrl(MSR_IA32_MC0_CTL+4*i, bank[i]);
758                 wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
759         }
760 }
761
762 /* Add per CPU specific workarounds here */
763 static void mce_cpu_quirks(struct cpuinfo_x86 *c)
764 {
765         /* This should be disabled by the BIOS, but isn't always */
766         if (c->x86_vendor == X86_VENDOR_AMD) {
767                 if (c->x86 == 15 && banks > 4) {
768                         /*
769                          * disable GART TBL walk error reporting, which
770                          * trips off incorrectly with the IOMMU & 3ware
771                          * & Cerberus:
772                          */
773                         clear_bit(10, (unsigned long *)&bank[4]);
774                 }
775                 if (c->x86 <= 17 && mce_bootlog < 0) {
776                         /*
777                          * Lots of broken BIOS around that don't clear them
778                          * by default and leave crap in there. Don't log:
779                          */
780                         mce_bootlog = 0;
781                 }
782                 /*
783                  * Various K7s with broken bank 0 around. Always disable
784                  * by default.
785                  */
786                  if (c->x86 == 6)
787                         bank[0] = 0;
788         }
789
790         if (c->x86_vendor == X86_VENDOR_INTEL) {
791                 /*
792                  * SDM documents that on family 6 bank 0 should not be written
793                  * because it aliases to another special BIOS controlled
794                  * register.
795                  * But it's not aliased anymore on model 0x1a+
796                  * Don't ignore bank 0 completely because there could be a
797                  * valid event later, merely don't write CTL0.
798                  */
799
800                 if (c->x86 == 6 && c->x86_model < 0x1A)
801                         __set_bit(0, &dont_init_banks);
802         }
803 }
804
805 static void __cpuinit mce_ancient_init(struct cpuinfo_x86 *c)
806 {
807         if (c->x86 != 5)
808                 return;
809         switch (c->x86_vendor) {
810         case X86_VENDOR_INTEL:
811                 if (mce_p5_enabled())
812                         intel_p5_mcheck_init(c);
813                 break;
814         case X86_VENDOR_CENTAUR:
815                 winchip_mcheck_init(c);
816                 break;
817         }
818 }
819
820 static void mce_cpu_features(struct cpuinfo_x86 *c)
821 {
822         switch (c->x86_vendor) {
823         case X86_VENDOR_INTEL:
824                 mce_intel_feature_init(c);
825                 break;
826         case X86_VENDOR_AMD:
827                 mce_amd_feature_init(c);
828                 break;
829         default:
830                 break;
831         }
832 }
833
834 static void mce_init_timer(void)
835 {
836         struct timer_list *t = &__get_cpu_var(mce_timer);
837         int *n = &__get_cpu_var(next_interval);
838
839         *n = check_interval * HZ;
840         if (!*n)
841                 return;
842         setup_timer(t, mcheck_timer, smp_processor_id());
843         t->expires = round_jiffies(jiffies + *n);
844         add_timer(t);
845 }
846
847 /*
848  * Called for each booted CPU to set up machine checks.
849  * Must be called with preempt off:
850  */
851 void __cpuinit mcheck_init(struct cpuinfo_x86 *c)
852 {
853         if (mce_disabled)
854                 return;
855
856         mce_ancient_init(c);
857
858         if (!mce_available(c))
859                 return;
860
861         if (mce_cap_init() < 0) {
862                 mce_disabled = 1;
863                 return;
864         }
865         mce_cpu_quirks(c);
866
867         machine_check_vector = do_machine_check;
868
869         mce_init();
870         mce_cpu_features(c);
871         mce_init_timer();
872 }
873
874 /*
875  * Character device to read and clear the MCE log.
876  */
877
878 static DEFINE_SPINLOCK(mce_state_lock);
879 static int              open_count;             /* #times opened */
880 static int              open_exclu;             /* already open exclusive? */
881
882 static int mce_open(struct inode *inode, struct file *file)
883 {
884         spin_lock(&mce_state_lock);
885
886         if (open_exclu || (open_count && (file->f_flags & O_EXCL))) {
887                 spin_unlock(&mce_state_lock);
888
889                 return -EBUSY;
890         }
891
892         if (file->f_flags & O_EXCL)
893                 open_exclu = 1;
894         open_count++;
895
896         spin_unlock(&mce_state_lock);
897
898         return nonseekable_open(inode, file);
899 }
900
901 static int mce_release(struct inode *inode, struct file *file)
902 {
903         spin_lock(&mce_state_lock);
904
905         open_count--;
906         open_exclu = 0;
907
908         spin_unlock(&mce_state_lock);
909
910         return 0;
911 }
912
913 static void collect_tscs(void *data)
914 {
915         unsigned long *cpu_tsc = (unsigned long *)data;
916
917         rdtscll(cpu_tsc[smp_processor_id()]);
918 }
919
920 static DEFINE_MUTEX(mce_read_mutex);
921
922 static ssize_t mce_read(struct file *filp, char __user *ubuf, size_t usize,
923                         loff_t *off)
924 {
925         char __user *buf = ubuf;
926         unsigned long *cpu_tsc;
927         unsigned prev, next;
928         int i, err;
929
930         cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
931         if (!cpu_tsc)
932                 return -ENOMEM;
933
934         mutex_lock(&mce_read_mutex);
935         next = rcu_dereference(mcelog.next);
936
937         /* Only supports full reads right now */
938         if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce)) {
939                 mutex_unlock(&mce_read_mutex);
940                 kfree(cpu_tsc);
941
942                 return -EINVAL;
943         }
944
945         err = 0;
946         prev = 0;
947         do {
948                 for (i = prev; i < next; i++) {
949                         unsigned long start = jiffies;
950
951                         while (!mcelog.entry[i].finished) {
952                                 if (time_after_eq(jiffies, start + 2)) {
953                                         memset(mcelog.entry + i, 0,
954                                                sizeof(struct mce));
955                                         goto timeout;
956                                 }
957                                 cpu_relax();
958                         }
959                         smp_rmb();
960                         err |= copy_to_user(buf, mcelog.entry + i,
961                                             sizeof(struct mce));
962                         buf += sizeof(struct mce);
963 timeout:
964                         ;
965                 }
966
967                 memset(mcelog.entry + prev, 0,
968                        (next - prev) * sizeof(struct mce));
969                 prev = next;
970                 next = cmpxchg(&mcelog.next, prev, 0);
971         } while (next != prev);
972
973         synchronize_sched();
974
975         /*
976          * Collect entries that were still getting written before the
977          * synchronize.
978          */
979         on_each_cpu(collect_tscs, cpu_tsc, 1);
980
981         for (i = next; i < MCE_LOG_LEN; i++) {
982                 if (mcelog.entry[i].finished &&
983                     mcelog.entry[i].tsc < cpu_tsc[mcelog.entry[i].cpu]) {
984                         err |= copy_to_user(buf, mcelog.entry+i,
985                                             sizeof(struct mce));
986                         smp_rmb();
987                         buf += sizeof(struct mce);
988                         memset(&mcelog.entry[i], 0, sizeof(struct mce));
989                 }
990         }
991         mutex_unlock(&mce_read_mutex);
992         kfree(cpu_tsc);
993
994         return err ? -EFAULT : buf - ubuf;
995 }
996
997 static unsigned int mce_poll(struct file *file, poll_table *wait)
998 {
999         poll_wait(file, &mce_wait, wait);
1000         if (rcu_dereference(mcelog.next))
1001                 return POLLIN | POLLRDNORM;
1002         return 0;
1003 }
1004
1005 static long mce_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1006 {
1007         int __user *p = (int __user *)arg;
1008
1009         if (!capable(CAP_SYS_ADMIN))
1010                 return -EPERM;
1011
1012         switch (cmd) {
1013         case MCE_GET_RECORD_LEN:
1014                 return put_user(sizeof(struct mce), p);
1015         case MCE_GET_LOG_LEN:
1016                 return put_user(MCE_LOG_LEN, p);
1017         case MCE_GETCLEAR_FLAGS: {
1018                 unsigned flags;
1019
1020                 do {
1021                         flags = mcelog.flags;
1022                 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1023
1024                 return put_user(flags, p);
1025         }
1026         default:
1027                 return -ENOTTY;
1028         }
1029 }
1030
1031 /* Modified in mce-inject.c, so not static or const */
1032 struct file_operations mce_chrdev_ops = {
1033         .open                   = mce_open,
1034         .release                = mce_release,
1035         .read                   = mce_read,
1036         .poll                   = mce_poll,
1037         .unlocked_ioctl         = mce_ioctl,
1038 };
1039 EXPORT_SYMBOL_GPL(mce_chrdev_ops);
1040
1041 static struct miscdevice mce_log_device = {
1042         MISC_MCELOG_MINOR,
1043         "mcelog",
1044         &mce_chrdev_ops,
1045 };
1046
1047 /*
1048  * mce=off disables machine check
1049  * mce=TOLERANCELEVEL (number, see above)
1050  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1051  * mce=nobootlog Don't log MCEs from before booting.
1052  */
1053 static int __init mcheck_enable(char *str)
1054 {
1055         if (*str == 0)
1056                 enable_p5_mce();
1057         if (*str == '=')
1058                 str++;
1059         if (!strcmp(str, "off"))
1060                 mce_disabled = 1;
1061         else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1062                 mce_bootlog = (str[0] == 'b');
1063         else if (isdigit(str[0]))
1064                 get_option(&str, &tolerant);
1065         else {
1066                 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1067                        str);
1068                 return 0;
1069         }
1070         return 1;
1071 }
1072 __setup("mce", mcheck_enable);
1073
1074 /*
1075  * Sysfs support
1076  */
1077
1078 /*
1079  * Disable machine checks on suspend and shutdown. We can't really handle
1080  * them later.
1081  */
1082 static int mce_disable(void)
1083 {
1084         int i;
1085
1086         for (i = 0; i < banks; i++) {
1087                 if (!skip_bank_init(i))
1088                         wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1089         }
1090         return 0;
1091 }
1092
1093 static int mce_suspend(struct sys_device *dev, pm_message_t state)
1094 {
1095         return mce_disable();
1096 }
1097
1098 static int mce_shutdown(struct sys_device *dev)
1099 {
1100         return mce_disable();
1101 }
1102
1103 /*
1104  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
1105  * Only one CPU is active at this time, the others get re-added later using
1106  * CPU hotplug:
1107  */
1108 static int mce_resume(struct sys_device *dev)
1109 {
1110         mce_init();
1111         mce_cpu_features(&current_cpu_data);
1112
1113         return 0;
1114 }
1115
1116 static void mce_cpu_restart(void *data)
1117 {
1118         del_timer_sync(&__get_cpu_var(mce_timer));
1119         if (mce_available(&current_cpu_data))
1120                 mce_init();
1121         mce_init_timer();
1122 }
1123
1124 /* Reinit MCEs after user configuration changes */
1125 static void mce_restart(void)
1126 {
1127         on_each_cpu(mce_cpu_restart, NULL, 1);
1128 }
1129
1130 static struct sysdev_class mce_sysclass = {
1131         .suspend        = mce_suspend,
1132         .shutdown       = mce_shutdown,
1133         .resume         = mce_resume,
1134         .name           = "machinecheck",
1135 };
1136
1137 DEFINE_PER_CPU(struct sys_device, mce_dev);
1138
1139 __cpuinitdata
1140 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1141
1142 static struct sysdev_attribute *bank_attrs;
1143
1144 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1145                          char *buf)
1146 {
1147         u64 b = bank[attr - bank_attrs];
1148
1149         return sprintf(buf, "%llx\n", b);
1150 }
1151
1152 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1153                         const char *buf, size_t size)
1154 {
1155         u64 new;
1156
1157         if (strict_strtoull(buf, 0, &new) < 0)
1158                 return -EINVAL;
1159
1160         bank[attr - bank_attrs] = new;
1161         mce_restart();
1162
1163         return size;
1164 }
1165
1166 static ssize_t
1167 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1168 {
1169         strcpy(buf, trigger);
1170         strcat(buf, "\n");
1171         return strlen(trigger) + 1;
1172 }
1173
1174 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1175                                 const char *buf, size_t siz)
1176 {
1177         char *p;
1178         int len;
1179
1180         strncpy(trigger, buf, sizeof(trigger));
1181         trigger[sizeof(trigger)-1] = 0;
1182         len = strlen(trigger);
1183         p = strchr(trigger, '\n');
1184
1185         if (*p)
1186                 *p = 0;
1187
1188         return len;
1189 }
1190
1191 static ssize_t store_int_with_restart(struct sys_device *s,
1192                                       struct sysdev_attribute *attr,
1193                                       const char *buf, size_t size)
1194 {
1195         ssize_t ret = sysdev_store_int(s, attr, buf, size);
1196         mce_restart();
1197         return ret;
1198 }
1199
1200 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
1201 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
1202
1203 static struct sysdev_ext_attribute attr_check_interval = {
1204         _SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
1205                      store_int_with_restart),
1206         &check_interval
1207 };
1208
1209 static struct sysdev_attribute *mce_attrs[] = {
1210         &attr_tolerant.attr, &attr_check_interval.attr, &attr_trigger,
1211         NULL
1212 };
1213
1214 static cpumask_var_t mce_dev_initialized;
1215
1216 /* Per cpu sysdev init. All of the cpus still share the same ctrl bank: */
1217 static __cpuinit int mce_create_device(unsigned int cpu)
1218 {
1219         int err;
1220         int i;
1221
1222         if (!mce_available(&boot_cpu_data))
1223                 return -EIO;
1224
1225         memset(&per_cpu(mce_dev, cpu).kobj, 0, sizeof(struct kobject));
1226         per_cpu(mce_dev, cpu).id        = cpu;
1227         per_cpu(mce_dev, cpu).cls       = &mce_sysclass;
1228
1229         err = sysdev_register(&per_cpu(mce_dev, cpu));
1230         if (err)
1231                 return err;
1232
1233         for (i = 0; mce_attrs[i]; i++) {
1234                 err = sysdev_create_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1235                 if (err)
1236                         goto error;
1237         }
1238         for (i = 0; i < banks; i++) {
1239                 err = sysdev_create_file(&per_cpu(mce_dev, cpu),
1240                                         &bank_attrs[i]);
1241                 if (err)
1242                         goto error2;
1243         }
1244         cpumask_set_cpu(cpu, mce_dev_initialized);
1245
1246         return 0;
1247 error2:
1248         while (--i >= 0)
1249                 sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[i]);
1250 error:
1251         while (--i >= 0)
1252                 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1253
1254         sysdev_unregister(&per_cpu(mce_dev, cpu));
1255
1256         return err;
1257 }
1258
1259 static __cpuinit void mce_remove_device(unsigned int cpu)
1260 {
1261         int i;
1262
1263         if (!cpumask_test_cpu(cpu, mce_dev_initialized))
1264                 return;
1265
1266         for (i = 0; mce_attrs[i]; i++)
1267                 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1268
1269         for (i = 0; i < banks; i++)
1270                 sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[i]);
1271
1272         sysdev_unregister(&per_cpu(mce_dev, cpu));
1273         cpumask_clear_cpu(cpu, mce_dev_initialized);
1274 }
1275
1276 /* Make sure there are no machine checks on offlined CPUs. */
1277 static void mce_disable_cpu(void *h)
1278 {
1279         unsigned long action = *(unsigned long *)h;
1280         int i;
1281
1282         if (!mce_available(&current_cpu_data))
1283                 return;
1284         if (!(action & CPU_TASKS_FROZEN))
1285                 cmci_clear();
1286         for (i = 0; i < banks; i++) {
1287                 if (!skip_bank_init(i))
1288                         wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1289         }
1290 }
1291
1292 static void mce_reenable_cpu(void *h)
1293 {
1294         unsigned long action = *(unsigned long *)h;
1295         int i;
1296
1297         if (!mce_available(&current_cpu_data))
1298                 return;
1299
1300         if (!(action & CPU_TASKS_FROZEN))
1301                 cmci_reenable();
1302         for (i = 0; i < banks; i++) {
1303                 if (!skip_bank_init(i))
1304                         wrmsrl(MSR_IA32_MC0_CTL + i*4, bank[i]);
1305         }
1306 }
1307
1308 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
1309 static int __cpuinit
1310 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
1311 {
1312         unsigned int cpu = (unsigned long)hcpu;
1313         struct timer_list *t = &per_cpu(mce_timer, cpu);
1314
1315         switch (action) {
1316         case CPU_ONLINE:
1317         case CPU_ONLINE_FROZEN:
1318                 mce_create_device(cpu);
1319                 if (threshold_cpu_callback)
1320                         threshold_cpu_callback(action, cpu);
1321                 break;
1322         case CPU_DEAD:
1323         case CPU_DEAD_FROZEN:
1324                 if (threshold_cpu_callback)
1325                         threshold_cpu_callback(action, cpu);
1326                 mce_remove_device(cpu);
1327                 break;
1328         case CPU_DOWN_PREPARE:
1329         case CPU_DOWN_PREPARE_FROZEN:
1330                 del_timer_sync(t);
1331                 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
1332                 break;
1333         case CPU_DOWN_FAILED:
1334         case CPU_DOWN_FAILED_FROZEN:
1335                 t->expires = round_jiffies(jiffies +
1336                                                 __get_cpu_var(next_interval));
1337                 add_timer_on(t, cpu);
1338                 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
1339                 break;
1340         case CPU_POST_DEAD:
1341                 /* intentionally ignoring frozen here */
1342                 cmci_rediscover(cpu);
1343                 break;
1344         }
1345         return NOTIFY_OK;
1346 }
1347
1348 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
1349         .notifier_call = mce_cpu_callback,
1350 };
1351
1352 static __init int mce_init_banks(void)
1353 {
1354         int i;
1355
1356         bank_attrs = kzalloc(sizeof(struct sysdev_attribute) * banks,
1357                                 GFP_KERNEL);
1358         if (!bank_attrs)
1359                 return -ENOMEM;
1360
1361         for (i = 0; i < banks; i++) {
1362                 struct sysdev_attribute *a = &bank_attrs[i];
1363
1364                 a->attr.name    = kasprintf(GFP_KERNEL, "bank%d", i);
1365                 if (!a->attr.name)
1366                         goto nomem;
1367
1368                 a->attr.mode    = 0644;
1369                 a->show         = show_bank;
1370                 a->store        = set_bank;
1371         }
1372         return 0;
1373
1374 nomem:
1375         while (--i >= 0)
1376                 kfree(bank_attrs[i].attr.name);
1377         kfree(bank_attrs);
1378         bank_attrs = NULL;
1379
1380         return -ENOMEM;
1381 }
1382
1383 static __init int mce_init_device(void)
1384 {
1385         int err;
1386         int i = 0;
1387
1388         if (!mce_available(&boot_cpu_data))
1389                 return -EIO;
1390
1391         alloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
1392
1393         err = mce_init_banks();
1394         if (err)
1395                 return err;
1396
1397         err = sysdev_class_register(&mce_sysclass);
1398         if (err)
1399                 return err;
1400
1401         for_each_online_cpu(i) {
1402                 err = mce_create_device(i);
1403                 if (err)
1404                         return err;
1405         }
1406
1407         register_hotcpu_notifier(&mce_cpu_notifier);
1408         misc_register(&mce_log_device);
1409
1410         return err;
1411 }
1412
1413 device_initcall(mce_init_device);
1414
1415 #else /* CONFIG_X86_OLD_MCE: */
1416
1417 int nr_mce_banks;
1418 EXPORT_SYMBOL_GPL(nr_mce_banks);        /* non-fatal.o */
1419
1420 /* This has to be run for each processor */
1421 void mcheck_init(struct cpuinfo_x86 *c)
1422 {
1423         if (mce_disabled == 1)
1424                 return;
1425
1426         switch (c->x86_vendor) {
1427         case X86_VENDOR_AMD:
1428                 amd_mcheck_init(c);
1429                 break;
1430
1431         case X86_VENDOR_INTEL:
1432                 if (c->x86 == 5)
1433                         intel_p5_mcheck_init(c);
1434                 if (c->x86 == 6)
1435                         intel_p6_mcheck_init(c);
1436                 if (c->x86 == 15)
1437                         intel_p4_mcheck_init(c);
1438                 break;
1439
1440         case X86_VENDOR_CENTAUR:
1441                 if (c->x86 == 5)
1442                         winchip_mcheck_init(c);
1443                 break;
1444
1445         default:
1446                 break;
1447         }
1448         printk(KERN_INFO "mce: CPU supports %d MCE banks\n", nr_mce_banks);
1449 }
1450
1451 static int __init mcheck_enable(char *str)
1452 {
1453         mce_disabled = -1;
1454         return 1;
1455 }
1456
1457 __setup("mce", mcheck_enable);
1458
1459 #endif /* CONFIG_X86_OLD_MCE */
1460
1461 /*
1462  * Old style boot options parsing. Only for compatibility.
1463  */
1464 static int __init mcheck_disable(char *str)
1465 {
1466         mce_disabled = 1;
1467         return 1;
1468 }
1469 __setup("nomce", mcheck_disable);