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