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