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