x86: mce: macros to compute banks MSRs
[linux-2.6/mini2440.git] / arch / x86 / kernel / cpu / mcheck / mce.c
blob07139a0578e3b8004d500500a7a2514518ef61bf
1 /*
2 * Machine check handler.
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>
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>
46 #include "mce-internal.h"
48 int mce_disabled __read_mostly;
50 #define MISC_MCELOG_MINOR 227
52 #define SPINUNIT 100 /* 100ns */
54 atomic_t mce_entry;
56 DEFINE_PER_CPU(unsigned, mce_exception_count);
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)
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;
76 struct mce_bank *mce_banks __read_mostly;
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 };
83 static DECLARE_WAIT_QUEUE_HEAD(mce_wait);
84 static DEFINE_PER_CPU(struct mce, mces_seen);
85 static int cpu_missing;
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
93 static DEFINE_PER_CPU(struct work_struct, mce_work);
95 /* Do initial initialization of a struct mce */
96 void mce_setup(struct mce *m)
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);
112 DEFINE_PER_CPU(struct mce, injectm);
113 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
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.
121 static struct mce_log mcelog = {
122 .signature = MCE_LOG_SIGNATURE,
123 .len = MCE_LOG_LEN,
124 .recordlen = sizeof(struct mce),
127 void mce_log(struct mce *mce)
129 unsigned next, entry;
131 mce->finished = 0;
132 wmb();
133 for (;;) {
134 entry = rcu_dereference(mcelog.next);
135 for (;;) {
137 * When the buffer fills up discard new entries.
138 * Assume that the earlier errors are the more
139 * interesting ones:
141 if (entry >= MCE_LOG_LEN) {
142 set_bit(MCE_OVERFLOW,
143 (unsigned long *)&mcelog.flags);
144 return;
146 /* Old left over entry. Skip: */
147 if (mcelog.entry[entry].finished) {
148 entry++;
149 continue;
151 break;
153 smp_rmb();
154 next = entry + 1;
155 if (cmpxchg(&mcelog.next, entry, next) == entry)
156 break;
158 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
159 wmb();
160 mcelog.entry[entry].finished = 1;
161 wmb();
163 mce->finished = 1;
164 set_bit(0, &mce_need_notify);
167 static void print_mce(struct mce *m)
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");
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);
191 static void print_mce_head(void)
193 printk(KERN_EMERG "\n" KERN_EMERG "HARDWARE ERROR\n");
196 static void print_mce_tail(void)
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");
202 #define PANIC_TIMEOUT 5 /* 5 seconds */
204 static atomic_t mce_paniced;
206 /* Panic in progress. Enable interrupts and wait for final IPI */
207 static void wait_for_panic(void)
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");
219 static void mce_panic(char *msg, struct mce *final, char *exp)
221 int i;
224 * Make sure only one CPU runs in machine check panic
226 if (atomic_inc_return(&mce_paniced) > 1)
227 wait_for_panic();
228 barrier();
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);
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);
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);
263 /* Support code for software error injection */
265 static int msr_to_offset(u32 msr)
267 unsigned bank = __get_cpu_var(injectm.bank);
268 if (msr == rip_msr)
269 return offsetof(struct mce, ip);
270 if (msr == MSR_IA32_MCx_STATUS(bank))
271 return offsetof(struct mce, status);
272 if (msr == MSR_IA32_MCx_ADDR(bank))
273 return offsetof(struct mce, addr);
274 if (msr == MSR_IA32_MCx_MISC(bank))
275 return offsetof(struct mce, misc);
276 if (msr == MSR_IA32_MCG_STATUS)
277 return offsetof(struct mce, mcgstatus);
278 return -1;
281 /* MSR access wrappers used for error injection */
282 static u64 mce_rdmsrl(u32 msr)
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);
291 rdmsrl(msr, v);
292 return v;
295 static void mce_wrmsrl(u32 msr, u64 v)
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;
303 wrmsrl(msr, v);
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.
311 #define MCE_RING_SIZE 16 /* we use one entry less */
313 struct mce_ring {
314 unsigned short start;
315 unsigned short end;
316 unsigned long ring[MCE_RING_SIZE];
318 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
320 /* Runs with CPU affinity in workqueue */
321 static int mce_ring_empty(void)
323 struct mce_ring *r = &__get_cpu_var(mce_ring);
325 return r->start == r->end;
328 static int mce_ring_get(unsigned long *pfn)
330 struct mce_ring *r;
331 int ret = 0;
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;
346 /* Always runs in MCE context with preempt off */
347 static int mce_ring_add(unsigned long pfn)
349 struct mce_ring *r = &__get_cpu_var(mce_ring);
350 unsigned next;
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;
361 int mce_available(struct cpuinfo_x86 *c)
363 if (mce_disabled)
364 return 0;
365 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
368 static void mce_schedule_work(void)
370 if (!mce_ring_empty()) {
371 struct work_struct *work = &__get_cpu_var(mce_work);
372 if (!work_pending(work))
373 schedule_work(work);
378 * Get the address of the instruction at the time of the machine check
379 * error.
381 static inline void mce_get_rip(struct mce *m, struct pt_regs *regs)
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;
391 if (rip_msr)
392 m->ip = mce_rdmsrl(rip_msr);
395 #ifdef CONFIG_X86_LOCAL_APIC
397 * Called after interrupts have been reenabled again
398 * when a MCE happened during an interrupts off region
399 * in the kernel.
401 asmlinkage void smp_mce_self_interrupt(struct pt_regs *regs)
403 ack_APIC_irq();
404 exit_idle();
405 irq_enter();
406 mce_notify_irq();
407 mce_schedule_work();
408 irq_exit();
410 #endif
412 static void mce_report_event(struct pt_regs *regs)
414 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
415 mce_notify_irq();
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)
422 mce_schedule_work();
423 return;
426 #ifdef CONFIG_X86_LOCAL_APIC
428 * Without APIC do not notify. The event will be picked
429 * up eventually.
431 if (!cpu_has_apic)
432 return;
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.
440 apic->send_IPI_self(MCE_SELF_VECTOR);
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.
447 apic_wait_icr_idle();
448 #endif
451 DEFINE_PER_CPU(unsigned, mce_poll_count);
454 * Poll for corrected events or events that happened before reset.
455 * Those are just logged through /dev/mcelog.
457 * This is executed in standard interrupt context.
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.
468 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
470 struct mce m;
471 int i;
473 __get_cpu_var(mce_poll_count)++;
475 mce_setup(&m);
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;
482 m.misc = 0;
483 m.addr = 0;
484 m.bank = i;
485 m.tsc = 0;
487 barrier();
488 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
489 if (!(m.status & MCI_STATUS_VAL))
490 continue;
493 * Uncorrected or signalled events are handled by the exception
494 * handler when it is enabled, so don't process those here.
496 * TBD do the same check for MCI_STATUS_EN here?
498 if (!(flags & MCP_UC) &&
499 (m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)))
500 continue;
502 if (m.status & MCI_STATUS_MISCV)
503 m.misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
504 if (m.status & MCI_STATUS_ADDRV)
505 m.addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
507 if (!(flags & MCP_TIMESTAMP))
508 m.tsc = 0;
510 * Don't get the IP here because it's unlikely to
511 * have anything to do with the actual error location.
513 if (!(flags & MCP_DONTLOG) && !mce_dont_log_ce) {
514 mce_log(&m);
515 add_taint(TAINT_MACHINE_CHECK);
519 * Clear state for this bank.
521 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
525 * Don't clear MCG_STATUS here because it's only defined for
526 * exceptions.
529 sync_core();
531 EXPORT_SYMBOL_GPL(machine_check_poll);
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.
537 static int mce_no_way_out(struct mce *m, char **msg)
539 int i;
541 for (i = 0; i < banks; i++) {
542 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
543 if (mce_severity(m, tolerant, msg) >= MCE_PANIC_SEVERITY)
544 return 1;
546 return 0;
550 * Variable to establish order between CPUs while scanning.
551 * Each CPU spins initially until executing is equal its number.
553 static atomic_t mce_executing;
556 * Defines order of CPUs on entry. First CPU becomes Monarch.
558 static atomic_t mce_callin;
561 * Check if a timeout waiting for other CPUs happened.
563 static int mce_timed_out(u64 *t)
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.
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;
584 *t -= SPINUNIT;
585 out:
586 touch_nmi_watchdog();
587 return 0;
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.
596 * The other CPUs entering the MCE handler will be controlled by the
597 * Monarch. They are called Subjects.
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.
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.
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.
611 * All the spin loops have timeouts; when a timeout happens a CPU
612 * typically elects itself to be Monarch.
614 static void mce_reign(void)
616 int cpu;
617 struct mce *m = NULL;
618 int global_worst = 0;
619 char *msg = NULL;
620 char *nmsg = NULL;
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.
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);
638 * Cannot recover? Panic here then.
639 * This dumps all the mces in the log buffer and stops the
640 * other CPUs.
642 if (m && global_worst >= MCE_PANIC_SEVERITY && tolerant < 3)
643 mce_panic("Fatal Machine check", m, msg);
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.
652 * No machine check event found. Must be some external
653 * source or one CPU is hung. Panic.
655 if (!m && tolerant < 3)
656 mce_panic("Machine check from unknown source", NULL, NULL);
659 * Now clear all the mces_seen so that they don't reappear on
660 * the next mce.
662 for_each_possible_cpu(cpu)
663 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
666 static atomic_t global_nwo;
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
675 static int mce_start(int *no_way_out)
677 int order;
678 int cpus = num_online_cpus();
679 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
681 if (!timeout)
682 return -1;
684 atomic_add(*no_way_out, &global_nwo);
686 * global_nwo should be updated before mce_callin
688 smp_wmb();
689 order = atomic_inc_return(&mce_callin);
692 * Wait for everyone.
694 while (atomic_read(&mce_callin) != cpus) {
695 if (mce_timed_out(&timeout)) {
696 atomic_set(&global_nwo, 0);
697 return -1;
699 ndelay(SPINUNIT);
703 * mce_callin should be read before global_nwo
705 smp_rmb();
707 if (order == 1) {
709 * Monarch: Starts executing now, the others wait.
711 atomic_set(&mce_executing, 1);
712 } else {
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.
719 while (atomic_read(&mce_executing) < order) {
720 if (mce_timed_out(&timeout)) {
721 atomic_set(&global_nwo, 0);
722 return -1;
724 ndelay(SPINUNIT);
729 * Cache the global no_way_out state.
731 *no_way_out = atomic_read(&global_nwo);
733 return order;
737 * Synchronize between CPUs after main scanning loop.
738 * This invokes the bulk of the Monarch processing.
740 static int mce_end(int order)
742 int ret = -1;
743 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
745 if (!timeout)
746 goto reset;
747 if (order < 0)
748 goto reset;
751 * Allow others to run.
753 atomic_inc(&mce_executing);
755 if (order == 1) {
756 /* CHECKME: Can this race with a parallel hotplug? */
757 int cpus = num_online_cpus();
760 * Monarch: Wait for everyone to go through their scanning
761 * loops.
763 while (atomic_read(&mce_executing) <= cpus) {
764 if (mce_timed_out(&timeout))
765 goto reset;
766 ndelay(SPINUNIT);
769 mce_reign();
770 barrier();
771 ret = 0;
772 } else {
774 * Subject: Wait for Monarch to finish.
776 while (atomic_read(&mce_executing) != 0) {
777 if (mce_timed_out(&timeout))
778 goto reset;
779 ndelay(SPINUNIT);
783 * Don't reset anything. That's done by the Monarch.
785 return 0;
789 * Reset all global state.
791 reset:
792 atomic_set(&global_nwo, 0);
793 atomic_set(&mce_callin, 0);
794 barrier();
797 * Let others run again.
799 atomic_set(&mce_executing, 0);
800 return ret;
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.
809 static int mce_usable_address(struct mce *m)
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;
820 static void mce_clear_state(unsigned long *toclear)
822 int i;
824 for (i = 0; i < banks; i++) {
825 if (test_bit(i, toclear))
826 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
831 * The actual machine check handler. This only handles real
832 * exceptions when something got corrupted coming in through int 18.
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!
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.
842 void do_machine_check(struct pt_regs *regs, long error_code)
844 struct mce m, *final;
845 int i;
846 int worst = 0;
847 int severity;
849 * Establish sequential order between the CPUs entering the machine
850 * check handler.
852 int order;
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.
857 int no_way_out = 0;
859 * If kill_it gets set, there might be a way to recover from this
860 * error.
862 int kill_it = 0;
863 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
864 char *msg = "Unknown";
866 atomic_inc(&mce_entry);
868 __get_cpu_var(mce_exception_count)++;
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;
876 mce_setup(&m);
878 m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
879 no_way_out = mce_no_way_out(&m, &msg);
881 final = &__get_cpu_var(mces_seen);
882 *final = m;
884 barrier();
887 * When no restart IP must always kill or panic.
889 if (!(m.mcgstatus & MCG_STATUS_RIPV))
890 kill_it = 1;
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.
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;
903 m.misc = 0;
904 m.addr = 0;
905 m.bank = i;
907 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
908 if ((m.status & MCI_STATUS_VAL) == 0)
909 continue;
912 * Non uncorrected or non signaled errors are handled by
913 * machine_check_poll. Leave them alone, unless this panics.
915 if (!(m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
916 !no_way_out)
917 continue;
920 * Set taint even when machine check was not enabled.
922 add_taint(TAINT_MACHINE_CHECK);
924 severity = mce_severity(&m, tolerant, NULL);
927 * When machine check was for corrected handler don't touch,
928 * unless we're panicing.
930 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
931 continue;
932 __set_bit(i, toclear);
933 if (severity == MCE_NO_SEVERITY) {
935 * Machine check event was not enabled. Clear, but
936 * ignore.
938 continue;
942 * Kill on action required.
944 if (severity == MCE_AR_SEVERITY)
945 kill_it = 1;
947 if (m.status & MCI_STATUS_MISCV)
948 m.misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
949 if (m.status & MCI_STATUS_ADDRV)
950 m.addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
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
959 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
960 mce_ring_add(m.addr >> PAGE_SHIFT);
962 mce_get_rip(&m, regs);
963 mce_log(&m);
965 if (severity > worst) {
966 *final = m;
967 worst = severity;
971 if (!no_way_out)
972 mce_clear_state(toclear);
975 * Do most of the synchronization with other CPUs.
976 * When there's any problem use only local no_way_out state.
978 if (mce_end(order) < 0)
979 no_way_out = worst >= MCE_PANIC_SEVERITY;
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.
985 * This is mainly used in the case when the system doesn't
986 * support MCE broadcasting or it has been disabled.
988 if (no_way_out && tolerant < 3)
989 mce_panic("Fatal machine check on current CPU", final, msg);
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.
998 if (kill_it && tolerant < 3)
999 force_sig(SIGBUS, current);
1001 /* notify userspace ASAP */
1002 set_thread_flag(TIF_MCE_NOTIFY);
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();
1011 EXPORT_SYMBOL_GPL(do_machine_check);
1013 /* dummy to break dependency. actual code is in mm/memory-failure.c */
1014 void __attribute__((weak)) memory_failure(unsigned long pfn, int vector)
1016 printk(KERN_ERR "Action optional memory failure at %lx ignored\n", pfn);
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.
1030 void mce_notify_process(void)
1032 unsigned long pfn;
1033 mce_notify_irq();
1034 while (mce_ring_get(&pfn))
1035 memory_failure(pfn, MCE_VECTOR);
1038 static void mce_process_work(struct work_struct *dummy)
1040 mce_notify_process();
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
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.
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.
1057 void mce_log_therm_throt_event(__u64 status)
1059 struct mce m;
1061 mce_setup(&m);
1062 m.bank = MCE_THERMAL_BANK;
1063 m.status = status;
1064 mce_log(&m);
1066 #endif /* CONFIG_X86_MCE_INTEL */
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).
1073 static int check_interval = 5 * 60; /* 5 minutes */
1075 static DEFINE_PER_CPU(int, next_interval); /* in jiffies */
1076 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1078 static void mcheck_timer(unsigned long data)
1080 struct timer_list *t = &per_cpu(mce_timer, data);
1081 int *n;
1083 WARN_ON(smp_processor_id() != data);
1085 if (mce_available(&current_cpu_data)) {
1086 machine_check_poll(MCP_TIMESTAMP,
1087 &__get_cpu_var(mce_poll_banks));
1091 * Alert userspace if needed. If we logged an MCE, reduce the
1092 * polling interval, otherwise increase the polling interval.
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));
1100 t->expires = jiffies + *n;
1101 add_timer(t);
1104 static void mce_do_trigger(struct work_struct *work)
1106 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1109 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
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.
1116 int mce_notify_irq(void)
1118 /* Not more than two messages every minute */
1119 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1121 clear_thread_flag(TIF_MCE_NOTIFY);
1123 if (test_and_clear_bit(0, &mce_need_notify)) {
1124 wake_up_interruptible(&mce_wait);
1127 * There is no risk of missing notifications because
1128 * work_pending is always cleared before the function is
1129 * executed.
1131 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1132 schedule_work(&mce_trigger_work);
1134 if (__ratelimit(&ratelimit))
1135 printk(KERN_INFO "Machine check events logged\n");
1137 return 1;
1139 return 0;
1141 EXPORT_SYMBOL_GPL(mce_notify_irq);
1143 static int mce_banks_init(void)
1145 int i;
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;
1155 return 0;
1159 * Initialize Machine Checks for a CPU.
1161 static int mce_cap_init(void)
1163 unsigned b;
1164 u64 cap;
1166 rdmsrl(MSR_IA32_MCG_CAP, cap);
1168 b = cap & MCG_BANKCNT_MASK;
1169 printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
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;
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;
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;
1191 if (cap & MCG_SER_P)
1192 mce_ser = 1;
1194 return 0;
1197 static void mce_init(void)
1199 mce_banks_t all_banks;
1200 u64 cap;
1201 int i;
1204 * Log the machine checks left over from the previous reset.
1206 bitmap_fill(all_banks, MAX_NR_BANKS);
1207 machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
1209 set_in_cr4(X86_CR4_MCE);
1211 rdmsrl(MSR_IA32_MCG_CAP, cap);
1212 if (cap & MCG_CTL_P)
1213 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
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_MCx_CTL(i), b->ctl);
1220 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1224 /* Add per CPU specific workarounds here */
1225 static void mce_cpu_quirks(struct cpuinfo_x86 *c)
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) {
1231 * disable GART TBL walk error reporting, which
1232 * trips off incorrectly with the IOMMU & 3ware
1233 * & Cerberus:
1235 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1237 if (c->x86 <= 17 && mce_bootlog < 0) {
1239 * Lots of broken BIOS around that don't clear them
1240 * by default and leave crap in there. Don't log:
1242 mce_bootlog = 0;
1245 * Various K7s with broken bank 0 around. Always disable
1246 * by default.
1248 if (c->x86 == 6 && banks > 0)
1249 mce_banks[0].ctl = 0;
1252 if (c->x86_vendor == X86_VENDOR_INTEL) {
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.
1262 if (c->x86 == 6 && c->x86_model < 0x1A && banks > 0)
1263 mce_banks[0].init = 0;
1266 * All newer Intel systems support MCE broadcasting. Enable
1267 * synchronization with a one second timeout.
1269 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1270 monarch_timeout < 0)
1271 monarch_timeout = USEC_PER_SEC;
1273 if (monarch_timeout < 0)
1274 monarch_timeout = 0;
1275 if (mce_bootlog != 0)
1276 mce_panic_timeout = 30;
1279 static void __cpuinit mce_ancient_init(struct cpuinfo_x86 *c)
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;
1293 static void mce_cpu_features(struct cpuinfo_x86 *c)
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;
1307 static void mce_init_timer(void)
1309 struct timer_list *t = &__get_cpu_var(mce_timer);
1310 int *n = &__get_cpu_var(next_interval);
1312 if (mce_ignore_ce)
1313 return;
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);
1323 /* Handle unconfigured int18 (should never happen) */
1324 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1326 printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
1327 smp_processor_id());
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;
1335 * Called for each booted CPU to set up machine checks.
1336 * Must be called with preempt off:
1338 void __cpuinit mcheck_init(struct cpuinfo_x86 *c)
1340 if (mce_disabled)
1341 return;
1343 mce_ancient_init(c);
1345 if (!mce_available(c))
1346 return;
1348 if (mce_cap_init() < 0) {
1349 mce_disabled = 1;
1350 return;
1352 mce_cpu_quirks(c);
1354 machine_check_vector = do_machine_check;
1356 mce_init();
1357 mce_cpu_features(c);
1358 mce_init_timer();
1359 INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1363 * Character device to read and clear the MCE log.
1366 static DEFINE_SPINLOCK(mce_state_lock);
1367 static int open_count; /* #times opened */
1368 static int open_exclu; /* already open exclusive? */
1370 static int mce_open(struct inode *inode, struct file *file)
1372 spin_lock(&mce_state_lock);
1374 if (open_exclu || (open_count && (file->f_flags & O_EXCL))) {
1375 spin_unlock(&mce_state_lock);
1377 return -EBUSY;
1380 if (file->f_flags & O_EXCL)
1381 open_exclu = 1;
1382 open_count++;
1384 spin_unlock(&mce_state_lock);
1386 return nonseekable_open(inode, file);
1389 static int mce_release(struct inode *inode, struct file *file)
1391 spin_lock(&mce_state_lock);
1393 open_count--;
1394 open_exclu = 0;
1396 spin_unlock(&mce_state_lock);
1398 return 0;
1401 static void collect_tscs(void *data)
1403 unsigned long *cpu_tsc = (unsigned long *)data;
1405 rdtscll(cpu_tsc[smp_processor_id()]);
1408 static DEFINE_MUTEX(mce_read_mutex);
1410 static ssize_t mce_read(struct file *filp, char __user *ubuf, size_t usize,
1411 loff_t *off)
1413 char __user *buf = ubuf;
1414 unsigned long *cpu_tsc;
1415 unsigned prev, next;
1416 int i, err;
1418 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1419 if (!cpu_tsc)
1420 return -ENOMEM;
1422 mutex_lock(&mce_read_mutex);
1423 next = rcu_dereference(mcelog.next);
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);
1430 return -EINVAL;
1433 err = 0;
1434 prev = 0;
1435 do {
1436 for (i = prev; i < next; i++) {
1437 unsigned long start = jiffies;
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;
1445 cpu_relax();
1447 smp_rmb();
1448 err |= copy_to_user(buf, mcelog.entry + i,
1449 sizeof(struct mce));
1450 buf += sizeof(struct mce);
1451 timeout:
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);
1461 synchronize_sched();
1464 * Collect entries that were still getting written before the
1465 * synchronize.
1467 on_each_cpu(collect_tscs, cpu_tsc, 1);
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));
1479 mutex_unlock(&mce_read_mutex);
1480 kfree(cpu_tsc);
1482 return err ? -EFAULT : buf - ubuf;
1485 static unsigned int mce_poll(struct file *file, poll_table *wait)
1487 poll_wait(file, &mce_wait, wait);
1488 if (rcu_dereference(mcelog.next))
1489 return POLLIN | POLLRDNORM;
1490 return 0;
1493 static long mce_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1495 int __user *p = (int __user *)arg;
1497 if (!capable(CAP_SYS_ADMIN))
1498 return -EPERM;
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;
1508 do {
1509 flags = mcelog.flags;
1510 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1512 return put_user(flags, p);
1514 default:
1515 return -ENOTTY;
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,
1527 EXPORT_SYMBOL_GPL(mce_chrdev_ops);
1529 static struct miscdevice mce_log_device = {
1530 MISC_MCELOG_MINOR,
1531 "mcelog",
1532 &mce_chrdev_ops,
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.
1546 static int __init mcheck_enable(char *str)
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);
1568 } else {
1569 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1570 str);
1571 return 0;
1573 return 1;
1575 __setup("mce", mcheck_enable);
1578 * Sysfs support
1582 * Disable machine checks on suspend and shutdown. We can't really handle
1583 * them later.
1585 static int mce_disable(void)
1587 int i;
1589 for (i = 0; i < banks; i++) {
1590 struct mce_bank *b = &mce_banks[i];
1591 if (b->init)
1592 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
1594 return 0;
1597 static int mce_suspend(struct sys_device *dev, pm_message_t state)
1599 return mce_disable();
1602 static int mce_shutdown(struct sys_device *dev)
1604 return mce_disable();
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:
1612 static int mce_resume(struct sys_device *dev)
1614 mce_init();
1615 mce_cpu_features(&current_cpu_data);
1617 return 0;
1620 static void mce_cpu_restart(void *data)
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();
1629 /* Reinit MCEs after user configuration changes */
1630 static void mce_restart(void)
1632 on_each_cpu(mce_cpu_restart, NULL, 1);
1635 /* Toggle features for corrected errors */
1636 static void mce_disable_ce(void *all)
1638 if (!mce_available(&current_cpu_data))
1639 return;
1640 if (all)
1641 del_timer_sync(&__get_cpu_var(mce_timer));
1642 cmci_clear();
1645 static void mce_enable_ce(void *all)
1647 if (!mce_available(&current_cpu_data))
1648 return;
1649 cmci_reenable();
1650 cmci_recheck();
1651 if (all)
1652 mce_init_timer();
1655 static struct sysdev_class mce_sysclass = {
1656 .suspend = mce_suspend,
1657 .shutdown = mce_shutdown,
1658 .resume = mce_resume,
1659 .name = "machinecheck",
1662 DEFINE_PER_CPU(struct sys_device, mce_dev);
1664 __cpuinitdata
1665 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1667 static inline struct mce_bank *attr_to_bank(struct sysdev_attribute *attr)
1669 return container_of(attr, struct mce_bank, attr);
1672 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1673 char *buf)
1675 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
1678 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1679 const char *buf, size_t size)
1681 u64 new;
1683 if (strict_strtoull(buf, 0, &new) < 0)
1684 return -EINVAL;
1686 attr_to_bank(attr)->ctl = new;
1687 mce_restart();
1689 return size;
1692 static ssize_t
1693 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1695 strcpy(buf, mce_helper);
1696 strcat(buf, "\n");
1697 return strlen(mce_helper) + 1;
1700 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1701 const char *buf, size_t siz)
1703 char *p;
1704 int len;
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');
1711 if (*p)
1712 *p = 0;
1714 return len;
1717 static ssize_t set_ignore_ce(struct sys_device *s,
1718 struct sysdev_attribute *attr,
1719 const char *buf, size_t size)
1721 u64 new;
1723 if (strict_strtoull(buf, 0, &new) < 0)
1724 return -EINVAL;
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);
1737 return size;
1740 static ssize_t set_cmci_disabled(struct sys_device *s,
1741 struct sysdev_attribute *attr,
1742 const char *buf, size_t size)
1744 u64 new;
1746 if (strict_strtoull(buf, 0, &new) < 0)
1747 return -EINVAL;
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);
1760 return size;
1763 static ssize_t store_int_with_restart(struct sys_device *s,
1764 struct sysdev_attribute *attr,
1765 const char *buf, size_t size)
1767 ssize_t ret = sysdev_store_int(s, attr, buf, size);
1768 mce_restart();
1769 return ret;
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);
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
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
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
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
1804 static cpumask_var_t mce_dev_initialized;
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)
1809 int err;
1810 int i, j;
1812 if (!mce_available(&boot_cpu_data))
1813 return -EIO;
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;
1819 err = sysdev_register(&per_cpu(mce_dev, cpu));
1820 if (err)
1821 return err;
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;
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;
1834 cpumask_set_cpu(cpu, mce_dev_initialized);
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);
1844 sysdev_unregister(&per_cpu(mce_dev, cpu));
1846 return err;
1849 static __cpuinit void mce_remove_device(unsigned int cpu)
1851 int i;
1853 if (!cpumask_test_cpu(cpu, mce_dev_initialized))
1854 return;
1856 for (i = 0; mce_attrs[i]; i++)
1857 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1859 for (i = 0; i < banks; i++)
1860 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[i].attr);
1862 sysdev_unregister(&per_cpu(mce_dev, cpu));
1863 cpumask_clear_cpu(cpu, mce_dev_initialized);
1866 /* Make sure there are no machine checks on offlined CPUs. */
1867 static void mce_disable_cpu(void *h)
1869 unsigned long action = *(unsigned long *)h;
1870 int i;
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_MCx_CTL(i), 0);
1883 static void mce_reenable_cpu(void *h)
1885 unsigned long action = *(unsigned long *)h;
1886 int i;
1888 if (!mce_available(&current_cpu_data))
1889 return;
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_MCx_CTL(i), b->ctl);
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)
1904 unsigned int cpu = (unsigned long)hcpu;
1905 struct timer_list *t = &per_cpu(mce_timer, cpu);
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;
1937 return NOTIFY_OK;
1940 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
1941 .notifier_call = mce_cpu_callback,
1944 static __init void mce_init_banks(void)
1946 int i;
1948 for (i = 0; i < banks; i++) {
1949 struct mce_bank *b = &mce_banks[i];
1950 struct sysdev_attribute *a = &b->attr;
1952 a->attr.name = b->attrname;
1953 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
1955 a->attr.mode = 0644;
1956 a->show = show_bank;
1957 a->store = set_bank;
1961 static __init int mce_init_device(void)
1963 int err;
1964 int i = 0;
1966 if (!mce_available(&boot_cpu_data))
1967 return -EIO;
1969 zalloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
1971 mce_init_banks();
1973 err = sysdev_class_register(&mce_sysclass);
1974 if (err)
1975 return err;
1977 for_each_online_cpu(i) {
1978 err = mce_create_device(i);
1979 if (err)
1980 return err;
1983 register_hotcpu_notifier(&mce_cpu_notifier);
1984 misc_register(&mce_log_device);
1986 return err;
1989 device_initcall(mce_init_device);
1992 * Old style boot options parsing. Only for compatibility.
1994 static int __init mcheck_disable(char *str)
1996 mce_disabled = 1;
1997 return 1;
1999 __setup("nomce", mcheck_disable);