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
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>
38 #include <asm/processor.h>
39 #include <asm/hw_irq.h>
46 #include "mce-internal.h"
49 /* Handle unconfigured int18 (should never happen) */
50 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
52 printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
56 /* Call the installed machine check handler for this CPU setup. */
57 void (*machine_check_vector)(struct pt_regs *, long error_code) =
58 unexpected_machine_check;
62 #ifdef CONFIG_X86_NEW_MCE
64 #define MISC_MCELOG_MINOR 227
66 #define SPINUNIT 100 /* 100ns */
70 DEFINE_PER_CPU(unsigned, mce_exception_count);
74 * 0: always panic on uncorrected errors, log corrected errors
75 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
76 * 2: SIGBUS or log uncorrected errors (if possible), log corrected errors
77 * 3: never panic or SIGBUS, log all errors (for testing only)
79 static int tolerant = 1;
82 static unsigned long notify_user;
84 static int mce_bootlog = -1;
85 static int monarch_timeout = -1;
86 static int mce_panic_timeout;
89 static char trigger[128];
90 static char *trigger_argv[2] = { trigger, NULL };
92 static unsigned long dont_init_banks;
94 static DECLARE_WAIT_QUEUE_HEAD(mce_wait);
95 static DEFINE_PER_CPU(struct mce, mces_seen);
96 static int cpu_missing;
99 /* MCA banks polled by the period polling timer for corrected events */
100 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
101 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
104 static inline int skip_bank_init(int i)
106 return i < BITS_PER_LONG && test_bit(i, &dont_init_banks);
109 static DEFINE_PER_CPU(struct work_struct, mce_work);
111 /* Do initial initialization of a struct mce */
112 void mce_setup(struct mce *m)
114 memset(m, 0, sizeof(struct mce));
115 m->cpu = m->extcpu = smp_processor_id();
117 /* We hope get_seconds stays lockless */
118 m->time = get_seconds();
119 m->cpuvendor = boot_cpu_data.x86_vendor;
120 m->cpuid = cpuid_eax(1);
122 m->socketid = cpu_data(m->extcpu).phys_proc_id;
124 m->apicid = cpu_data(m->extcpu).initial_apicid;
125 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
128 DEFINE_PER_CPU(struct mce, injectm);
129 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
132 * Lockless MCE logging infrastructure.
133 * This avoids deadlocks on printk locks without having to break locks. Also
134 * separate MCEs from kernel messages to avoid bogus bug reports.
137 static struct mce_log mcelog = {
138 .signature = MCE_LOG_SIGNATURE,
140 .recordlen = sizeof(struct mce),
143 void mce_log(struct mce *mce)
145 unsigned next, entry;
150 entry = rcu_dereference(mcelog.next);
153 * When the buffer fills up discard new entries.
154 * Assume that the earlier errors are the more
157 if (entry >= MCE_LOG_LEN) {
158 set_bit(MCE_OVERFLOW,
159 (unsigned long *)&mcelog.flags);
162 /* Old left over entry. Skip: */
163 if (mcelog.entry[entry].finished) {
171 if (cmpxchg(&mcelog.next, entry, next) == entry)
174 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
176 mcelog.entry[entry].finished = 1;
180 set_bit(0, ¬ify_user);
183 static void print_mce(struct mce *m, int *first)
186 printk(KERN_EMERG "\n" KERN_EMERG "HARDWARE ERROR\n");
190 "CPU %d: Machine Check Exception: %16Lx Bank %d: %016Lx\n",
191 m->extcpu, m->mcgstatus, m->bank, m->status);
193 printk(KERN_EMERG "RIP%s %02x:<%016Lx> ",
194 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
196 if (m->cs == __KERNEL_CS)
197 print_symbol("{%s}", m->ip);
200 printk(KERN_EMERG "TSC %llx ", m->tsc);
202 printk("ADDR %llx ", m->addr);
204 printk("MISC %llx ", m->misc);
206 printk(KERN_EMERG "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x\n",
207 m->cpuvendor, m->cpuid, m->time, m->socketid,
211 static void print_mce_tail(void)
213 printk(KERN_EMERG "This is not a software problem!\n"
214 KERN_EMERG "Run through mcelog --ascii to decode and contact your hardware vendor\n");
217 #define PANIC_TIMEOUT 5 /* 5 seconds */
219 static atomic_t mce_paniced;
221 /* Panic in progress. Enable interrupts and wait for final IPI */
222 static void wait_for_panic(void)
224 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
227 while (timeout-- > 0)
229 if (panic_timeout == 0)
230 panic_timeout = mce_panic_timeout;
231 panic("Panicing machine check CPU died");
234 static void mce_panic(char *msg, struct mce *final, char *exp)
240 * Make sure only one CPU runs in machine check panic
242 if (atomic_add_return(1, &mce_paniced) > 1)
248 /* First print corrected ones that are still unlogged */
249 for (i = 0; i < MCE_LOG_LEN; i++) {
250 struct mce *m = &mcelog.entry[i];
251 if ((m->status & MCI_STATUS_VAL) &&
252 !(m->status & MCI_STATUS_UC))
253 print_mce(m, &first);
255 /* Now print uncorrected but with the final one last */
256 for (i = 0; i < MCE_LOG_LEN; i++) {
257 struct mce *m = &mcelog.entry[i];
258 if (!(m->status & MCI_STATUS_VAL))
260 if (!final || memcmp(m, final, sizeof(struct mce)))
261 print_mce(m, &first);
264 print_mce(final, &first);
266 printk(KERN_EMERG "Some CPUs didn't answer in synchronization\n");
269 printk(KERN_EMERG "Machine check: %s\n", exp);
270 if (panic_timeout == 0)
271 panic_timeout = mce_panic_timeout;
275 /* Support code for software error injection */
277 static int msr_to_offset(u32 msr)
279 unsigned bank = __get_cpu_var(injectm.bank);
281 return offsetof(struct mce, ip);
282 if (msr == MSR_IA32_MC0_STATUS + bank*4)
283 return offsetof(struct mce, status);
284 if (msr == MSR_IA32_MC0_ADDR + bank*4)
285 return offsetof(struct mce, addr);
286 if (msr == MSR_IA32_MC0_MISC + bank*4)
287 return offsetof(struct mce, misc);
288 if (msr == MSR_IA32_MCG_STATUS)
289 return offsetof(struct mce, mcgstatus);
293 /* MSR access wrappers used for error injection */
294 static u64 mce_rdmsrl(u32 msr)
297 if (__get_cpu_var(injectm).finished) {
298 int offset = msr_to_offset(msr);
301 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
307 static void mce_wrmsrl(u32 msr, u64 v)
309 if (__get_cpu_var(injectm).finished) {
310 int offset = msr_to_offset(msr);
312 *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
319 * Simple lockless ring to communicate PFNs from the exception handler with the
320 * process context work function. This is vastly simplified because there's
321 * only a single reader and a single writer.
323 #define MCE_RING_SIZE 16 /* we use one entry less */
326 unsigned short start;
328 unsigned long ring[MCE_RING_SIZE];
330 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
332 /* Runs with CPU affinity in workqueue */
333 static int mce_ring_empty(void)
335 struct mce_ring *r = &__get_cpu_var(mce_ring);
337 return r->start == r->end;
340 static int mce_ring_get(unsigned long *pfn)
347 r = &__get_cpu_var(mce_ring);
348 if (r->start == r->end)
350 *pfn = r->ring[r->start];
351 r->start = (r->start + 1) % MCE_RING_SIZE;
358 /* Always runs in MCE context with preempt off */
359 static int mce_ring_add(unsigned long pfn)
361 struct mce_ring *r = &__get_cpu_var(mce_ring);
364 next = (r->end + 1) % MCE_RING_SIZE;
365 if (next == r->start)
367 r->ring[r->end] = pfn;
373 int mce_available(struct cpuinfo_x86 *c)
377 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
380 static void mce_schedule_work(void)
382 if (!mce_ring_empty()) {
383 struct work_struct *work = &__get_cpu_var(mce_work);
384 if (!work_pending(work))
390 * Get the address of the instruction at the time of the machine check
393 static inline void mce_get_rip(struct mce *m, struct pt_regs *regs)
396 if (regs && (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV))) {
404 m->ip = mce_rdmsrl(rip_msr);
407 #ifdef CONFIG_X86_LOCAL_APIC
409 * Called after interrupts have been reenabled again
410 * when a MCE happened during an interrupts off region
413 asmlinkage void smp_mce_self_interrupt(struct pt_regs *regs)
424 static void mce_report_event(struct pt_regs *regs)
426 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
429 * Triggering the work queue here is just an insurance
430 * policy in case the syscall exit notify handler
431 * doesn't run soon enough or ends up running on the
432 * wrong CPU (can happen when audit sleeps)
438 #ifdef CONFIG_X86_LOCAL_APIC
440 * Without APIC do not notify. The event will be picked
447 * When interrupts are disabled we cannot use
448 * kernel services safely. Trigger an self interrupt
449 * through the APIC to instead do the notification
450 * after interrupts are reenabled again.
452 apic->send_IPI_self(MCE_SELF_VECTOR);
455 * Wait for idle afterwards again so that we don't leave the
456 * APIC in a non idle state because the normal APIC writes
459 apic_wait_icr_idle();
463 DEFINE_PER_CPU(unsigned, mce_poll_count);
466 * Poll for corrected events or events that happened before reset.
467 * Those are just logged through /dev/mcelog.
469 * This is executed in standard interrupt context.
471 * Note: spec recommends to panic for fatal unsignalled
472 * errors here. However this would be quite problematic --
473 * we would need to reimplement the Monarch handling and
474 * it would mess up the exclusion between exception handler
475 * and poll hander -- * so we skip this for now.
476 * These cases should not happen anyways, or only when the CPU
477 * is already totally * confused. In this case it's likely it will
478 * not fully execute the machine check handler either.
480 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
485 __get_cpu_var(mce_poll_count)++;
489 m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
490 for (i = 0; i < banks; i++) {
491 if (!bank[i] || !test_bit(i, *b))
500 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
501 if (!(m.status & MCI_STATUS_VAL))
505 * Uncorrected or signalled events are handled by the exception
506 * handler when it is enabled, so don't process those here.
508 * TBD do the same check for MCI_STATUS_EN here?
510 if (!(flags & MCP_UC) &&
511 (m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)))
514 if (m.status & MCI_STATUS_MISCV)
515 m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
516 if (m.status & MCI_STATUS_ADDRV)
517 m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
519 if (!(flags & MCP_TIMESTAMP))
522 * Don't get the IP here because it's unlikely to
523 * have anything to do with the actual error location.
525 if (!(flags & MCP_DONTLOG)) {
527 add_taint(TAINT_MACHINE_CHECK);
531 * Clear state for this bank.
533 mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
537 * Don't clear MCG_STATUS here because it's only defined for
543 EXPORT_SYMBOL_GPL(machine_check_poll);
546 * Do a quick check if any of the events requires a panic.
547 * This decides if we keep the events around or clear them.
549 static int mce_no_way_out(struct mce *m, char **msg)
553 for (i = 0; i < banks; i++) {
554 m->status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
555 if (mce_severity(m, tolerant, msg) >= MCE_PANIC_SEVERITY)
562 * Variable to establish order between CPUs while scanning.
563 * Each CPU spins initially until executing is equal its number.
565 static atomic_t mce_executing;
568 * Defines order of CPUs on entry. First CPU becomes Monarch.
570 static atomic_t mce_callin;
573 * Check if a timeout waiting for other CPUs happened.
575 static int mce_timed_out(u64 *t)
578 * The others already did panic for some reason.
579 * Bail out like in a timeout.
580 * rmb() to tell the compiler that system_state
581 * might have been modified by someone else.
584 if (atomic_read(&mce_paniced))
586 if (!monarch_timeout)
588 if ((s64)*t < SPINUNIT) {
589 /* CHECKME: Make panic default for 1 too? */
591 mce_panic("Timeout synchronizing machine check over CPUs",
598 touch_nmi_watchdog();
603 * The Monarch's reign. The Monarch is the CPU who entered
604 * the machine check handler first. It waits for the others to
605 * raise the exception too and then grades them. When any
606 * error is fatal panic. Only then let the others continue.
608 * The other CPUs entering the MCE handler will be controlled by the
609 * Monarch. They are called Subjects.
611 * This way we prevent any potential data corruption in a unrecoverable case
612 * and also makes sure always all CPU's errors are examined.
614 * Also this detects the case of an machine check event coming from outer
615 * space (not detected by any CPUs) In this case some external agent wants
616 * us to shut down, so panic too.
618 * The other CPUs might still decide to panic if the handler happens
619 * in a unrecoverable place, but in this case the system is in a semi-stable
620 * state and won't corrupt anything by itself. It's ok to let the others
621 * continue for a bit first.
623 * All the spin loops have timeouts; when a timeout happens a CPU
624 * typically elects itself to be Monarch.
626 static void mce_reign(void)
629 struct mce *m = NULL;
630 int global_worst = 0;
635 * This CPU is the Monarch and the other CPUs have run
636 * through their handlers.
637 * Grade the severity of the errors of all the CPUs.
639 for_each_possible_cpu(cpu) {
640 int severity = mce_severity(&per_cpu(mces_seen, cpu), tolerant,
642 if (severity > global_worst) {
644 global_worst = severity;
645 m = &per_cpu(mces_seen, cpu);
650 * Cannot recover? Panic here then.
651 * This dumps all the mces in the log buffer and stops the
654 if (m && global_worst >= MCE_PANIC_SEVERITY && tolerant < 3)
655 mce_panic("Fatal Machine check", m, msg);
658 * For UC somewhere we let the CPU who detects it handle it.
659 * Also must let continue the others, otherwise the handling
660 * CPU could deadlock on a lock.
664 * No machine check event found. Must be some external
665 * source or one CPU is hung. Panic.
667 if (!m && tolerant < 3)
668 mce_panic("Machine check from unknown source", NULL, NULL);
671 * Now clear all the mces_seen so that they don't reappear on
674 for_each_possible_cpu(cpu)
675 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
678 static atomic_t global_nwo;
681 * Start of Monarch synchronization. This waits until all CPUs have
682 * entered the exception handler and then determines if any of them
683 * saw a fatal event that requires panic. Then it executes them
684 * in the entry order.
685 * TBD double check parallel CPU hotunplug
687 static int mce_start(int no_way_out, int *order)
690 int cpus = num_online_cpus();
691 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
698 atomic_add(no_way_out, &global_nwo);
703 while (atomic_read(&mce_callin) != cpus) {
704 if (mce_timed_out(&timeout)) {
705 atomic_set(&global_nwo, 0);
713 * Cache the global no_way_out state.
715 nwo = atomic_read(&global_nwo);
718 * Monarch starts executing now, the others wait.
721 atomic_set(&mce_executing, 1);
726 * Now start the scanning loop one by one
727 * in the original callin order.
728 * This way when there are any shared banks it will
729 * be only seen by one CPU before cleared, avoiding duplicates.
731 while (atomic_read(&mce_executing) < *order) {
732 if (mce_timed_out(&timeout)) {
733 atomic_set(&global_nwo, 0);
743 * Synchronize between CPUs after main scanning loop.
744 * This invokes the bulk of the Monarch processing.
746 static int mce_end(int order)
749 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
757 * Allow others to run.
759 atomic_inc(&mce_executing);
762 /* CHECKME: Can this race with a parallel hotplug? */
763 int cpus = num_online_cpus();
766 * Monarch: Wait for everyone to go through their scanning
769 while (atomic_read(&mce_executing) <= cpus) {
770 if (mce_timed_out(&timeout))
780 * Subject: Wait for Monarch to finish.
782 while (atomic_read(&mce_executing) != 0) {
783 if (mce_timed_out(&timeout))
789 * Don't reset anything. That's done by the Monarch.
795 * Reset all global state.
798 atomic_set(&global_nwo, 0);
799 atomic_set(&mce_callin, 0);
803 * Let others run again.
805 atomic_set(&mce_executing, 0);
810 * Check if the address reported by the CPU is in a format we can parse.
811 * It would be possible to add code for most other cases, but all would
812 * be somewhat complicated (e.g. segment offset would require an instruction
813 * parser). So only support physical addresses upto page granuality for now.
815 static int mce_usable_address(struct mce *m)
817 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
819 if ((m->misc & 0x3f) > PAGE_SHIFT)
821 if (((m->misc >> 6) & 7) != MCM_ADDR_PHYS)
826 static void mce_clear_state(unsigned long *toclear)
830 for (i = 0; i < banks; i++) {
831 if (test_bit(i, toclear))
832 mce_wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
837 * The actual machine check handler. This only handles real
838 * exceptions when something got corrupted coming in through int 18.
840 * This is executed in NMI context not subject to normal locking rules. This
841 * implies that most kernel services cannot be safely used. Don't even
842 * think about putting a printk in there!
844 * On Intel systems this is entered on all CPUs in parallel through
845 * MCE broadcast. However some CPUs might be broken beyond repair,
846 * so be always careful when synchronizing with others.
848 void do_machine_check(struct pt_regs *regs, long error_code)
850 struct mce m, *final;
855 * Establish sequential order between the CPUs entering the machine
861 * If no_way_out gets set, there is no safe way to recover from this
862 * MCE. If tolerant is cranked up, we'll try anyway.
866 * If kill_it gets set, there might be a way to recover from this
870 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
871 char *msg = "Unknown";
873 atomic_inc(&mce_entry);
875 __get_cpu_var(mce_exception_count)++;
877 if (notify_die(DIE_NMI, "machine check", regs, error_code,
878 18, SIGKILL) == NOTIFY_STOP)
883 order = atomic_add_return(1, &mce_callin);
886 m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
887 no_way_out = mce_no_way_out(&m, &msg);
889 final = &__get_cpu_var(mces_seen);
895 * When no restart IP must always kill or panic.
897 if (!(m.mcgstatus & MCG_STATUS_RIPV))
901 * Go through all the banks in exclusion of the other CPUs.
902 * This way we don't report duplicated events on shared banks
903 * because the first one to see it will clear it.
905 no_way_out = mce_start(no_way_out, &order);
906 for (i = 0; i < banks; i++) {
907 __clear_bit(i, toclear);
915 m.status = mce_rdmsrl(MSR_IA32_MC0_STATUS + i*4);
916 if ((m.status & MCI_STATUS_VAL) == 0)
920 * Non uncorrected or non signaled errors are handled by
921 * machine_check_poll. Leave them alone, unless this panics.
923 if (!(m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
928 * Set taint even when machine check was not enabled.
930 add_taint(TAINT_MACHINE_CHECK);
932 severity = mce_severity(&m, tolerant, NULL);
935 * When machine check was for corrected handler don't touch,
936 * unless we're panicing.
938 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
940 __set_bit(i, toclear);
941 if (severity == MCE_NO_SEVERITY) {
943 * Machine check event was not enabled. Clear, but
950 * Kill on action required.
952 if (severity == MCE_AR_SEVERITY)
955 if (m.status & MCI_STATUS_MISCV)
956 m.misc = mce_rdmsrl(MSR_IA32_MC0_MISC + i*4);
957 if (m.status & MCI_STATUS_ADDRV)
958 m.addr = mce_rdmsrl(MSR_IA32_MC0_ADDR + i*4);
961 * Action optional error. Queue address for later processing.
962 * When the ring overflows we just ignore the AO error.
963 * RED-PEN add some logging mechanism when
964 * usable_address or mce_add_ring fails.
965 * RED-PEN don't ignore overflow for tolerant == 0
967 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
968 mce_ring_add(m.addr >> PAGE_SHIFT);
970 mce_get_rip(&m, regs);
973 if (severity > worst) {
980 mce_clear_state(toclear);
983 * Do most of the synchronization with other CPUs.
984 * When there's any problem use only local no_way_out state.
986 if (mce_end(order) < 0)
987 no_way_out = worst >= MCE_PANIC_SEVERITY;
990 * If we have decided that we just CAN'T continue, and the user
991 * has not set tolerant to an insane level, give up and die.
993 * This is mainly used in the case when the system doesn't
994 * support MCE broadcasting or it has been disabled.
996 if (no_way_out && tolerant < 3)
997 mce_panic("Fatal machine check on current CPU", final, msg);
1000 * If the error seems to be unrecoverable, something should be
1001 * done. Try to kill as little as possible. If we can kill just
1002 * one task, do that. If the user has set the tolerance very
1003 * high, don't try to do anything at all.
1006 if (kill_it && tolerant < 3)
1007 force_sig(SIGBUS, current);
1009 /* notify userspace ASAP */
1010 set_thread_flag(TIF_MCE_NOTIFY);
1013 mce_report_event(regs);
1014 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1016 atomic_dec(&mce_entry);
1019 EXPORT_SYMBOL_GPL(do_machine_check);
1021 /* dummy to break dependency. actual code is in mm/memory-failure.c */
1022 void __attribute__((weak)) memory_failure(unsigned long pfn, int vector)
1024 printk(KERN_ERR "Action optional memory failure at %lx ignored\n", pfn);
1028 * Called after mce notification in process context. This code
1029 * is allowed to sleep. Call the high level VM handler to process
1030 * any corrupted pages.
1031 * Assume that the work queue code only calls this one at a time
1033 * Note we don't disable preemption, so this code might run on the wrong
1034 * CPU. In this case the event is picked up by the scheduled work queue.
1035 * This is merely a fast path to expedite processing in some common
1038 void mce_notify_process(void)
1042 while (mce_ring_get(&pfn))
1043 memory_failure(pfn, MCE_VECTOR);
1046 static void mce_process_work(struct work_struct *dummy)
1048 mce_notify_process();
1051 #ifdef CONFIG_X86_MCE_INTEL
1053 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1054 * @cpu: The CPU on which the event occurred.
1055 * @status: Event status information
1057 * This function should be called by the thermal interrupt after the
1058 * event has been processed and the decision was made to log the event
1061 * The status parameter will be saved to the 'status' field of 'struct mce'
1062 * and historically has been the register value of the
1063 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1065 void mce_log_therm_throt_event(__u64 status)
1070 m.bank = MCE_THERMAL_BANK;
1074 #endif /* CONFIG_X86_MCE_INTEL */
1077 * Periodic polling timer for "silent" machine check errors. If the
1078 * poller finds an MCE, poll 2x faster. When the poller finds no more
1079 * errors, poll 2x slower (up to check_interval seconds).
1081 static int check_interval = 5 * 60; /* 5 minutes */
1083 static DEFINE_PER_CPU(int, next_interval); /* in jiffies */
1084 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1086 static void mcheck_timer(unsigned long data)
1088 struct timer_list *t = &per_cpu(mce_timer, data);
1091 WARN_ON(smp_processor_id() != data);
1093 if (mce_available(¤t_cpu_data)) {
1094 machine_check_poll(MCP_TIMESTAMP,
1095 &__get_cpu_var(mce_poll_banks));
1099 * Alert userspace if needed. If we logged an MCE, reduce the
1100 * polling interval, otherwise increase the polling interval.
1102 n = &__get_cpu_var(next_interval);
1103 if (mce_notify_irq())
1104 *n = max(*n/2, HZ/100);
1106 *n = min(*n*2, (int)round_jiffies_relative(check_interval*HZ));
1108 t->expires = jiffies + *n;
1112 static void mce_do_trigger(struct work_struct *work)
1114 call_usermodehelper(trigger, trigger_argv, NULL, UMH_NO_WAIT);
1117 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1120 * Notify the user(s) about new machine check events.
1121 * Can be called from interrupt context, but not from machine check/NMI
1124 int mce_notify_irq(void)
1126 /* Not more than two messages every minute */
1127 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1129 clear_thread_flag(TIF_MCE_NOTIFY);
1131 if (test_and_clear_bit(0, ¬ify_user)) {
1132 wake_up_interruptible(&mce_wait);
1135 * There is no risk of missing notifications because
1136 * work_pending is always cleared before the function is
1139 if (trigger[0] && !work_pending(&mce_trigger_work))
1140 schedule_work(&mce_trigger_work);
1142 if (__ratelimit(&ratelimit))
1143 printk(KERN_INFO "Machine check events logged\n");
1149 EXPORT_SYMBOL_GPL(mce_notify_irq);
1152 * Initialize Machine Checks for a CPU.
1154 static int mce_cap_init(void)
1159 rdmsrl(MSR_IA32_MCG_CAP, cap);
1161 b = cap & MCG_BANKCNT_MASK;
1162 printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
1164 if (b > MAX_NR_BANKS) {
1166 "MCE: Using only %u machine check banks out of %u\n",
1171 /* Don't support asymmetric configurations today */
1172 WARN_ON(banks != 0 && b != banks);
1175 bank = kmalloc(banks * sizeof(u64), GFP_KERNEL);
1178 memset(bank, 0xff, banks * sizeof(u64));
1181 /* Use accurate RIP reporting if available. */
1182 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1183 rip_msr = MSR_IA32_MCG_EIP;
1185 if (cap & MCG_SER_P)
1191 static void mce_init(void)
1193 mce_banks_t all_banks;
1198 * Log the machine checks left over from the previous reset.
1200 bitmap_fill(all_banks, MAX_NR_BANKS);
1201 machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
1203 set_in_cr4(X86_CR4_MCE);
1205 rdmsrl(MSR_IA32_MCG_CAP, cap);
1206 if (cap & MCG_CTL_P)
1207 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1209 for (i = 0; i < banks; i++) {
1210 if (skip_bank_init(i))
1212 wrmsrl(MSR_IA32_MC0_CTL+4*i, bank[i]);
1213 wrmsrl(MSR_IA32_MC0_STATUS+4*i, 0);
1217 /* Add per CPU specific workarounds here */
1218 static void mce_cpu_quirks(struct cpuinfo_x86 *c)
1220 /* This should be disabled by the BIOS, but isn't always */
1221 if (c->x86_vendor == X86_VENDOR_AMD) {
1222 if (c->x86 == 15 && banks > 4) {
1224 * disable GART TBL walk error reporting, which
1225 * trips off incorrectly with the IOMMU & 3ware
1228 clear_bit(10, (unsigned long *)&bank[4]);
1230 if (c->x86 <= 17 && mce_bootlog < 0) {
1232 * Lots of broken BIOS around that don't clear them
1233 * by default and leave crap in there. Don't log:
1238 * Various K7s with broken bank 0 around. Always disable
1245 if (c->x86_vendor == X86_VENDOR_INTEL) {
1247 * SDM documents that on family 6 bank 0 should not be written
1248 * because it aliases to another special BIOS controlled
1250 * But it's not aliased anymore on model 0x1a+
1251 * Don't ignore bank 0 completely because there could be a
1252 * valid event later, merely don't write CTL0.
1255 if (c->x86 == 6 && c->x86_model < 0x1A)
1256 __set_bit(0, &dont_init_banks);
1259 * All newer Intel systems support MCE broadcasting. Enable
1260 * synchronization with a one second timeout.
1262 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1263 monarch_timeout < 0)
1264 monarch_timeout = USEC_PER_SEC;
1266 if (monarch_timeout < 0)
1267 monarch_timeout = 0;
1268 if (mce_bootlog != 0)
1269 mce_panic_timeout = 30;
1272 static void __cpuinit mce_ancient_init(struct cpuinfo_x86 *c)
1276 switch (c->x86_vendor) {
1277 case X86_VENDOR_INTEL:
1278 if (mce_p5_enabled())
1279 intel_p5_mcheck_init(c);
1281 case X86_VENDOR_CENTAUR:
1282 winchip_mcheck_init(c);
1287 static void mce_cpu_features(struct cpuinfo_x86 *c)
1289 switch (c->x86_vendor) {
1290 case X86_VENDOR_INTEL:
1291 mce_intel_feature_init(c);
1293 case X86_VENDOR_AMD:
1294 mce_amd_feature_init(c);
1301 static void mce_init_timer(void)
1303 struct timer_list *t = &__get_cpu_var(mce_timer);
1304 int *n = &__get_cpu_var(next_interval);
1306 *n = check_interval * HZ;
1309 setup_timer(t, mcheck_timer, smp_processor_id());
1310 t->expires = round_jiffies(jiffies + *n);
1315 * Called for each booted CPU to set up machine checks.
1316 * Must be called with preempt off:
1318 void __cpuinit mcheck_init(struct cpuinfo_x86 *c)
1323 mce_ancient_init(c);
1325 if (!mce_available(c))
1328 if (mce_cap_init() < 0) {
1334 machine_check_vector = do_machine_check;
1337 mce_cpu_features(c);
1339 INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1343 * Character device to read and clear the MCE log.
1346 static DEFINE_SPINLOCK(mce_state_lock);
1347 static int open_count; /* #times opened */
1348 static int open_exclu; /* already open exclusive? */
1350 static int mce_open(struct inode *inode, struct file *file)
1352 spin_lock(&mce_state_lock);
1354 if (open_exclu || (open_count && (file->f_flags & O_EXCL))) {
1355 spin_unlock(&mce_state_lock);
1360 if (file->f_flags & O_EXCL)
1364 spin_unlock(&mce_state_lock);
1366 return nonseekable_open(inode, file);
1369 static int mce_release(struct inode *inode, struct file *file)
1371 spin_lock(&mce_state_lock);
1376 spin_unlock(&mce_state_lock);
1381 static void collect_tscs(void *data)
1383 unsigned long *cpu_tsc = (unsigned long *)data;
1385 rdtscll(cpu_tsc[smp_processor_id()]);
1388 static DEFINE_MUTEX(mce_read_mutex);
1390 static ssize_t mce_read(struct file *filp, char __user *ubuf, size_t usize,
1393 char __user *buf = ubuf;
1394 unsigned long *cpu_tsc;
1395 unsigned prev, next;
1398 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1402 mutex_lock(&mce_read_mutex);
1403 next = rcu_dereference(mcelog.next);
1405 /* Only supports full reads right now */
1406 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce)) {
1407 mutex_unlock(&mce_read_mutex);
1416 for (i = prev; i < next; i++) {
1417 unsigned long start = jiffies;
1419 while (!mcelog.entry[i].finished) {
1420 if (time_after_eq(jiffies, start + 2)) {
1421 memset(mcelog.entry + i, 0,
1422 sizeof(struct mce));
1428 err |= copy_to_user(buf, mcelog.entry + i,
1429 sizeof(struct mce));
1430 buf += sizeof(struct mce);
1435 memset(mcelog.entry + prev, 0,
1436 (next - prev) * sizeof(struct mce));
1438 next = cmpxchg(&mcelog.next, prev, 0);
1439 } while (next != prev);
1441 synchronize_sched();
1444 * Collect entries that were still getting written before the
1447 on_each_cpu(collect_tscs, cpu_tsc, 1);
1449 for (i = next; i < MCE_LOG_LEN; i++) {
1450 if (mcelog.entry[i].finished &&
1451 mcelog.entry[i].tsc < cpu_tsc[mcelog.entry[i].cpu]) {
1452 err |= copy_to_user(buf, mcelog.entry+i,
1453 sizeof(struct mce));
1455 buf += sizeof(struct mce);
1456 memset(&mcelog.entry[i], 0, sizeof(struct mce));
1459 mutex_unlock(&mce_read_mutex);
1462 return err ? -EFAULT : buf - ubuf;
1465 static unsigned int mce_poll(struct file *file, poll_table *wait)
1467 poll_wait(file, &mce_wait, wait);
1468 if (rcu_dereference(mcelog.next))
1469 return POLLIN | POLLRDNORM;
1473 static long mce_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1475 int __user *p = (int __user *)arg;
1477 if (!capable(CAP_SYS_ADMIN))
1481 case MCE_GET_RECORD_LEN:
1482 return put_user(sizeof(struct mce), p);
1483 case MCE_GET_LOG_LEN:
1484 return put_user(MCE_LOG_LEN, p);
1485 case MCE_GETCLEAR_FLAGS: {
1489 flags = mcelog.flags;
1490 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1492 return put_user(flags, p);
1499 /* Modified in mce-inject.c, so not static or const */
1500 struct file_operations mce_chrdev_ops = {
1502 .release = mce_release,
1505 .unlocked_ioctl = mce_ioctl,
1507 EXPORT_SYMBOL_GPL(mce_chrdev_ops);
1509 static struct miscdevice mce_log_device = {
1516 * mce=off disables machine check
1517 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1518 * monarchtimeout is how long to wait for other CPUs on machine
1519 * check, or 0 to not wait
1520 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1521 * mce=nobootlog Don't log MCEs from before booting.
1523 static int __init mcheck_enable(char *str)
1529 if (!strcmp(str, "off"))
1531 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1532 mce_bootlog = (str[0] == 'b');
1533 else if (isdigit(str[0])) {
1534 get_option(&str, &tolerant);
1537 get_option(&str, &monarch_timeout);
1540 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1546 __setup("mce", mcheck_enable);
1553 * Disable machine checks on suspend and shutdown. We can't really handle
1556 static int mce_disable(void)
1560 for (i = 0; i < banks; i++) {
1561 if (!skip_bank_init(i))
1562 wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1567 static int mce_suspend(struct sys_device *dev, pm_message_t state)
1569 return mce_disable();
1572 static int mce_shutdown(struct sys_device *dev)
1574 return mce_disable();
1578 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
1579 * Only one CPU is active at this time, the others get re-added later using
1582 static int mce_resume(struct sys_device *dev)
1585 mce_cpu_features(¤t_cpu_data);
1590 static void mce_cpu_restart(void *data)
1592 del_timer_sync(&__get_cpu_var(mce_timer));
1593 if (mce_available(¤t_cpu_data))
1598 /* Reinit MCEs after user configuration changes */
1599 static void mce_restart(void)
1601 on_each_cpu(mce_cpu_restart, NULL, 1);
1604 static struct sysdev_class mce_sysclass = {
1605 .suspend = mce_suspend,
1606 .shutdown = mce_shutdown,
1607 .resume = mce_resume,
1608 .name = "machinecheck",
1611 DEFINE_PER_CPU(struct sys_device, mce_dev);
1614 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1616 static struct sysdev_attribute *bank_attrs;
1618 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1621 u64 b = bank[attr - bank_attrs];
1623 return sprintf(buf, "%llx\n", b);
1626 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1627 const char *buf, size_t size)
1631 if (strict_strtoull(buf, 0, &new) < 0)
1634 bank[attr - bank_attrs] = new;
1641 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1643 strcpy(buf, trigger);
1645 return strlen(trigger) + 1;
1648 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1649 const char *buf, size_t siz)
1654 strncpy(trigger, buf, sizeof(trigger));
1655 trigger[sizeof(trigger)-1] = 0;
1656 len = strlen(trigger);
1657 p = strchr(trigger, '\n');
1665 static ssize_t store_int_with_restart(struct sys_device *s,
1666 struct sysdev_attribute *attr,
1667 const char *buf, size_t size)
1669 ssize_t ret = sysdev_store_int(s, attr, buf, size);
1674 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
1675 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
1676 static SYSDEV_INT_ATTR(monarch_timeout, 0644, monarch_timeout);
1678 static struct sysdev_ext_attribute attr_check_interval = {
1679 _SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
1680 store_int_with_restart),
1684 static struct sysdev_attribute *mce_attrs[] = {
1685 &attr_tolerant.attr, &attr_check_interval.attr, &attr_trigger,
1686 &attr_monarch_timeout.attr,
1690 static cpumask_var_t mce_dev_initialized;
1692 /* Per cpu sysdev init. All of the cpus still share the same ctrl bank: */
1693 static __cpuinit int mce_create_device(unsigned int cpu)
1698 if (!mce_available(&boot_cpu_data))
1701 memset(&per_cpu(mce_dev, cpu).kobj, 0, sizeof(struct kobject));
1702 per_cpu(mce_dev, cpu).id = cpu;
1703 per_cpu(mce_dev, cpu).cls = &mce_sysclass;
1705 err = sysdev_register(&per_cpu(mce_dev, cpu));
1709 for (i = 0; mce_attrs[i]; i++) {
1710 err = sysdev_create_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1714 for (i = 0; i < banks; i++) {
1715 err = sysdev_create_file(&per_cpu(mce_dev, cpu),
1720 cpumask_set_cpu(cpu, mce_dev_initialized);
1725 sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[i]);
1728 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1730 sysdev_unregister(&per_cpu(mce_dev, cpu));
1735 static __cpuinit void mce_remove_device(unsigned int cpu)
1739 if (!cpumask_test_cpu(cpu, mce_dev_initialized))
1742 for (i = 0; mce_attrs[i]; i++)
1743 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1745 for (i = 0; i < banks; i++)
1746 sysdev_remove_file(&per_cpu(mce_dev, cpu), &bank_attrs[i]);
1748 sysdev_unregister(&per_cpu(mce_dev, cpu));
1749 cpumask_clear_cpu(cpu, mce_dev_initialized);
1752 /* Make sure there are no machine checks on offlined CPUs. */
1753 static void mce_disable_cpu(void *h)
1755 unsigned long action = *(unsigned long *)h;
1758 if (!mce_available(¤t_cpu_data))
1760 if (!(action & CPU_TASKS_FROZEN))
1762 for (i = 0; i < banks; i++) {
1763 if (!skip_bank_init(i))
1764 wrmsrl(MSR_IA32_MC0_CTL + i*4, 0);
1768 static void mce_reenable_cpu(void *h)
1770 unsigned long action = *(unsigned long *)h;
1773 if (!mce_available(¤t_cpu_data))
1776 if (!(action & CPU_TASKS_FROZEN))
1778 for (i = 0; i < banks; i++) {
1779 if (!skip_bank_init(i))
1780 wrmsrl(MSR_IA32_MC0_CTL + i*4, bank[i]);
1784 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
1785 static int __cpuinit
1786 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
1788 unsigned int cpu = (unsigned long)hcpu;
1789 struct timer_list *t = &per_cpu(mce_timer, cpu);
1793 case CPU_ONLINE_FROZEN:
1794 mce_create_device(cpu);
1795 if (threshold_cpu_callback)
1796 threshold_cpu_callback(action, cpu);
1799 case CPU_DEAD_FROZEN:
1800 if (threshold_cpu_callback)
1801 threshold_cpu_callback(action, cpu);
1802 mce_remove_device(cpu);
1804 case CPU_DOWN_PREPARE:
1805 case CPU_DOWN_PREPARE_FROZEN:
1807 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
1809 case CPU_DOWN_FAILED:
1810 case CPU_DOWN_FAILED_FROZEN:
1811 t->expires = round_jiffies(jiffies +
1812 __get_cpu_var(next_interval));
1813 add_timer_on(t, cpu);
1814 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
1817 /* intentionally ignoring frozen here */
1818 cmci_rediscover(cpu);
1824 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
1825 .notifier_call = mce_cpu_callback,
1828 static __init int mce_init_banks(void)
1832 bank_attrs = kzalloc(sizeof(struct sysdev_attribute) * banks,
1837 for (i = 0; i < banks; i++) {
1838 struct sysdev_attribute *a = &bank_attrs[i];
1840 a->attr.name = kasprintf(GFP_KERNEL, "bank%d", i);
1844 a->attr.mode = 0644;
1845 a->show = show_bank;
1846 a->store = set_bank;
1852 kfree(bank_attrs[i].attr.name);
1859 static __init int mce_init_device(void)
1864 if (!mce_available(&boot_cpu_data))
1867 alloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
1869 err = mce_init_banks();
1873 err = sysdev_class_register(&mce_sysclass);
1877 for_each_online_cpu(i) {
1878 err = mce_create_device(i);
1883 register_hotcpu_notifier(&mce_cpu_notifier);
1884 misc_register(&mce_log_device);
1889 device_initcall(mce_init_device);
1891 #else /* CONFIG_X86_OLD_MCE: */
1894 EXPORT_SYMBOL_GPL(nr_mce_banks); /* non-fatal.o */
1896 /* This has to be run for each processor */
1897 void mcheck_init(struct cpuinfo_x86 *c)
1899 if (mce_disabled == 1)
1902 switch (c->x86_vendor) {
1903 case X86_VENDOR_AMD:
1907 case X86_VENDOR_INTEL:
1909 intel_p5_mcheck_init(c);
1911 intel_p6_mcheck_init(c);
1913 intel_p4_mcheck_init(c);
1916 case X86_VENDOR_CENTAUR:
1918 winchip_mcheck_init(c);
1924 printk(KERN_INFO "mce: CPU supports %d MCE banks\n", nr_mce_banks);
1927 static int __init mcheck_enable(char *str)
1933 __setup("mce", mcheck_enable);
1935 #endif /* CONFIG_X86_OLD_MCE */
1938 * Old style boot options parsing. Only for compatibility.
1940 static int __init mcheck_disable(char *str)
1945 __setup("nomce", mcheck_disable);