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