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