a04806e01a82423ee89c130d5f271269b14ac625
[safe/jmp/linux-2.6] / 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/interrupt.h>
14 #include <linux/ratelimit.h>
15 #include <linux/kallsyms.h>
16 #include <linux/rcupdate.h>
17 #include <linux/kobject.h>
18 #include <linux/uaccess.h>
19 #include <linux/kdebug.h>
20 #include <linux/kernel.h>
21 #include <linux/percpu.h>
22 #include <linux/string.h>
23 #include <linux/sysdev.h>
24 #include <linux/delay.h>
25 #include <linux/ctype.h>
26 #include <linux/sched.h>
27 #include <linux/sysfs.h>
28 #include <linux/types.h>
29 #include <linux/init.h>
30 #include <linux/kmod.h>
31 #include <linux/poll.h>
32 #include <linux/nmi.h>
33 #include <linux/cpu.h>
34 #include <linux/smp.h>
35 #include <linux/fs.h>
36 #include <linux/mm.h>
37
38 #include <asm/processor.h>
39 #include <asm/hw_irq.h>
40 #include <asm/apic.h>
41 #include <asm/idle.h>
42 #include <asm/ipi.h>
43 #include <asm/mce.h>
44 #include <asm/msr.h>
45
46 #include "mce-internal.h"
47
48 int mce_disabled __read_mostly;
49
50 #define MISC_MCELOG_MINOR       227
51
52 #define SPINUNIT 100    /* 100ns */
53
54 atomic_t mce_entry;
55
56 DEFINE_PER_CPU(unsigned, mce_exception_count);
57
58 /*
59  * Tolerant levels:
60  *   0: always panic on uncorrected errors, log corrected errors
61  *   1: panic or SIGBUS on uncorrected errors, log corrected errors
62  *   2: SIGBUS or log uncorrected errors (if possible), log corrected errors
63  *   3: never panic or SIGBUS, log all errors (for testing only)
64  */
65 static int                      tolerant                __read_mostly = 1;
66 static int                      banks                   __read_mostly;
67 static int                      rip_msr                 __read_mostly;
68 static int                      mce_bootlog             __read_mostly = -1;
69 static int                      monarch_timeout         __read_mostly = -1;
70 static int                      mce_panic_timeout       __read_mostly;
71 static int                      mce_dont_log_ce         __read_mostly;
72 int                             mce_cmci_disabled       __read_mostly;
73 int                             mce_ignore_ce           __read_mostly;
74 int                             mce_ser                 __read_mostly;
75
76 struct mce_bank                *mce_banks               __read_mostly;
77
78 /* User mode helper program triggered by machine check event */
79 static unsigned long            mce_need_notify;
80 static char                     mce_helper[128];
81 static char                     *mce_helper_argv[2] = { mce_helper, NULL };
82
83 static DECLARE_WAIT_QUEUE_HEAD(mce_wait);
84 static DEFINE_PER_CPU(struct mce, mces_seen);
85 static int                      cpu_missing;
86
87
88 /* MCA banks polled by the period polling timer for corrected events */
89 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
90         [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
91 };
92
93 static DEFINE_PER_CPU(struct work_struct, mce_work);
94
95 /* Do initial initialization of a struct mce */
96 void mce_setup(struct mce *m)
97 {
98         memset(m, 0, sizeof(struct mce));
99         m->cpu = m->extcpu = smp_processor_id();
100         rdtscll(m->tsc);
101         /* We hope get_seconds stays lockless */
102         m->time = get_seconds();
103         m->cpuvendor = boot_cpu_data.x86_vendor;
104         m->cpuid = cpuid_eax(1);
105 #ifdef CONFIG_SMP
106         m->socketid = cpu_data(m->extcpu).phys_proc_id;
107 #endif
108         m->apicid = cpu_data(m->extcpu).initial_apicid;
109         rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
110 }
111
112 DEFINE_PER_CPU(struct mce, injectm);
113 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
114
115 /*
116  * Lockless MCE logging infrastructure.
117  * This avoids deadlocks on printk locks without having to break locks. Also
118  * separate MCEs from kernel messages to avoid bogus bug reports.
119  */
120
121 static struct mce_log mcelog = {
122         .signature      = MCE_LOG_SIGNATURE,
123         .len            = MCE_LOG_LEN,
124         .recordlen      = sizeof(struct mce),
125 };
126
127 void mce_log(struct mce *mce)
128 {
129         unsigned next, entry;
130
131         mce->finished = 0;
132         wmb();
133         for (;;) {
134                 entry = rcu_dereference(mcelog.next);
135                 for (;;) {
136                         /*
137                          * When the buffer fills up discard new entries.
138                          * Assume that the earlier errors are the more
139                          * interesting ones:
140                          */
141                         if (entry >= MCE_LOG_LEN) {
142                                 set_bit(MCE_OVERFLOW,
143                                         (unsigned long *)&mcelog.flags);
144                                 return;
145                         }
146                         /* Old left over entry. Skip: */
147                         if (mcelog.entry[entry].finished) {
148                                 entry++;
149                                 continue;
150                         }
151                         break;
152                 }
153                 smp_rmb();
154                 next = entry + 1;
155                 if (cmpxchg(&mcelog.next, entry, next) == entry)
156                         break;
157         }
158         memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
159         wmb();
160         mcelog.entry[entry].finished = 1;
161         wmb();
162
163         mce->finished = 1;
164         set_bit(0, &mce_need_notify);
165 }
166
167 static void print_mce(struct mce *m)
168 {
169         printk(KERN_EMERG
170                "CPU %d: Machine Check Exception: %16Lx Bank %d: %016Lx\n",
171                m->extcpu, m->mcgstatus, m->bank, m->status);
172         if (m->ip) {
173                 printk(KERN_EMERG "RIP%s %02x:<%016Lx> ",
174                        !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
175                        m->cs, m->ip);
176                 if (m->cs == __KERNEL_CS)
177                         print_symbol("{%s}", m->ip);
178                 printk("\n");
179         }
180         printk(KERN_EMERG "TSC %llx ", m->tsc);
181         if (m->addr)
182                 printk("ADDR %llx ", m->addr);
183         if (m->misc)
184                 printk("MISC %llx ", m->misc);
185         printk("\n");
186         printk(KERN_EMERG "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x\n",
187                         m->cpuvendor, m->cpuid, m->time, m->socketid,
188                         m->apicid);
189 }
190
191 static void print_mce_head(void)
192 {
193         printk(KERN_EMERG "\n" KERN_EMERG "HARDWARE ERROR\n");
194 }
195
196 static void print_mce_tail(void)
197 {
198         printk(KERN_EMERG "This is not a software problem!\n"
199                KERN_EMERG "Run through mcelog --ascii to decode and contact your hardware vendor\n");
200 }
201
202 #define PANIC_TIMEOUT 5 /* 5 seconds */
203
204 static atomic_t mce_paniced;
205
206 /* Panic in progress. Enable interrupts and wait for final IPI */
207 static void wait_for_panic(void)
208 {
209         long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
210         preempt_disable();
211         local_irq_enable();
212         while (timeout-- > 0)
213                 udelay(1);
214         if (panic_timeout == 0)
215                 panic_timeout = mce_panic_timeout;
216         panic("Panicing machine check CPU died");
217 }
218
219 static void mce_panic(char *msg, struct mce *final, char *exp)
220 {
221         int i;
222
223         /*
224          * Make sure only one CPU runs in machine check panic
225          */
226         if (atomic_inc_return(&mce_paniced) > 1)
227                 wait_for_panic();
228         barrier();
229
230         bust_spinlocks(1);
231         console_verbose();
232         print_mce_head();
233         /* First print corrected ones that are still unlogged */
234         for (i = 0; i < MCE_LOG_LEN; i++) {
235                 struct mce *m = &mcelog.entry[i];
236                 if (!(m->status & MCI_STATUS_VAL))
237                         continue;
238                 if (!(m->status & MCI_STATUS_UC))
239                         print_mce(m);
240         }
241         /* Now print uncorrected but with the final one last */
242         for (i = 0; i < MCE_LOG_LEN; i++) {
243                 struct mce *m = &mcelog.entry[i];
244                 if (!(m->status & MCI_STATUS_VAL))
245                         continue;
246                 if (!(m->status & MCI_STATUS_UC))
247                         continue;
248                 if (!final || memcmp(m, final, sizeof(struct mce)))
249                         print_mce(m);
250         }
251         if (final)
252                 print_mce(final);
253         if (cpu_missing)
254                 printk(KERN_EMERG "Some CPUs didn't answer in synchronization\n");
255         print_mce_tail();
256         if (exp)
257                 printk(KERN_EMERG "Machine check: %s\n", exp);
258         if (panic_timeout == 0)
259                 panic_timeout = mce_panic_timeout;
260         panic(msg);
261 }
262
263 /* Support code for software error injection */
264
265 static int msr_to_offset(u32 msr)
266 {
267         unsigned bank = __get_cpu_var(injectm.bank);
268         if (msr == rip_msr)
269                 return offsetof(struct mce, ip);
270         if (msr == MSR_IA32_MC0_STATUS + bank*4)
271                 return offsetof(struct mce, status);
272         if (msr == MSR_IA32_MC0_ADDR + bank*4)
273                 return offsetof(struct mce, addr);
274         if (msr == MSR_IA32_MC0_MISC + bank*4)
275                 return offsetof(struct mce, misc);
276         if (msr == MSR_IA32_MCG_STATUS)
277                 return offsetof(struct mce, mcgstatus);
278         return -1;
279 }
280
281 /* MSR access wrappers used for error injection */
282 static u64 mce_rdmsrl(u32 msr)
283 {
284         u64 v;
285         if (__get_cpu_var(injectm).finished) {
286                 int offset = msr_to_offset(msr);
287                 if (offset < 0)
288                         return 0;
289                 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
290         }
291         rdmsrl(msr, v);
292         return v;
293 }
294
295 static void mce_wrmsrl(u32 msr, u64 v)
296 {
297         if (__get_cpu_var(injectm).finished) {
298                 int offset = msr_to_offset(msr);
299                 if (offset >= 0)
300                         *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
301                 return;
302         }
303         wrmsrl(msr, v);
304 }
305
306 /*
307  * Simple lockless ring to communicate PFNs from the exception handler with the
308  * process context work function. This is vastly simplified because there's
309  * only a single reader and a single writer.
310  */
311 #define MCE_RING_SIZE 16        /* we use one entry less */
312
313 struct mce_ring {
314         unsigned short start;
315         unsigned short end;
316         unsigned long ring[MCE_RING_SIZE];
317 };
318 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
319
320 /* Runs with CPU affinity in workqueue */
321 static int mce_ring_empty(void)
322 {
323         struct mce_ring *r = &__get_cpu_var(mce_ring);
324
325         return r->start == r->end;
326 }
327
328 static int mce_ring_get(unsigned long *pfn)
329 {
330         struct mce_ring *r;
331         int ret = 0;
332
333         *pfn = 0;
334         get_cpu();
335         r = &__get_cpu_var(mce_ring);
336         if (r->start == r->end)
337                 goto out;
338         *pfn = r->ring[r->start];
339         r->start = (r->start + 1) % MCE_RING_SIZE;
340         ret = 1;
341 out:
342         put_cpu();
343         return ret;
344 }
345
346 /* Always runs in MCE context with preempt off */
347 static int mce_ring_add(unsigned long pfn)
348 {
349         struct mce_ring *r = &__get_cpu_var(mce_ring);
350         unsigned next;
351
352         next = (r->end + 1) % MCE_RING_SIZE;
353         if (next == r->start)
354                 return -1;
355         r->ring[r->end] = pfn;
356         wmb();
357         r->end = next;
358         return 0;
359 }
360
361 int mce_available(struct cpuinfo_x86 *c)
362 {
363         if (mce_disabled)
364                 return 0;
365         return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
366 }
367
368 static void mce_schedule_work(void)
369 {
370         if (!mce_ring_empty()) {
371                 struct work_struct *work = &__get_cpu_var(mce_work);
372                 if (!work_pending(work))
373                         schedule_work(work);
374         }
375 }
376
377 /*
378  * Get the address of the instruction at the time of the machine check
379  * error.
380  */
381 static inline void mce_get_rip(struct mce *m, struct pt_regs *regs)
382 {
383
384         if (regs && (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV))) {
385                 m->ip = regs->ip;
386                 m->cs = regs->cs;
387         } else {
388                 m->ip = 0;
389                 m->cs = 0;
390         }
391         if (rip_msr)
392                 m->ip = mce_rdmsrl(rip_msr);
393 }
394
395 #ifdef CONFIG_X86_LOCAL_APIC 
396 /*
397  * Called after interrupts have been reenabled again
398  * when a MCE happened during an interrupts off region
399  * in the kernel.
400  */
401 asmlinkage void smp_mce_self_interrupt(struct pt_regs *regs)
402 {
403         ack_APIC_irq();
404         exit_idle();
405         irq_enter();
406         mce_notify_irq();
407         mce_schedule_work();
408         irq_exit();
409 }
410 #endif
411
412 static void mce_report_event(struct pt_regs *regs)
413 {
414         if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
415                 mce_notify_irq();
416                 /*
417                  * Triggering the work queue here is just an insurance
418                  * policy in case the syscall exit notify handler
419                  * doesn't run soon enough or ends up running on the
420                  * wrong CPU (can happen when audit sleeps)
421                  */
422                 mce_schedule_work();
423                 return;
424         }
425
426 #ifdef CONFIG_X86_LOCAL_APIC
427         /*
428          * Without APIC do not notify. The event will be picked
429          * up eventually.
430          */
431         if (!cpu_has_apic)
432                 return;
433
434         /*
435          * When interrupts are disabled we cannot use
436          * kernel services safely. Trigger an self interrupt
437          * through the APIC to instead do the notification
438          * after interrupts are reenabled again.
439          */
440         apic->send_IPI_self(MCE_SELF_VECTOR);
441
442         /*
443          * Wait for idle afterwards again so that we don't leave the
444          * APIC in a non idle state because the normal APIC writes
445          * cannot exclude us.
446          */
447         apic_wait_icr_idle();
448 #endif
449 }
450
451 DEFINE_PER_CPU(unsigned, mce_poll_count);
452
453 /*
454  * Poll for corrected events or events that happened before reset.
455  * Those are just logged through /dev/mcelog.
456  *
457  * This is executed in standard interrupt context.
458  *
459  * Note: spec recommends to panic for fatal unsignalled
460  * errors here. However this would be quite problematic --
461  * we would need to reimplement the Monarch handling and
462  * it would mess up the exclusion between exception handler
463  * and poll hander -- * so we skip this for now.
464  * These cases should not happen anyways, or only when the CPU
465  * is already totally * confused. In this case it's likely it will
466  * not fully execute the machine check handler either.
467  */
468 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
469 {
470         struct mce m;
471         int i;
472
473         __get_cpu_var(mce_poll_count)++;
474
475         mce_setup(&m);
476
477         m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
478         for (i = 0; i < banks; i++) {
479                 if (!mce_banks[i].ctl || !test_bit(i, *b))
480                         continue;
481
482                 m.misc = 0;
483                 m.addr = 0;
484                 m.bank = i;
485                 m.tsc = 0;
486
487                 barrier();
488                 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
489                 if (!(m.status & MCI_STATUS_VAL))
490                         continue;
491
492                 /*
493                  * Uncorrected or signalled events are handled by the exception
494                  * handler when it is enabled, so don't process those here.
495                  *
496                  * TBD do the same check for MCI_STATUS_EN here?
497                  */
498                 if (!(flags & MCP_UC) &&
499                     (m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)))
500                         continue;
501
502                 if (m.status & MCI_STATUS_MISCV)
503                         m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
504                 if (m.status & MCI_STATUS_ADDRV)
505                         m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
506
507                 if (!(flags & MCP_TIMESTAMP))
508                         m.tsc = 0;
509                 /*
510                  * Don't get the IP here because it's unlikely to
511                  * have anything to do with the actual error location.
512                  */
513                 if (!(flags & MCP_DONTLOG) && !mce_dont_log_ce) {
514                         mce_log(&m);
515                         add_taint(TAINT_MACHINE_CHECK);
516                 }
517
518                 /*
519                  * Clear state for this bank.
520                  */
521                 mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
522         }
523
524         /*
525          * Don't clear MCG_STATUS here because it's only defined for
526          * exceptions.
527          */
528
529         sync_core();
530 }
531 EXPORT_SYMBOL_GPL(machine_check_poll);
532
533 /*
534  * Do a quick check if any of the events requires a panic.
535  * This decides if we keep the events around or clear them.
536  */
537 static int mce_no_way_out(struct mce *m, char **msg)
538 {
539         int i;
540
541         for (i = 0; i < banks; i++) {
542                 m->status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
543                 if (mce_severity(m, tolerant, msg) >= MCE_PANIC_SEVERITY)
544                         return 1;
545         }
546         return 0;
547 }
548
549 /*
550  * Variable to establish order between CPUs while scanning.
551  * Each CPU spins initially until executing is equal its number.
552  */
553 static atomic_t mce_executing;
554
555 /*
556  * Defines order of CPUs on entry. First CPU becomes Monarch.
557  */
558 static atomic_t mce_callin;
559
560 /*
561  * Check if a timeout waiting for other CPUs happened.
562  */
563 static int mce_timed_out(u64 *t)
564 {
565         /*
566          * The others already did panic for some reason.
567          * Bail out like in a timeout.
568          * rmb() to tell the compiler that system_state
569          * might have been modified by someone else.
570          */
571         rmb();
572         if (atomic_read(&mce_paniced))
573                 wait_for_panic();
574         if (!monarch_timeout)
575                 goto out;
576         if ((s64)*t < SPINUNIT) {
577                 /* CHECKME: Make panic default for 1 too? */
578                 if (tolerant < 1)
579                         mce_panic("Timeout synchronizing machine check over CPUs",
580                                   NULL, NULL);
581                 cpu_missing = 1;
582                 return 1;
583         }
584         *t -= SPINUNIT;
585 out:
586         touch_nmi_watchdog();
587         return 0;
588 }
589
590 /*
591  * The Monarch's reign.  The Monarch is the CPU who entered
592  * the machine check handler first. It waits for the others to
593  * raise the exception too and then grades them. When any
594  * error is fatal panic. Only then let the others continue.
595  *
596  * The other CPUs entering the MCE handler will be controlled by the
597  * Monarch. They are called Subjects.
598  *
599  * This way we prevent any potential data corruption in a unrecoverable case
600  * and also makes sure always all CPU's errors are examined.
601  *
602  * Also this detects the case of an machine check event coming from outer
603  * space (not detected by any CPUs) In this case some external agent wants
604  * us to shut down, so panic too.
605  *
606  * The other CPUs might still decide to panic if the handler happens
607  * in a unrecoverable place, but in this case the system is in a semi-stable
608  * state and won't corrupt anything by itself. It's ok to let the others
609  * continue for a bit first.
610  *
611  * All the spin loops have timeouts; when a timeout happens a CPU
612  * typically elects itself to be Monarch.
613  */
614 static void mce_reign(void)
615 {
616         int cpu;
617         struct mce *m = NULL;
618         int global_worst = 0;
619         char *msg = NULL;
620         char *nmsg = NULL;
621
622         /*
623          * This CPU is the Monarch and the other CPUs have run
624          * through their handlers.
625          * Grade the severity of the errors of all the CPUs.
626          */
627         for_each_possible_cpu(cpu) {
628                 int severity = mce_severity(&per_cpu(mces_seen, cpu), tolerant,
629                                             &nmsg);
630                 if (severity > global_worst) {
631                         msg = nmsg;
632                         global_worst = severity;
633                         m = &per_cpu(mces_seen, cpu);
634                 }
635         }
636
637         /*
638          * Cannot recover? Panic here then.
639          * This dumps all the mces in the log buffer and stops the
640          * other CPUs.
641          */
642         if (m && global_worst >= MCE_PANIC_SEVERITY && tolerant < 3)
643                 mce_panic("Fatal Machine check", m, msg);
644
645         /*
646          * For UC somewhere we let the CPU who detects it handle it.
647          * Also must let continue the others, otherwise the handling
648          * CPU could deadlock on a lock.
649          */
650
651         /*
652          * No machine check event found. Must be some external
653          * source or one CPU is hung. Panic.
654          */
655         if (!m && tolerant < 3)
656                 mce_panic("Machine check from unknown source", NULL, NULL);
657
658         /*
659          * Now clear all the mces_seen so that they don't reappear on
660          * the next mce.
661          */
662         for_each_possible_cpu(cpu)
663                 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
664 }
665
666 static atomic_t global_nwo;
667
668 /*
669  * Start of Monarch synchronization. This waits until all CPUs have
670  * entered the exception handler and then determines if any of them
671  * saw a fatal event that requires panic. Then it executes them
672  * in the entry order.
673  * TBD double check parallel CPU hotunplug
674  */
675 static int mce_start(int *no_way_out)
676 {
677         int order;
678         int cpus = num_online_cpus();
679         u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
680
681         if (!timeout)
682                 return -1;
683
684         atomic_add(*no_way_out, &global_nwo);
685         /*
686          * global_nwo should be updated before mce_callin
687          */
688         smp_wmb();
689         order = atomic_inc_return(&mce_callin);
690
691         /*
692          * Wait for everyone.
693          */
694         while (atomic_read(&mce_callin) != cpus) {
695                 if (mce_timed_out(&timeout)) {
696                         atomic_set(&global_nwo, 0);
697                         return -1;
698                 }
699                 ndelay(SPINUNIT);
700         }
701
702         /*
703          * mce_callin should be read before global_nwo
704          */
705         smp_rmb();
706
707         if (order == 1) {
708                 /*
709                  * Monarch: Starts executing now, the others wait.
710                  */
711                 atomic_set(&mce_executing, 1);
712         } else {
713                 /*
714                  * Subject: Now start the scanning loop one by one in
715                  * the original callin order.
716                  * This way when there are any shared banks it will be
717                  * only seen by one CPU before cleared, avoiding duplicates.
718                  */
719                 while (atomic_read(&mce_executing) < order) {
720                         if (mce_timed_out(&timeout)) {
721                                 atomic_set(&global_nwo, 0);
722                                 return -1;
723                         }
724                         ndelay(SPINUNIT);
725                 }
726         }
727
728         /*
729          * Cache the global no_way_out state.
730          */
731         *no_way_out = atomic_read(&global_nwo);
732
733         return order;
734 }
735
736 /*
737  * Synchronize between CPUs after main scanning loop.
738  * This invokes the bulk of the Monarch processing.
739  */
740 static int mce_end(int order)
741 {
742         int ret = -1;
743         u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
744
745         if (!timeout)
746                 goto reset;
747         if (order < 0)
748                 goto reset;
749
750         /*
751          * Allow others to run.
752          */
753         atomic_inc(&mce_executing);
754
755         if (order == 1) {
756                 /* CHECKME: Can this race with a parallel hotplug? */
757                 int cpus = num_online_cpus();
758
759                 /*
760                  * Monarch: Wait for everyone to go through their scanning
761                  * loops.
762                  */
763                 while (atomic_read(&mce_executing) <= cpus) {
764                         if (mce_timed_out(&timeout))
765                                 goto reset;
766                         ndelay(SPINUNIT);
767                 }
768
769                 mce_reign();
770                 barrier();
771                 ret = 0;
772         } else {
773                 /*
774                  * Subject: Wait for Monarch to finish.
775                  */
776                 while (atomic_read(&mce_executing) != 0) {
777                         if (mce_timed_out(&timeout))
778                                 goto reset;
779                         ndelay(SPINUNIT);
780                 }
781
782                 /*
783                  * Don't reset anything. That's done by the Monarch.
784                  */
785                 return 0;
786         }
787
788         /*
789          * Reset all global state.
790          */
791 reset:
792         atomic_set(&global_nwo, 0);
793         atomic_set(&mce_callin, 0);
794         barrier();
795
796         /*
797          * Let others run again.
798          */
799         atomic_set(&mce_executing, 0);
800         return ret;
801 }
802
803 /*
804  * Check if the address reported by the CPU is in a format we can parse.
805  * It would be possible to add code for most other cases, but all would
806  * be somewhat complicated (e.g. segment offset would require an instruction
807  * parser). So only support physical addresses upto page granuality for now.
808  */
809 static int mce_usable_address(struct mce *m)
810 {
811         if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
812                 return 0;
813         if ((m->misc & 0x3f) > PAGE_SHIFT)
814                 return 0;
815         if (((m->misc >> 6) & 7) != MCM_ADDR_PHYS)
816                 return 0;
817         return 1;
818 }
819
820 static void mce_clear_state(unsigned long *toclear)
821 {
822         int i;
823
824         for (i = 0; i < banks; i++) {
825                 if (test_bit(i, toclear))
826                         mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
827         }
828 }
829
830 /*
831  * The actual machine check handler. This only handles real
832  * exceptions when something got corrupted coming in through int 18.
833  *
834  * This is executed in NMI context not subject to normal locking rules. This
835  * implies that most kernel services cannot be safely used. Don't even
836  * think about putting a printk in there!
837  *
838  * On Intel systems this is entered on all CPUs in parallel through
839  * MCE broadcast. However some CPUs might be broken beyond repair,
840  * so be always careful when synchronizing with others.
841  */
842 void do_machine_check(struct pt_regs *regs, long error_code)
843 {
844         struct mce m, *final;
845         int i;
846         int worst = 0;
847         int severity;
848         /*
849          * Establish sequential order between the CPUs entering the machine
850          * check handler.
851          */
852         int order;
853         /*
854          * If no_way_out gets set, there is no safe way to recover from this
855          * MCE.  If tolerant is cranked up, we'll try anyway.
856          */
857         int no_way_out = 0;
858         /*
859          * If kill_it gets set, there might be a way to recover from this
860          * error.
861          */
862         int kill_it = 0;
863         DECLARE_BITMAP(toclear, MAX_NR_BANKS);
864         char *msg = "Unknown";
865
866         atomic_inc(&mce_entry);
867
868         __get_cpu_var(mce_exception_count)++;
869
870         if (notify_die(DIE_NMI, "machine check", regs, error_code,
871                            18, SIGKILL) == NOTIFY_STOP)
872                 goto out;
873         if (!banks)
874                 goto out;
875
876         mce_setup(&m);
877
878         m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
879         no_way_out = mce_no_way_out(&m, &msg);
880
881         final = &__get_cpu_var(mces_seen);
882         *final = m;
883
884         barrier();
885
886         /*
887          * When no restart IP must always kill or panic.
888          */
889         if (!(m.mcgstatus & MCG_STATUS_RIPV))
890                 kill_it = 1;
891
892         /*
893          * Go through all the banks in exclusion of the other CPUs.
894          * This way we don't report duplicated events on shared banks
895          * because the first one to see it will clear it.
896          */
897         order = mce_start(&no_way_out);
898         for (i = 0; i < banks; i++) {
899                 __clear_bit(i, toclear);
900                 if (!mce_banks[i].ctl)
901                         continue;
902
903                 m.misc = 0;
904                 m.addr = 0;
905                 m.bank = i;
906
907                 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
908                 if ((m.status & MCI_STATUS_VAL) == 0)
909                         continue;
910
911                 /*
912                  * Non uncorrected or non signaled errors are handled by
913                  * machine_check_poll. Leave them alone, unless this panics.
914                  */
915                 if (!(m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
916                         !no_way_out)
917                         continue;
918
919                 /*
920                  * Set taint even when machine check was not enabled.
921                  */
922                 add_taint(TAINT_MACHINE_CHECK);
923
924                 severity = mce_severity(&m, tolerant, NULL);
925
926                 /*
927                  * When machine check was for corrected handler don't touch,
928                  * unless we're panicing.
929                  */
930                 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
931                         continue;
932                 __set_bit(i, toclear);
933                 if (severity == MCE_NO_SEVERITY) {
934                         /*
935                          * Machine check event was not enabled. Clear, but
936                          * ignore.
937                          */
938                         continue;
939                 }
940
941                 /*
942                  * Kill on action required.
943                  */
944                 if (severity == MCE_AR_SEVERITY)
945                         kill_it = 1;
946
947                 if (m.status & MCI_STATUS_MISCV)
948                         m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
949                 if (m.status & MCI_STATUS_ADDRV)
950                         m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
951
952                 /*
953                  * Action optional error. Queue address for later processing.
954                  * When the ring overflows we just ignore the AO error.
955                  * RED-PEN add some logging mechanism when
956                  * usable_address or mce_add_ring fails.
957                  * RED-PEN don't ignore overflow for tolerant == 0
958                  */
959                 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
960                         mce_ring_add(m.addr >> PAGE_SHIFT);
961
962                 mce_get_rip(&m, regs);
963                 mce_log(&m);
964
965                 if (severity > worst) {
966                         *final = m;
967                         worst = severity;
968                 }
969         }
970
971         if (!no_way_out)
972                 mce_clear_state(toclear);
973
974         /*
975          * Do most of the synchronization with other CPUs.
976          * When there's any problem use only local no_way_out state.
977          */
978         if (mce_end(order) < 0)
979                 no_way_out = worst >= MCE_PANIC_SEVERITY;
980
981         /*
982          * If we have decided that we just CAN'T continue, and the user
983          * has not set tolerant to an insane level, give up and die.
984          *
985          * This is mainly used in the case when the system doesn't
986          * support MCE broadcasting or it has been disabled.
987          */
988         if (no_way_out && tolerant < 3)
989                 mce_panic("Fatal machine check on current CPU", final, msg);
990
991         /*
992          * If the error seems to be unrecoverable, something should be
993          * done.  Try to kill as little as possible.  If we can kill just
994          * one task, do that.  If the user has set the tolerance very
995          * high, don't try to do anything at all.
996          */
997
998         if (kill_it && tolerant < 3)
999                 force_sig(SIGBUS, current);
1000
1001         /* notify userspace ASAP */
1002         set_thread_flag(TIF_MCE_NOTIFY);
1003
1004         if (worst > 0)
1005                 mce_report_event(regs);
1006         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1007 out:
1008         atomic_dec(&mce_entry);
1009         sync_core();
1010 }
1011 EXPORT_SYMBOL_GPL(do_machine_check);
1012
1013 /* dummy to break dependency. actual code is in mm/memory-failure.c */
1014 void __attribute__((weak)) memory_failure(unsigned long pfn, int vector)
1015 {
1016         printk(KERN_ERR "Action optional memory failure at %lx ignored\n", pfn);
1017 }
1018
1019 /*
1020  * Called after mce notification in process context. This code
1021  * is allowed to sleep. Call the high level VM handler to process
1022  * any corrupted pages.
1023  * Assume that the work queue code only calls this one at a time
1024  * per CPU.
1025  * Note we don't disable preemption, so this code might run on the wrong
1026  * CPU. In this case the event is picked up by the scheduled work queue.
1027  * This is merely a fast path to expedite processing in some common
1028  * cases.
1029  */
1030 void mce_notify_process(void)
1031 {
1032         unsigned long pfn;
1033         mce_notify_irq();
1034         while (mce_ring_get(&pfn))
1035                 memory_failure(pfn, MCE_VECTOR);
1036 }
1037
1038 static void mce_process_work(struct work_struct *dummy)
1039 {
1040         mce_notify_process();
1041 }
1042
1043 #ifdef CONFIG_X86_MCE_INTEL
1044 /***
1045  * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1046  * @cpu: The CPU on which the event occurred.
1047  * @status: Event status information
1048  *
1049  * This function should be called by the thermal interrupt after the
1050  * event has been processed and the decision was made to log the event
1051  * further.
1052  *
1053  * The status parameter will be saved to the 'status' field of 'struct mce'
1054  * and historically has been the register value of the
1055  * MSR_IA32_THERMAL_STATUS (Intel) msr.
1056  */
1057 void mce_log_therm_throt_event(__u64 status)
1058 {
1059         struct mce m;
1060
1061         mce_setup(&m);
1062         m.bank = MCE_THERMAL_BANK;
1063         m.status = status;
1064         mce_log(&m);
1065 }
1066 #endif /* CONFIG_X86_MCE_INTEL */
1067
1068 /*
1069  * Periodic polling timer for "silent" machine check errors.  If the
1070  * poller finds an MCE, poll 2x faster.  When the poller finds no more
1071  * errors, poll 2x slower (up to check_interval seconds).
1072  */
1073 static int check_interval = 5 * 60; /* 5 minutes */
1074
1075 static DEFINE_PER_CPU(int, next_interval); /* in jiffies */
1076 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1077
1078 static void mcheck_timer(unsigned long data)
1079 {
1080         struct timer_list *t = &per_cpu(mce_timer, data);
1081         int *n;
1082
1083         WARN_ON(smp_processor_id() != data);
1084
1085         if (mce_available(&current_cpu_data)) {
1086                 machine_check_poll(MCP_TIMESTAMP,
1087                                 &__get_cpu_var(mce_poll_banks));
1088         }
1089
1090         /*
1091          * Alert userspace if needed.  If we logged an MCE, reduce the
1092          * polling interval, otherwise increase the polling interval.
1093          */
1094         n = &__get_cpu_var(next_interval);
1095         if (mce_notify_irq())
1096                 *n = max(*n/2, HZ/100);
1097         else
1098                 *n = min(*n*2, (int)round_jiffies_relative(check_interval*HZ));
1099
1100         t->expires = jiffies + *n;
1101         add_timer(t);
1102 }
1103
1104 static void mce_do_trigger(struct work_struct *work)
1105 {
1106         call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1107 }
1108
1109 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1110
1111 /*
1112  * Notify the user(s) about new machine check events.
1113  * Can be called from interrupt context, but not from machine check/NMI
1114  * context.
1115  */
1116 int mce_notify_irq(void)
1117 {
1118         /* Not more than two messages every minute */
1119         static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1120
1121         clear_thread_flag(TIF_MCE_NOTIFY);
1122
1123         if (test_and_clear_bit(0, &mce_need_notify)) {
1124                 wake_up_interruptible(&mce_wait);
1125
1126                 /*
1127                  * There is no risk of missing notifications because
1128                  * work_pending is always cleared before the function is
1129                  * executed.
1130                  */
1131                 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1132                         schedule_work(&mce_trigger_work);
1133
1134                 if (__ratelimit(&ratelimit))
1135                         printk(KERN_INFO "Machine check events logged\n");
1136
1137                 return 1;
1138         }
1139         return 0;
1140 }
1141 EXPORT_SYMBOL_GPL(mce_notify_irq);
1142
1143 static int mce_banks_init(void)
1144 {
1145         int i;
1146
1147         mce_banks = kzalloc(banks * sizeof(struct mce_bank), GFP_KERNEL);
1148         if (!mce_banks)
1149                 return -ENOMEM;
1150         for (i = 0; i < banks; i++) {
1151                 struct mce_bank *b = &mce_banks[i];
1152                 b->ctl = -1ULL;
1153                 b->init = 1;
1154         }
1155         return 0;
1156 }
1157
1158 /*
1159  * Initialize Machine Checks for a CPU.
1160  */
1161 static int mce_cap_init(void)
1162 {
1163         unsigned b;
1164         u64 cap;
1165
1166         rdmsrl(MSR_IA32_MCG_CAP, cap);
1167
1168         b = cap & MCG_BANKCNT_MASK;
1169         printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
1170
1171         if (b > MAX_NR_BANKS) {
1172                 printk(KERN_WARNING
1173                        "MCE: Using only %u machine check banks out of %u\n",
1174                         MAX_NR_BANKS, b);
1175                 b = MAX_NR_BANKS;
1176         }
1177
1178         /* Don't support asymmetric configurations today */
1179         WARN_ON(banks != 0 && b != banks);
1180         banks = b;
1181         if (!mce_banks) {
1182                 int err = mce_banks_init();
1183                 if (err)
1184                         return err;
1185         }
1186
1187         /* Use accurate RIP reporting if available. */
1188         if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1189                 rip_msr = MSR_IA32_MCG_EIP;
1190
1191         if (cap & MCG_SER_P)
1192                 mce_ser = 1;
1193
1194         return 0;
1195 }
1196
1197 static void mce_init(void)
1198 {
1199         mce_banks_t all_banks;
1200         u64 cap;
1201         int i;
1202
1203         /*
1204          * Log the machine checks left over from the previous reset.
1205          */
1206         bitmap_fill(all_banks, MAX_NR_BANKS);
1207         machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
1208
1209         set_in_cr4(X86_CR4_MCE);
1210
1211         rdmsrl(MSR_IA32_MCG_CAP, cap);
1212         if (cap & MCG_CTL_P)
1213                 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1214
1215         for (i = 0; i < banks; i++) {
1216                 struct mce_bank *b = &mce_banks[i];
1217                 if (!b->init)
1218                         continue;
1219                 wrmsrl(MSR_IA32_MC0_CTL+4*i, b->ctl);
1220                 wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
1221         }
1222 }
1223
1224 /* Add per CPU specific workarounds here */
1225 static void mce_cpu_quirks(struct cpuinfo_x86 *c)
1226 {
1227         /* This should be disabled by the BIOS, but isn't always */
1228         if (c->x86_vendor == X86_VENDOR_AMD) {
1229                 if (c->x86 == 15 && banks > 4) {
1230                         /*
1231                          * disable GART TBL walk error reporting, which
1232                          * trips off incorrectly with the IOMMU & 3ware
1233                          * & Cerberus:
1234                          */
1235                         clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1236                 }
1237                 if (c->x86 <= 17 && mce_bootlog < 0) {
1238                         /*
1239                          * Lots of broken BIOS around that don't clear them
1240                          * by default and leave crap in there. Don't log:
1241                          */
1242                         mce_bootlog = 0;
1243                 }
1244                 /*
1245                  * Various K7s with broken bank 0 around. Always disable
1246                  * by default.
1247                  */
1248                  if (c->x86 == 6 && banks > 0)
1249                         mce_banks[0].ctl = 0;
1250         }
1251
1252         if (c->x86_vendor == X86_VENDOR_INTEL) {
1253                 /*
1254                  * SDM documents that on family 6 bank 0 should not be written
1255                  * because it aliases to another special BIOS controlled
1256                  * register.
1257                  * But it's not aliased anymore on model 0x1a+
1258                  * Don't ignore bank 0 completely because there could be a
1259                  * valid event later, merely don't write CTL0.
1260                  */
1261
1262                 if (c->x86 == 6 && c->x86_model < 0x1A && banks > 0)
1263                         mce_banks[0].init = 0;
1264
1265                 /*
1266                  * All newer Intel systems support MCE broadcasting. Enable
1267                  * synchronization with a one second timeout.
1268                  */
1269                 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1270                         monarch_timeout < 0)
1271                         monarch_timeout = USEC_PER_SEC;
1272         }
1273         if (monarch_timeout < 0)
1274                 monarch_timeout = 0;
1275         if (mce_bootlog != 0)
1276                 mce_panic_timeout = 30;
1277 }
1278
1279 static void __cpuinit mce_ancient_init(struct cpuinfo_x86 *c)
1280 {
1281         if (c->x86 != 5)
1282                 return;
1283         switch (c->x86_vendor) {
1284         case X86_VENDOR_INTEL:
1285                 intel_p5_mcheck_init(c);
1286                 break;
1287         case X86_VENDOR_CENTAUR:
1288                 winchip_mcheck_init(c);
1289                 break;
1290         }
1291 }
1292
1293 static void mce_cpu_features(struct cpuinfo_x86 *c)
1294 {
1295         switch (c->x86_vendor) {
1296         case X86_VENDOR_INTEL:
1297                 mce_intel_feature_init(c);
1298                 break;
1299         case X86_VENDOR_AMD:
1300                 mce_amd_feature_init(c);
1301                 break;
1302         default:
1303                 break;
1304         }
1305 }
1306
1307 static void mce_init_timer(void)
1308 {
1309         struct timer_list *t = &__get_cpu_var(mce_timer);
1310         int *n = &__get_cpu_var(next_interval);
1311
1312         if (mce_ignore_ce)
1313                 return;
1314
1315         *n = check_interval * HZ;
1316         if (!*n)
1317                 return;
1318         setup_timer(t, mcheck_timer, smp_processor_id());
1319         t->expires = round_jiffies(jiffies + *n);
1320         add_timer(t);
1321 }
1322
1323 /* Handle unconfigured int18 (should never happen) */
1324 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1325 {
1326         printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
1327                smp_processor_id());
1328 }
1329
1330 /* Call the installed machine check handler for this CPU setup. */
1331 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1332                                                 unexpected_machine_check;
1333
1334 /*
1335  * Called for each booted CPU to set up machine checks.
1336  * Must be called with preempt off:
1337  */
1338 void __cpuinit mcheck_init(struct cpuinfo_x86 *c)
1339 {
1340         if (mce_disabled)
1341                 return;
1342
1343         mce_ancient_init(c);
1344
1345         if (!mce_available(c))
1346                 return;
1347
1348         if (mce_cap_init() < 0) {
1349                 mce_disabled = 1;
1350                 return;
1351         }
1352         mce_cpu_quirks(c);
1353
1354         machine_check_vector = do_machine_check;
1355
1356         mce_init();
1357         mce_cpu_features(c);
1358         mce_init_timer();
1359         INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1360 }
1361
1362 /*
1363  * Character device to read and clear the MCE log.
1364  */
1365
1366 static DEFINE_SPINLOCK(mce_state_lock);
1367 static int              open_count;             /* #times opened */
1368 static int              open_exclu;             /* already open exclusive? */
1369
1370 static int mce_open(struct inode *inode, struct file *file)
1371 {
1372         spin_lock(&mce_state_lock);
1373
1374         if (open_exclu || (open_count && (file->f_flags & O_EXCL))) {
1375                 spin_unlock(&mce_state_lock);
1376
1377                 return -EBUSY;
1378         }
1379
1380         if (file->f_flags & O_EXCL)
1381                 open_exclu = 1;
1382         open_count++;
1383
1384         spin_unlock(&mce_state_lock);
1385
1386         return nonseekable_open(inode, file);
1387 }
1388
1389 static int mce_release(struct inode *inode, struct file *file)
1390 {
1391         spin_lock(&mce_state_lock);
1392
1393         open_count--;
1394         open_exclu = 0;
1395
1396         spin_unlock(&mce_state_lock);
1397
1398         return 0;
1399 }
1400
1401 static void collect_tscs(void *data)
1402 {
1403         unsigned long *cpu_tsc = (unsigned long *)data;
1404
1405         rdtscll(cpu_tsc[smp_processor_id()]);
1406 }
1407
1408 static DEFINE_MUTEX(mce_read_mutex);
1409
1410 static ssize_t mce_read(struct file *filp, char __user *ubuf, size_t usize,
1411                         loff_t *off)
1412 {
1413         char __user *buf = ubuf;
1414         unsigned long *cpu_tsc;
1415         unsigned prev, next;
1416         int i, err;
1417
1418         cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1419         if (!cpu_tsc)
1420                 return -ENOMEM;
1421
1422         mutex_lock(&mce_read_mutex);
1423         next = rcu_dereference(mcelog.next);
1424
1425         /* Only supports full reads right now */
1426         if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce)) {
1427                 mutex_unlock(&mce_read_mutex);
1428                 kfree(cpu_tsc);
1429
1430                 return -EINVAL;
1431         }
1432
1433         err = 0;
1434         prev = 0;
1435         do {
1436                 for (i = prev; i < next; i++) {
1437                         unsigned long start = jiffies;
1438
1439                         while (!mcelog.entry[i].finished) {
1440                                 if (time_after_eq(jiffies, start + 2)) {
1441                                         memset(mcelog.entry + i, 0,
1442                                                sizeof(struct mce));
1443                                         goto timeout;
1444                                 }
1445                                 cpu_relax();
1446                         }
1447                         smp_rmb();
1448                         err |= copy_to_user(buf, mcelog.entry + i,
1449                                             sizeof(struct mce));
1450                         buf += sizeof(struct mce);
1451 timeout:
1452                         ;
1453                 }
1454
1455                 memset(mcelog.entry + prev, 0,
1456                        (next - prev) * sizeof(struct mce));
1457                 prev = next;
1458                 next = cmpxchg(&mcelog.next, prev, 0);
1459         } while (next != prev);
1460
1461         synchronize_sched();
1462
1463         /*
1464          * Collect entries that were still getting written before the
1465          * synchronize.
1466          */
1467         on_each_cpu(collect_tscs, cpu_tsc, 1);
1468
1469         for (i = next; i < MCE_LOG_LEN; i++) {
1470                 if (mcelog.entry[i].finished &&
1471                     mcelog.entry[i].tsc < cpu_tsc[mcelog.entry[i].cpu]) {
1472                         err |= copy_to_user(buf, mcelog.entry+i,
1473                                             sizeof(struct mce));
1474                         smp_rmb();
1475                         buf += sizeof(struct mce);
1476                         memset(&mcelog.entry[i], 0, sizeof(struct mce));
1477                 }
1478         }
1479         mutex_unlock(&mce_read_mutex);
1480         kfree(cpu_tsc);
1481
1482         return err ? -EFAULT : buf - ubuf;
1483 }
1484
1485 static unsigned int mce_poll(struct file *file, poll_table *wait)
1486 {
1487         poll_wait(file, &mce_wait, wait);
1488         if (rcu_dereference(mcelog.next))
1489                 return POLLIN | POLLRDNORM;
1490         return 0;
1491 }
1492
1493 static long mce_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1494 {
1495         int __user *p = (int __user *)arg;
1496
1497         if (!capable(CAP_SYS_ADMIN))
1498                 return -EPERM;
1499
1500         switch (cmd) {
1501         case MCE_GET_RECORD_LEN:
1502                 return put_user(sizeof(struct mce), p);
1503         case MCE_GET_LOG_LEN:
1504                 return put_user(MCE_LOG_LEN, p);
1505         case MCE_GETCLEAR_FLAGS: {
1506                 unsigned flags;
1507
1508                 do {
1509                         flags = mcelog.flags;
1510                 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1511
1512                 return put_user(flags, p);
1513         }
1514         default:
1515                 return -ENOTTY;
1516         }
1517 }
1518
1519 /* Modified in mce-inject.c, so not static or const */
1520 struct file_operations mce_chrdev_ops = {
1521         .open                   = mce_open,
1522         .release                = mce_release,
1523         .read                   = mce_read,
1524         .poll                   = mce_poll,
1525         .unlocked_ioctl         = mce_ioctl,
1526 };
1527 EXPORT_SYMBOL_GPL(mce_chrdev_ops);
1528
1529 static struct miscdevice mce_log_device = {
1530         MISC_MCELOG_MINOR,
1531         "mcelog",
1532         &mce_chrdev_ops,
1533 };
1534
1535 /*
1536  * mce=off Disables machine check
1537  * mce=no_cmci Disables CMCI
1538  * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1539  * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1540  * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1541  *      monarchtimeout is how long to wait for other CPUs on machine
1542  *      check, or 0 to not wait
1543  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1544  * mce=nobootlog Don't log MCEs from before booting.
1545  */
1546 static int __init mcheck_enable(char *str)
1547 {
1548         if (*str == 0)
1549                 enable_p5_mce();
1550         if (*str == '=')
1551                 str++;
1552         if (!strcmp(str, "off"))
1553                 mce_disabled = 1;
1554         else if (!strcmp(str, "no_cmci"))
1555                 mce_cmci_disabled = 1;
1556         else if (!strcmp(str, "dont_log_ce"))
1557                 mce_dont_log_ce = 1;
1558         else if (!strcmp(str, "ignore_ce"))
1559                 mce_ignore_ce = 1;
1560         else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1561                 mce_bootlog = (str[0] == 'b');
1562         else if (isdigit(str[0])) {
1563                 get_option(&str, &tolerant);
1564                 if (*str == ',') {
1565                         ++str;
1566                         get_option(&str, &monarch_timeout);
1567                 }
1568         } else {
1569                 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1570                        str);
1571                 return 0;
1572         }
1573         return 1;
1574 }
1575 __setup("mce", mcheck_enable);
1576
1577 /*
1578  * Sysfs support
1579  */
1580
1581 /*
1582  * Disable machine checks on suspend and shutdown. We can't really handle
1583  * them later.
1584  */
1585 static int mce_disable(void)
1586 {
1587         int i;
1588
1589         for (i = 0; i < banks; i++) {
1590                 struct mce_bank *b = &mce_banks[i];
1591                 if (b->init)
1592                         wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1593         }
1594         return 0;
1595 }
1596
1597 static int mce_suspend(struct sys_device *dev, pm_message_t state)
1598 {
1599         return mce_disable();
1600 }
1601
1602 static int mce_shutdown(struct sys_device *dev)
1603 {
1604         return mce_disable();
1605 }
1606
1607 /*
1608  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
1609  * Only one CPU is active at this time, the others get re-added later using
1610  * CPU hotplug:
1611  */
1612 static int mce_resume(struct sys_device *dev)
1613 {
1614         mce_init();
1615         mce_cpu_features(&current_cpu_data);
1616
1617         return 0;
1618 }
1619
1620 static void mce_cpu_restart(void *data)
1621 {
1622         del_timer_sync(&__get_cpu_var(mce_timer));
1623         if (!mce_available(&current_cpu_data))
1624                 return;
1625         mce_init();
1626         mce_init_timer();
1627 }
1628
1629 /* Reinit MCEs after user configuration changes */
1630 static void mce_restart(void)
1631 {
1632         on_each_cpu(mce_cpu_restart, NULL, 1);
1633 }
1634
1635 /* Toggle features for corrected errors */
1636 static void mce_disable_ce(void *all)
1637 {
1638         if (!mce_available(&current_cpu_data))
1639                 return;
1640         if (all)
1641                 del_timer_sync(&__get_cpu_var(mce_timer));
1642         cmci_clear();
1643 }
1644
1645 static void mce_enable_ce(void *all)
1646 {
1647         if (!mce_available(&current_cpu_data))
1648                 return;
1649         cmci_reenable();
1650         cmci_recheck();
1651         if (all)
1652                 mce_init_timer();
1653 }
1654
1655 static struct sysdev_class mce_sysclass = {
1656         .suspend        = mce_suspend,
1657         .shutdown       = mce_shutdown,
1658         .resume         = mce_resume,
1659         .name           = "machinecheck",
1660 };
1661
1662 DEFINE_PER_CPU(struct sys_device, mce_dev);
1663
1664 __cpuinitdata
1665 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1666
1667 static inline struct mce_bank *attr_to_bank(struct sysdev_attribute *attr)
1668 {
1669         return container_of(attr, struct mce_bank, attr);
1670 }
1671
1672 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1673                          char *buf)
1674 {
1675         return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
1676 }
1677
1678 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1679                         const char *buf, size_t size)
1680 {
1681         u64 new;
1682
1683         if (strict_strtoull(buf, 0, &new) < 0)
1684                 return -EINVAL;
1685
1686         attr_to_bank(attr)->ctl = new;
1687         mce_restart();
1688
1689         return size;
1690 }
1691
1692 static ssize_t
1693 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1694 {
1695         strcpy(buf, mce_helper);
1696         strcat(buf, "\n");
1697         return strlen(mce_helper) + 1;
1698 }
1699
1700 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1701                                 const char *buf, size_t siz)
1702 {
1703         char *p;
1704         int len;
1705
1706         strncpy(mce_helper, buf, sizeof(mce_helper));
1707         mce_helper[sizeof(mce_helper)-1] = 0;
1708         len = strlen(mce_helper);
1709         p = strchr(mce_helper, '\n');
1710
1711         if (*p)
1712                 *p = 0;
1713
1714         return len;
1715 }
1716
1717 static ssize_t set_ignore_ce(struct sys_device *s,
1718                              struct sysdev_attribute *attr,
1719                              const char *buf, size_t size)
1720 {
1721         u64 new;
1722
1723         if (strict_strtoull(buf, 0, &new) < 0)
1724                 return -EINVAL;
1725
1726         if (mce_ignore_ce ^ !!new) {
1727                 if (new) {
1728                         /* disable ce features */
1729                         on_each_cpu(mce_disable_ce, (void *)1, 1);
1730                         mce_ignore_ce = 1;
1731                 } else {
1732                         /* enable ce features */
1733                         mce_ignore_ce = 0;
1734                         on_each_cpu(mce_enable_ce, (void *)1, 1);
1735                 }
1736         }
1737         return size;
1738 }
1739
1740 static ssize_t set_cmci_disabled(struct sys_device *s,
1741                                  struct sysdev_attribute *attr,
1742                                  const char *buf, size_t size)
1743 {
1744         u64 new;
1745
1746         if (strict_strtoull(buf, 0, &new) < 0)
1747                 return -EINVAL;
1748
1749         if (mce_cmci_disabled ^ !!new) {
1750                 if (new) {
1751                         /* disable cmci */
1752                         on_each_cpu(mce_disable_ce, NULL, 1);
1753                         mce_cmci_disabled = 1;
1754                 } else {
1755                         /* enable cmci */
1756                         mce_cmci_disabled = 0;
1757                         on_each_cpu(mce_enable_ce, NULL, 1);
1758                 }
1759         }
1760         return size;
1761 }
1762
1763 static ssize_t store_int_with_restart(struct sys_device *s,
1764                                       struct sysdev_attribute *attr,
1765                                       const char *buf, size_t size)
1766 {
1767         ssize_t ret = sysdev_store_int(s, attr, buf, size);
1768         mce_restart();
1769         return ret;
1770 }
1771
1772 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
1773 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
1774 static SYSDEV_INT_ATTR(monarch_timeout, 0644, monarch_timeout);
1775 static SYSDEV_INT_ATTR(dont_log_ce, 0644, mce_dont_log_ce);
1776
1777 static struct sysdev_ext_attribute attr_check_interval = {
1778         _SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
1779                      store_int_with_restart),
1780         &check_interval
1781 };
1782
1783 static struct sysdev_ext_attribute attr_ignore_ce = {
1784         _SYSDEV_ATTR(ignore_ce, 0644, sysdev_show_int, set_ignore_ce),
1785         &mce_ignore_ce
1786 };
1787
1788 static struct sysdev_ext_attribute attr_cmci_disabled = {
1789         _SYSDEV_ATTR(cmci_disabled, 0644, sysdev_show_int, set_cmci_disabled),
1790         &mce_cmci_disabled
1791 };
1792
1793 static struct sysdev_attribute *mce_attrs[] = {
1794         &attr_tolerant.attr,
1795         &attr_check_interval.attr,
1796         &attr_trigger,
1797         &attr_monarch_timeout.attr,
1798         &attr_dont_log_ce.attr,
1799         &attr_ignore_ce.attr,
1800         &attr_cmci_disabled.attr,
1801         NULL
1802 };
1803
1804 static cpumask_var_t mce_dev_initialized;
1805
1806 /* Per cpu sysdev init. All of the cpus still share the same ctrl bank: */
1807 static __cpuinit int mce_create_device(unsigned int cpu)
1808 {
1809         int err;
1810         int i, j;
1811
1812         if (!mce_available(&boot_cpu_data))
1813                 return -EIO;
1814
1815         memset(&per_cpu(mce_dev, cpu).kobj, 0, sizeof(struct kobject));
1816         per_cpu(mce_dev, cpu).id        = cpu;
1817         per_cpu(mce_dev, cpu).cls       = &mce_sysclass;
1818
1819         err = sysdev_register(&per_cpu(mce_dev, cpu));
1820         if (err)
1821                 return err;
1822
1823         for (i = 0; mce_attrs[i]; i++) {
1824                 err = sysdev_create_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1825                 if (err)
1826                         goto error;
1827         }
1828         for (j = 0; j < banks; j++) {
1829                 err = sysdev_create_file(&per_cpu(mce_dev, cpu),
1830                                         &mce_banks[j].attr);
1831                 if (err)
1832                         goto error2;
1833         }
1834         cpumask_set_cpu(cpu, mce_dev_initialized);
1835
1836         return 0;
1837 error2:
1838         while (--j >= 0)
1839                 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[j].attr);
1840 error:
1841         while (--i >= 0)
1842                 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[i].attr);
1843
1844         sysdev_unregister(&per_cpu(mce_dev, cpu));
1845
1846         return err;
1847 }
1848
1849 static __cpuinit void mce_remove_device(unsigned int cpu)
1850 {
1851         int i;
1852
1853         if (!cpumask_test_cpu(cpu, mce_dev_initialized))
1854                 return;
1855
1856         for (i = 0; mce_attrs[i]; i++)
1857                 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1858
1859         for (i = 0; i < banks; i++)
1860                 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[i].attr);
1861
1862         sysdev_unregister(&per_cpu(mce_dev, cpu));
1863         cpumask_clear_cpu(cpu, mce_dev_initialized);
1864 }
1865
1866 /* Make sure there are no machine checks on offlined CPUs. */
1867 static void mce_disable_cpu(void *h)
1868 {
1869         unsigned long action = *(unsigned long *)h;
1870         int i;
1871
1872         if (!mce_available(&current_cpu_data))
1873                 return;
1874         if (!(action & CPU_TASKS_FROZEN))
1875                 cmci_clear();
1876         for (i = 0; i < banks; i++) {
1877                 struct mce_bank *b = &mce_banks[i];
1878                 if (b->init)
1879                         wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1880         }
1881 }
1882
1883 static void mce_reenable_cpu(void *h)
1884 {
1885         unsigned long action = *(unsigned long *)h;
1886         int i;
1887
1888         if (!mce_available(&current_cpu_data))
1889                 return;
1890
1891         if (!(action & CPU_TASKS_FROZEN))
1892                 cmci_reenable();
1893         for (i = 0; i < banks; i++) {
1894                 struct mce_bank *b = &mce_banks[i];
1895                 if (b->init)
1896                         wrmsrl(MSR_IA32_MC0_CTL + i*4, b->ctl);
1897         }
1898 }
1899
1900 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
1901 static int __cpuinit
1902 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
1903 {
1904         unsigned int cpu = (unsigned long)hcpu;
1905         struct timer_list *t = &per_cpu(mce_timer, cpu);
1906
1907         switch (action) {
1908         case CPU_ONLINE:
1909         case CPU_ONLINE_FROZEN:
1910                 mce_create_device(cpu);
1911                 if (threshold_cpu_callback)
1912                         threshold_cpu_callback(action, cpu);
1913                 break;
1914         case CPU_DEAD:
1915         case CPU_DEAD_FROZEN:
1916                 if (threshold_cpu_callback)
1917                         threshold_cpu_callback(action, cpu);
1918                 mce_remove_device(cpu);
1919                 break;
1920         case CPU_DOWN_PREPARE:
1921         case CPU_DOWN_PREPARE_FROZEN:
1922                 del_timer_sync(t);
1923                 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
1924                 break;
1925         case CPU_DOWN_FAILED:
1926         case CPU_DOWN_FAILED_FROZEN:
1927                 t->expires = round_jiffies(jiffies +
1928                                                 __get_cpu_var(next_interval));
1929                 add_timer_on(t, cpu);
1930                 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
1931                 break;
1932         case CPU_POST_DEAD:
1933                 /* intentionally ignoring frozen here */
1934                 cmci_rediscover(cpu);
1935                 break;
1936         }
1937         return NOTIFY_OK;
1938 }
1939
1940 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
1941         .notifier_call = mce_cpu_callback,
1942 };
1943
1944 static __init void mce_init_banks(void)
1945 {
1946         int i;
1947
1948         for (i = 0; i < banks; i++) {
1949                 struct mce_bank *b = &mce_banks[i];
1950                 struct sysdev_attribute *a = &b->attr;
1951
1952                 a->attr.name    = b->attrname;
1953                 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
1954
1955                 a->attr.mode    = 0644;
1956                 a->show         = show_bank;
1957                 a->store        = set_bank;
1958         }
1959 }
1960
1961 static __init int mce_init_device(void)
1962 {
1963         int err;
1964         int i = 0;
1965
1966         if (!mce_available(&boot_cpu_data))
1967                 return -EIO;
1968
1969         zalloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
1970
1971         mce_init_banks();
1972
1973         err = sysdev_class_register(&mce_sysclass);
1974         if (err)
1975                 return err;
1976
1977         for_each_online_cpu(i) {
1978                 err = mce_create_device(i);
1979                 if (err)
1980                         return err;
1981         }
1982
1983         register_hotcpu_notifier(&mce_cpu_notifier);
1984         misc_register(&mce_log_device);
1985
1986         return err;
1987 }
1988
1989 device_initcall(mce_init_device);
1990
1991 /*
1992  * Old style boot options parsing. Only for compatibility.
1993  */
1994 static int __init mcheck_disable(char *str)
1995 {
1996         mce_disabled = 1;
1997         return 1;
1998 }
1999 __setup("nomce", mcheck_disable);