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
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/thread_info.h>
14 #include <linux/capability.h>
15 #include <linux/miscdevice.h>
16 #include <linux/ratelimit.h>
17 #include <linux/kallsyms.h>
18 #include <linux/rcupdate.h>
19 #include <linux/kobject.h>
20 #include <linux/uaccess.h>
21 #include <linux/kdebug.h>
22 #include <linux/kernel.h>
23 #include <linux/percpu.h>
24 #include <linux/string.h>
25 #include <linux/device.h>
26 #include <linux/syscore_ops.h>
27 #include <linux/delay.h>
28 #include <linux/ctype.h>
29 #include <linux/sched.h>
30 #include <linux/sysfs.h>
31 #include <linux/types.h>
32 #include <linux/slab.h>
33 #include <linux/init.h>
34 #include <linux/kmod.h>
35 #include <linux/poll.h>
36 #include <linux/nmi.h>
37 #include <linux/cpu.h>
38 #include <linux/smp.h>
41 #include <linux/debugfs.h>
42 #include <linux/irq_work.h>
43 #include <linux/export.h>
45 #include <asm/processor.h>
49 #include "mce-internal.h"
51 static DEFINE_MUTEX(mce_chrdev_read_mutex);
53 #define rcu_dereference_check_mce(p) \
54 rcu_dereference_index_check((p), \
55 rcu_read_lock_sched_held() || \
56 lockdep_is_held(&mce_chrdev_read_mutex))
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/mce.h>
61 #define SPINUNIT 100 /* 100ns */
65 DEFINE_PER_CPU(unsigned, mce_exception_count);
67 struct mce_bank *mce_banks __read_mostly;
69 struct mca_config mca_cfg __read_mostly = {
73 * 0: always panic on uncorrected errors, log corrected errors
74 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
75 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
76 * 3: never panic or SIGBUS, log all errors (for testing only)
82 /* User mode helper program triggered by machine check event */
83 static unsigned long mce_need_notify;
84 static char mce_helper[128];
85 static char *mce_helper_argv[2] = { mce_helper, NULL };
87 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
89 static DEFINE_PER_CPU(struct mce, mces_seen);
90 static int cpu_missing;
93 * MCA banks polled by the period polling timer for corrected events.
94 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
96 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
97 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
100 static DEFINE_PER_CPU(struct work_struct, mce_work);
102 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
105 * CPU/chipset specific EDAC code can register a notifier call here to print
106 * MCE errors in a human-readable form.
108 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
110 /* Do initial initialization of a struct mce */
111 void mce_setup(struct mce *m)
113 memset(m, 0, sizeof(struct mce));
114 m->cpu = m->extcpu = smp_processor_id();
116 /* We hope get_seconds stays lockless */
117 m->time = get_seconds();
118 m->cpuvendor = boot_cpu_data.x86_vendor;
119 m->cpuid = cpuid_eax(1);
120 m->socketid = cpu_data(m->extcpu).phys_proc_id;
121 m->apicid = cpu_data(m->extcpu).initial_apicid;
122 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
125 DEFINE_PER_CPU(struct mce, injectm);
126 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
129 * Lockless MCE logging infrastructure.
130 * This avoids deadlocks on printk locks without having to break locks. Also
131 * separate MCEs from kernel messages to avoid bogus bug reports.
134 static struct mce_log mcelog = {
135 .signature = MCE_LOG_SIGNATURE,
137 .recordlen = sizeof(struct mce),
140 void mce_log(struct mce *mce)
142 unsigned next, entry;
145 /* Emit the trace record: */
146 trace_mce_record(mce);
148 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, mce);
149 if (ret == NOTIFY_STOP)
155 entry = rcu_dereference_check_mce(mcelog.next);
159 * When the buffer fills up discard new entries.
160 * Assume that the earlier errors are the more
163 if (entry >= MCE_LOG_LEN) {
164 set_bit(MCE_OVERFLOW,
165 (unsigned long *)&mcelog.flags);
168 /* Old left over entry. Skip: */
169 if (mcelog.entry[entry].finished) {
177 if (cmpxchg(&mcelog.next, entry, next) == entry)
180 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
182 mcelog.entry[entry].finished = 1;
186 set_bit(0, &mce_need_notify);
189 static void drain_mcelog_buffer(void)
191 unsigned int next, i, prev = 0;
193 next = ACCESS_ONCE(mcelog.next);
198 /* drain what was logged during boot */
199 for (i = prev; i < next; i++) {
200 unsigned long start = jiffies;
201 unsigned retries = 1;
203 m = &mcelog.entry[i];
205 while (!m->finished) {
206 if (time_after_eq(jiffies, start + 2*retries))
211 if (!m->finished && retries >= 4) {
212 pr_err("skipping error being logged currently!\n");
217 atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
220 memset(mcelog.entry + prev, 0, (next - prev) * sizeof(*m));
222 next = cmpxchg(&mcelog.next, prev, 0);
223 } while (next != prev);
227 void mce_register_decode_chain(struct notifier_block *nb)
229 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
230 drain_mcelog_buffer();
232 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
234 void mce_unregister_decode_chain(struct notifier_block *nb)
236 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
238 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
240 static void print_mce(struct mce *m)
244 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
245 m->extcpu, m->mcgstatus, m->bank, m->status);
248 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
249 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
252 if (m->cs == __KERNEL_CS)
253 print_symbol("{%s}", m->ip);
257 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
259 pr_cont("ADDR %llx ", m->addr);
261 pr_cont("MISC %llx ", m->misc);
265 * Note this output is parsed by external tools and old fields
266 * should not be changed.
268 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
269 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
270 cpu_data(m->extcpu).microcode);
273 * Print out human-readable details about the MCE error,
274 * (if the CPU has an implementation for that)
276 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
277 if (ret == NOTIFY_STOP)
280 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
283 #define PANIC_TIMEOUT 5 /* 5 seconds */
285 static atomic_t mce_paniced;
287 static int fake_panic;
288 static atomic_t mce_fake_paniced;
290 /* Panic in progress. Enable interrupts and wait for final IPI */
291 static void wait_for_panic(void)
293 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
297 while (timeout-- > 0)
299 if (panic_timeout == 0)
300 panic_timeout = mca_cfg.panic_timeout;
301 panic("Panicing machine check CPU died");
304 static void mce_panic(char *msg, struct mce *final, char *exp)
310 * Make sure only one CPU runs in machine check panic
312 if (atomic_inc_return(&mce_paniced) > 1)
319 /* Don't log too much for fake panic */
320 if (atomic_inc_return(&mce_fake_paniced) > 1)
323 /* First print corrected ones that are still unlogged */
324 for (i = 0; i < MCE_LOG_LEN; i++) {
325 struct mce *m = &mcelog.entry[i];
326 if (!(m->status & MCI_STATUS_VAL))
328 if (!(m->status & MCI_STATUS_UC)) {
331 apei_err = apei_write_mce(m);
334 /* Now print uncorrected but with the final one last */
335 for (i = 0; i < MCE_LOG_LEN; i++) {
336 struct mce *m = &mcelog.entry[i];
337 if (!(m->status & MCI_STATUS_VAL))
339 if (!(m->status & MCI_STATUS_UC))
341 if (!final || memcmp(m, final, sizeof(struct mce))) {
344 apei_err = apei_write_mce(m);
350 apei_err = apei_write_mce(final);
353 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
355 pr_emerg(HW_ERR "Machine check: %s\n", exp);
357 if (panic_timeout == 0)
358 panic_timeout = mca_cfg.panic_timeout;
361 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
364 /* Support code for software error injection */
366 static int msr_to_offset(u32 msr)
368 unsigned bank = __this_cpu_read(injectm.bank);
370 if (msr == mca_cfg.rip_msr)
371 return offsetof(struct mce, ip);
372 if (msr == MSR_IA32_MCx_STATUS(bank))
373 return offsetof(struct mce, status);
374 if (msr == MSR_IA32_MCx_ADDR(bank))
375 return offsetof(struct mce, addr);
376 if (msr == MSR_IA32_MCx_MISC(bank))
377 return offsetof(struct mce, misc);
378 if (msr == MSR_IA32_MCG_STATUS)
379 return offsetof(struct mce, mcgstatus);
383 /* MSR access wrappers used for error injection */
384 static u64 mce_rdmsrl(u32 msr)
388 if (__this_cpu_read(injectm.finished)) {
389 int offset = msr_to_offset(msr);
393 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
396 if (rdmsrl_safe(msr, &v)) {
397 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
399 * Return zero in case the access faulted. This should
400 * not happen normally but can happen if the CPU does
401 * something weird, or if the code is buggy.
409 static void mce_wrmsrl(u32 msr, u64 v)
411 if (__this_cpu_read(injectm.finished)) {
412 int offset = msr_to_offset(msr);
415 *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
422 * Collect all global (w.r.t. this processor) status about this machine
423 * check into our "mce" struct so that we can use it later to assess
424 * the severity of the problem as we read per-bank specific details.
426 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
430 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
433 * Get the address of the instruction at the time of
434 * the machine check error.
436 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
441 * When in VM86 mode make the cs look like ring 3
442 * always. This is a lie, but it's better than passing
443 * the additional vm86 bit around everywhere.
445 if (v8086_mode(regs))
448 /* Use accurate RIP reporting if available. */
450 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
455 * Simple lockless ring to communicate PFNs from the exception handler with the
456 * process context work function. This is vastly simplified because there's
457 * only a single reader and a single writer.
459 #define MCE_RING_SIZE 16 /* we use one entry less */
462 unsigned short start;
464 unsigned long ring[MCE_RING_SIZE];
466 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
468 /* Runs with CPU affinity in workqueue */
469 static int mce_ring_empty(void)
471 struct mce_ring *r = &__get_cpu_var(mce_ring);
473 return r->start == r->end;
476 static int mce_ring_get(unsigned long *pfn)
483 r = &__get_cpu_var(mce_ring);
484 if (r->start == r->end)
486 *pfn = r->ring[r->start];
487 r->start = (r->start + 1) % MCE_RING_SIZE;
494 /* Always runs in MCE context with preempt off */
495 static int mce_ring_add(unsigned long pfn)
497 struct mce_ring *r = &__get_cpu_var(mce_ring);
500 next = (r->end + 1) % MCE_RING_SIZE;
501 if (next == r->start)
503 r->ring[r->end] = pfn;
509 int mce_available(struct cpuinfo_x86 *c)
511 if (mca_cfg.disabled)
513 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
516 static void mce_schedule_work(void)
518 if (!mce_ring_empty())
519 schedule_work(&__get_cpu_var(mce_work));
522 DEFINE_PER_CPU(struct irq_work, mce_irq_work);
524 static void mce_irq_work_cb(struct irq_work *entry)
530 static void mce_report_event(struct pt_regs *regs)
532 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
535 * Triggering the work queue here is just an insurance
536 * policy in case the syscall exit notify handler
537 * doesn't run soon enough or ends up running on the
538 * wrong CPU (can happen when audit sleeps)
544 irq_work_queue(&__get_cpu_var(mce_irq_work));
548 * Read ADDR and MISC registers.
550 static void mce_read_aux(struct mce *m, int i)
552 if (m->status & MCI_STATUS_MISCV)
553 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
554 if (m->status & MCI_STATUS_ADDRV) {
555 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
558 * Mask the reported address by the reported granularity.
560 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
561 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
568 DEFINE_PER_CPU(unsigned, mce_poll_count);
571 * Poll for corrected events or events that happened before reset.
572 * Those are just logged through /dev/mcelog.
574 * This is executed in standard interrupt context.
576 * Note: spec recommends to panic for fatal unsignalled
577 * errors here. However this would be quite problematic --
578 * we would need to reimplement the Monarch handling and
579 * it would mess up the exclusion between exception handler
580 * and poll hander -- * so we skip this for now.
581 * These cases should not happen anyways, or only when the CPU
582 * is already totally * confused. In this case it's likely it will
583 * not fully execute the machine check handler either.
585 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
590 this_cpu_inc(mce_poll_count);
592 mce_gather_info(&m, NULL);
594 for (i = 0; i < mca_cfg.banks; i++) {
595 if (!mce_banks[i].ctl || !test_bit(i, *b))
604 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
605 if (!(m.status & MCI_STATUS_VAL))
609 * Uncorrected or signalled events are handled by the exception
610 * handler when it is enabled, so don't process those here.
612 * TBD do the same check for MCI_STATUS_EN here?
614 if (!(flags & MCP_UC) &&
615 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
620 if (!(flags & MCP_TIMESTAMP))
623 * Don't get the IP here because it's unlikely to
624 * have anything to do with the actual error location.
626 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
630 * Clear state for this bank.
632 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
636 * Don't clear MCG_STATUS here because it's only defined for
642 EXPORT_SYMBOL_GPL(machine_check_poll);
645 * Do a quick check if any of the events requires a panic.
646 * This decides if we keep the events around or clear them.
648 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
649 struct pt_regs *regs)
653 for (i = 0; i < mca_cfg.banks; i++) {
654 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
655 if (m->status & MCI_STATUS_VAL) {
656 __set_bit(i, validp);
657 if (quirk_no_way_out)
658 quirk_no_way_out(i, m, regs);
660 if (mce_severity(m, mca_cfg.tolerant, msg) >= MCE_PANIC_SEVERITY)
667 * Variable to establish order between CPUs while scanning.
668 * Each CPU spins initially until executing is equal its number.
670 static atomic_t mce_executing;
673 * Defines order of CPUs on entry. First CPU becomes Monarch.
675 static atomic_t mce_callin;
678 * Check if a timeout waiting for other CPUs happened.
680 static int mce_timed_out(u64 *t)
683 * The others already did panic for some reason.
684 * Bail out like in a timeout.
685 * rmb() to tell the compiler that system_state
686 * might have been modified by someone else.
689 if (atomic_read(&mce_paniced))
691 if (!mca_cfg.monarch_timeout)
693 if ((s64)*t < SPINUNIT) {
694 /* CHECKME: Make panic default for 1 too? */
695 if (mca_cfg.tolerant < 1)
696 mce_panic("Timeout synchronizing machine check over CPUs",
703 touch_nmi_watchdog();
708 * The Monarch's reign. The Monarch is the CPU who entered
709 * the machine check handler first. It waits for the others to
710 * raise the exception too and then grades them. When any
711 * error is fatal panic. Only then let the others continue.
713 * The other CPUs entering the MCE handler will be controlled by the
714 * Monarch. They are called Subjects.
716 * This way we prevent any potential data corruption in a unrecoverable case
717 * and also makes sure always all CPU's errors are examined.
719 * Also this detects the case of a machine check event coming from outer
720 * space (not detected by any CPUs) In this case some external agent wants
721 * us to shut down, so panic too.
723 * The other CPUs might still decide to panic if the handler happens
724 * in a unrecoverable place, but in this case the system is in a semi-stable
725 * state and won't corrupt anything by itself. It's ok to let the others
726 * continue for a bit first.
728 * All the spin loops have timeouts; when a timeout happens a CPU
729 * typically elects itself to be Monarch.
731 static void mce_reign(void)
734 struct mce *m = NULL;
735 int global_worst = 0;
740 * This CPU is the Monarch and the other CPUs have run
741 * through their handlers.
742 * Grade the severity of the errors of all the CPUs.
744 for_each_possible_cpu(cpu) {
745 int severity = mce_severity(&per_cpu(mces_seen, cpu),
748 if (severity > global_worst) {
750 global_worst = severity;
751 m = &per_cpu(mces_seen, cpu);
756 * Cannot recover? Panic here then.
757 * This dumps all the mces in the log buffer and stops the
760 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
761 mce_panic("Fatal Machine check", m, msg);
764 * For UC somewhere we let the CPU who detects it handle it.
765 * Also must let continue the others, otherwise the handling
766 * CPU could deadlock on a lock.
770 * No machine check event found. Must be some external
771 * source or one CPU is hung. Panic.
773 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
774 mce_panic("Machine check from unknown source", NULL, NULL);
777 * Now clear all the mces_seen so that they don't reappear on
780 for_each_possible_cpu(cpu)
781 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
784 static atomic_t global_nwo;
787 * Start of Monarch synchronization. This waits until all CPUs have
788 * entered the exception handler and then determines if any of them
789 * saw a fatal event that requires panic. Then it executes them
790 * in the entry order.
791 * TBD double check parallel CPU hotunplug
793 static int mce_start(int *no_way_out)
796 int cpus = num_online_cpus();
797 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
802 atomic_add(*no_way_out, &global_nwo);
804 * global_nwo should be updated before mce_callin
807 order = atomic_inc_return(&mce_callin);
812 while (atomic_read(&mce_callin) != cpus) {
813 if (mce_timed_out(&timeout)) {
814 atomic_set(&global_nwo, 0);
821 * mce_callin should be read before global_nwo
827 * Monarch: Starts executing now, the others wait.
829 atomic_set(&mce_executing, 1);
832 * Subject: Now start the scanning loop one by one in
833 * the original callin order.
834 * This way when there are any shared banks it will be
835 * only seen by one CPU before cleared, avoiding duplicates.
837 while (atomic_read(&mce_executing) < order) {
838 if (mce_timed_out(&timeout)) {
839 atomic_set(&global_nwo, 0);
847 * Cache the global no_way_out state.
849 *no_way_out = atomic_read(&global_nwo);
855 * Synchronize between CPUs after main scanning loop.
856 * This invokes the bulk of the Monarch processing.
858 static int mce_end(int order)
861 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
869 * Allow others to run.
871 atomic_inc(&mce_executing);
874 /* CHECKME: Can this race with a parallel hotplug? */
875 int cpus = num_online_cpus();
878 * Monarch: Wait for everyone to go through their scanning
881 while (atomic_read(&mce_executing) <= cpus) {
882 if (mce_timed_out(&timeout))
892 * Subject: Wait for Monarch to finish.
894 while (atomic_read(&mce_executing) != 0) {
895 if (mce_timed_out(&timeout))
901 * Don't reset anything. That's done by the Monarch.
907 * Reset all global state.
910 atomic_set(&global_nwo, 0);
911 atomic_set(&mce_callin, 0);
915 * Let others run again.
917 atomic_set(&mce_executing, 0);
922 * Check if the address reported by the CPU is in a format we can parse.
923 * It would be possible to add code for most other cases, but all would
924 * be somewhat complicated (e.g. segment offset would require an instruction
925 * parser). So only support physical addresses up to page granuality for now.
927 static int mce_usable_address(struct mce *m)
929 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
931 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
933 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
938 static void mce_clear_state(unsigned long *toclear)
942 for (i = 0; i < mca_cfg.banks; i++) {
943 if (test_bit(i, toclear))
944 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
949 * Need to save faulting physical address associated with a process
950 * in the machine check handler some place where we can grab it back
951 * later in mce_notify_process()
953 #define MCE_INFO_MAX 16
957 struct task_struct *t;
960 } mce_info[MCE_INFO_MAX];
962 static void mce_save_info(__u64 addr, int c)
966 for (mi = mce_info; mi < &mce_info[MCE_INFO_MAX]; mi++) {
967 if (atomic_cmpxchg(&mi->inuse, 0, 1) == 0) {
975 mce_panic("Too many concurrent recoverable errors", NULL, NULL);
978 static struct mce_info *mce_find_info(void)
982 for (mi = mce_info; mi < &mce_info[MCE_INFO_MAX]; mi++)
983 if (atomic_read(&mi->inuse) && mi->t == current)
988 static void mce_clear_info(struct mce_info *mi)
990 atomic_set(&mi->inuse, 0);
994 * The actual machine check handler. This only handles real
995 * exceptions when something got corrupted coming in through int 18.
997 * This is executed in NMI context not subject to normal locking rules. This
998 * implies that most kernel services cannot be safely used. Don't even
999 * think about putting a printk in there!
1001 * On Intel systems this is entered on all CPUs in parallel through
1002 * MCE broadcast. However some CPUs might be broken beyond repair,
1003 * so be always careful when synchronizing with others.
1005 void do_machine_check(struct pt_regs *regs, long error_code)
1007 struct mca_config *cfg = &mca_cfg;
1008 struct mce m, *final;
1013 * Establish sequential order between the CPUs entering the machine
1018 * If no_way_out gets set, there is no safe way to recover from this
1019 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1023 * If kill_it gets set, there might be a way to recover from this
1027 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1028 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1029 char *msg = "Unknown";
1031 atomic_inc(&mce_entry);
1033 this_cpu_inc(mce_exception_count);
1038 mce_gather_info(&m, regs);
1040 final = &__get_cpu_var(mces_seen);
1043 memset(valid_banks, 0, sizeof(valid_banks));
1044 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1049 * When no restart IP might need to kill or panic.
1050 * Assume the worst for now, but if we find the
1051 * severity is MCE_AR_SEVERITY we have other options.
1053 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1057 * Go through all the banks in exclusion of the other CPUs.
1058 * This way we don't report duplicated events on shared banks
1059 * because the first one to see it will clear it.
1061 order = mce_start(&no_way_out);
1062 for (i = 0; i < cfg->banks; i++) {
1063 __clear_bit(i, toclear);
1064 if (!test_bit(i, valid_banks))
1066 if (!mce_banks[i].ctl)
1073 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1074 if ((m.status & MCI_STATUS_VAL) == 0)
1078 * Non uncorrected or non signaled errors are handled by
1079 * machine_check_poll. Leave them alone, unless this panics.
1081 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1086 * Set taint even when machine check was not enabled.
1088 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1090 severity = mce_severity(&m, cfg->tolerant, NULL);
1093 * When machine check was for corrected handler don't touch,
1094 * unless we're panicing.
1096 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
1098 __set_bit(i, toclear);
1099 if (severity == MCE_NO_SEVERITY) {
1101 * Machine check event was not enabled. Clear, but
1107 mce_read_aux(&m, i);
1110 * Action optional error. Queue address for later processing.
1111 * When the ring overflows we just ignore the AO error.
1112 * RED-PEN add some logging mechanism when
1113 * usable_address or mce_add_ring fails.
1114 * RED-PEN don't ignore overflow for mca_cfg.tolerant == 0
1116 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1117 mce_ring_add(m.addr >> PAGE_SHIFT);
1121 if (severity > worst) {
1127 /* mce_clear_state will clear *final, save locally for use later */
1131 mce_clear_state(toclear);
1134 * Do most of the synchronization with other CPUs.
1135 * When there's any problem use only local no_way_out state.
1137 if (mce_end(order) < 0)
1138 no_way_out = worst >= MCE_PANIC_SEVERITY;
1141 * At insane "tolerant" levels we take no action. Otherwise
1142 * we only die if we have no other choice. For less serious
1143 * issues we try to recover, or limit damage to the current
1146 if (cfg->tolerant < 3) {
1148 mce_panic("Fatal machine check on current CPU", &m, msg);
1149 if (worst == MCE_AR_SEVERITY) {
1150 /* schedule action before return to userland */
1151 mce_save_info(m.addr, m.mcgstatus & MCG_STATUS_RIPV);
1152 set_thread_flag(TIF_MCE_NOTIFY);
1153 } else if (kill_it) {
1154 force_sig(SIGBUS, current);
1159 mce_report_event(regs);
1160 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1162 atomic_dec(&mce_entry);
1165 EXPORT_SYMBOL_GPL(do_machine_check);
1167 #ifndef CONFIG_MEMORY_FAILURE
1168 int memory_failure(unsigned long pfn, int vector, int flags)
1170 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1171 BUG_ON(flags & MF_ACTION_REQUIRED);
1172 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1173 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1181 * Called in process context that interrupted by MCE and marked with
1182 * TIF_MCE_NOTIFY, just before returning to erroneous userland.
1183 * This code is allowed to sleep.
1184 * Attempt possible recovery such as calling the high level VM handler to
1185 * process any corrupted pages, and kill/signal current process if required.
1186 * Action required errors are handled here.
1188 void mce_notify_process(void)
1191 struct mce_info *mi = mce_find_info();
1192 int flags = MF_ACTION_REQUIRED;
1195 mce_panic("Lost physical address for unconsumed uncorrectable error", NULL, NULL);
1196 pfn = mi->paddr >> PAGE_SHIFT;
1198 clear_thread_flag(TIF_MCE_NOTIFY);
1200 pr_err("Uncorrected hardware memory error in user-access at %llx",
1203 * We must call memory_failure() here even if the current process is
1204 * doomed. We still need to mark the page as poisoned and alert any
1205 * other users of the page.
1207 if (!mi->restartable)
1208 flags |= MF_MUST_KILL;
1209 if (memory_failure(pfn, MCE_VECTOR, flags) < 0) {
1210 pr_err("Memory error not recovered");
1211 force_sig(SIGBUS, current);
1217 * Action optional processing happens here (picking up
1218 * from the list of faulting pages that do_machine_check()
1219 * placed into the "ring").
1221 static void mce_process_work(struct work_struct *dummy)
1225 while (mce_ring_get(&pfn))
1226 memory_failure(pfn, MCE_VECTOR, 0);
1229 #ifdef CONFIG_X86_MCE_INTEL
1231 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1232 * @cpu: The CPU on which the event occurred.
1233 * @status: Event status information
1235 * This function should be called by the thermal interrupt after the
1236 * event has been processed and the decision was made to log the event
1239 * The status parameter will be saved to the 'status' field of 'struct mce'
1240 * and historically has been the register value of the
1241 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1243 void mce_log_therm_throt_event(__u64 status)
1248 m.bank = MCE_THERMAL_BANK;
1252 #endif /* CONFIG_X86_MCE_INTEL */
1255 * Periodic polling timer for "silent" machine check errors. If the
1256 * poller finds an MCE, poll 2x faster. When the poller finds no more
1257 * errors, poll 2x slower (up to check_interval seconds).
1259 static unsigned long check_interval = 5 * 60; /* 5 minutes */
1261 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1262 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1264 static unsigned long mce_adjust_timer_default(unsigned long interval)
1269 static unsigned long (*mce_adjust_timer)(unsigned long interval) =
1270 mce_adjust_timer_default;
1272 static void mce_timer_fn(unsigned long data)
1274 struct timer_list *t = &__get_cpu_var(mce_timer);
1277 WARN_ON(smp_processor_id() != data);
1279 if (mce_available(__this_cpu_ptr(&cpu_info))) {
1280 machine_check_poll(MCP_TIMESTAMP,
1281 &__get_cpu_var(mce_poll_banks));
1282 mce_intel_cmci_poll();
1286 * Alert userspace if needed. If we logged an MCE, reduce the
1287 * polling interval, otherwise increase the polling interval.
1289 iv = __this_cpu_read(mce_next_interval);
1290 if (mce_notify_irq()) {
1291 iv = max(iv / 2, (unsigned long) HZ/100);
1293 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1294 iv = mce_adjust_timer(iv);
1296 __this_cpu_write(mce_next_interval, iv);
1297 /* Might have become 0 after CMCI storm subsided */
1299 t->expires = jiffies + iv;
1300 add_timer_on(t, smp_processor_id());
1305 * Ensure that the timer is firing in @interval from now.
1307 void mce_timer_kick(unsigned long interval)
1309 struct timer_list *t = &__get_cpu_var(mce_timer);
1310 unsigned long when = jiffies + interval;
1311 unsigned long iv = __this_cpu_read(mce_next_interval);
1313 if (timer_pending(t)) {
1314 if (time_before(when, t->expires))
1315 mod_timer_pinned(t, when);
1317 t->expires = round_jiffies(when);
1318 add_timer_on(t, smp_processor_id());
1321 __this_cpu_write(mce_next_interval, interval);
1324 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1325 static void mce_timer_delete_all(void)
1329 for_each_online_cpu(cpu)
1330 del_timer_sync(&per_cpu(mce_timer, cpu));
1333 static void mce_do_trigger(struct work_struct *work)
1335 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1338 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1341 * Notify the user(s) about new machine check events.
1342 * Can be called from interrupt context, but not from machine check/NMI
1345 int mce_notify_irq(void)
1347 /* Not more than two messages every minute */
1348 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1350 if (test_and_clear_bit(0, &mce_need_notify)) {
1351 /* wake processes polling /dev/mcelog */
1352 wake_up_interruptible(&mce_chrdev_wait);
1355 schedule_work(&mce_trigger_work);
1357 if (__ratelimit(&ratelimit))
1358 pr_info(HW_ERR "Machine check events logged\n");
1364 EXPORT_SYMBOL_GPL(mce_notify_irq);
1366 static int __mcheck_cpu_mce_banks_init(void)
1369 u8 num_banks = mca_cfg.banks;
1371 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1375 for (i = 0; i < num_banks; i++) {
1376 struct mce_bank *b = &mce_banks[i];
1385 * Initialize Machine Checks for a CPU.
1387 static int __mcheck_cpu_cap_init(void)
1392 rdmsrl(MSR_IA32_MCG_CAP, cap);
1394 b = cap & MCG_BANKCNT_MASK;
1396 pr_info("CPU supports %d MCE banks\n", b);
1398 if (b > MAX_NR_BANKS) {
1399 pr_warn("Using only %u machine check banks out of %u\n",
1404 /* Don't support asymmetric configurations today */
1405 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1409 int err = __mcheck_cpu_mce_banks_init();
1415 /* Use accurate RIP reporting if available. */
1416 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1417 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1419 if (cap & MCG_SER_P)
1425 static void __mcheck_cpu_init_generic(void)
1427 enum mcp_flags m_fl = 0;
1428 mce_banks_t all_banks;
1432 if (!mca_cfg.bootlog)
1436 * Log the machine checks left over from the previous reset.
1438 bitmap_fill(all_banks, MAX_NR_BANKS);
1439 machine_check_poll(MCP_UC | m_fl, &all_banks);
1441 set_in_cr4(X86_CR4_MCE);
1443 rdmsrl(MSR_IA32_MCG_CAP, cap);
1444 if (cap & MCG_CTL_P)
1445 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1447 for (i = 0; i < mca_cfg.banks; i++) {
1448 struct mce_bank *b = &mce_banks[i];
1452 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1453 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1458 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1459 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1460 * Vol 3B Table 15-20). But this confuses both the code that determines
1461 * whether the machine check occurred in kernel or user mode, and also
1462 * the severity assessment code. Pretend that EIPV was set, and take the
1463 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1465 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1469 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1471 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1472 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1473 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1475 (MCI_STATUS_UC|MCI_STATUS_EN|
1476 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1477 MCI_STATUS_AR|MCACOD_INSTR))
1480 m->mcgstatus |= MCG_STATUS_EIPV;
1485 /* Add per CPU specific workarounds here */
1486 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1488 struct mca_config *cfg = &mca_cfg;
1490 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1491 pr_info("unknown CPU type - not enabling MCE support\n");
1495 /* This should be disabled by the BIOS, but isn't always */
1496 if (c->x86_vendor == X86_VENDOR_AMD) {
1497 if (c->x86 == 15 && cfg->banks > 4) {
1499 * disable GART TBL walk error reporting, which
1500 * trips off incorrectly with the IOMMU & 3ware
1503 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1505 if (c->x86 <= 17 && cfg->bootlog < 0) {
1507 * Lots of broken BIOS around that don't clear them
1508 * by default and leave crap in there. Don't log:
1513 * Various K7s with broken bank 0 around. Always disable
1516 if (c->x86 == 6 && cfg->banks > 0)
1517 mce_banks[0].ctl = 0;
1520 * Turn off MC4_MISC thresholding banks on those models since
1521 * they're not supported there.
1523 if (c->x86 == 0x15 &&
1524 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1529 0x00000413, /* MC4_MISC0 */
1530 0xc0000408, /* MC4_MISC1 */
1533 rdmsrl(MSR_K7_HWCR, hwcr);
1535 /* McStatusWrEn has to be set */
1536 need_toggle = !(hwcr & BIT(18));
1539 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1541 for (i = 0; i < ARRAY_SIZE(msrs); i++) {
1542 rdmsrl(msrs[i], val);
1545 if (val & BIT_64(62)) {
1547 wrmsrl(msrs[i], val);
1551 /* restore old settings */
1553 wrmsrl(MSR_K7_HWCR, hwcr);
1557 if (c->x86_vendor == X86_VENDOR_INTEL) {
1559 * SDM documents that on family 6 bank 0 should not be written
1560 * because it aliases to another special BIOS controlled
1562 * But it's not aliased anymore on model 0x1a+
1563 * Don't ignore bank 0 completely because there could be a
1564 * valid event later, merely don't write CTL0.
1567 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1568 mce_banks[0].init = 0;
1571 * All newer Intel systems support MCE broadcasting. Enable
1572 * synchronization with a one second timeout.
1574 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1575 cfg->monarch_timeout < 0)
1576 cfg->monarch_timeout = USEC_PER_SEC;
1579 * There are also broken BIOSes on some Pentium M and
1582 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1585 if (c->x86 == 6 && c->x86_model == 45)
1586 quirk_no_way_out = quirk_sandybridge_ifu;
1588 if (cfg->monarch_timeout < 0)
1589 cfg->monarch_timeout = 0;
1590 if (cfg->bootlog != 0)
1591 cfg->panic_timeout = 30;
1596 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1601 switch (c->x86_vendor) {
1602 case X86_VENDOR_INTEL:
1603 intel_p5_mcheck_init(c);
1606 case X86_VENDOR_CENTAUR:
1607 winchip_mcheck_init(c);
1615 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1617 switch (c->x86_vendor) {
1618 case X86_VENDOR_INTEL:
1619 mce_intel_feature_init(c);
1620 mce_adjust_timer = mce_intel_adjust_timer;
1622 case X86_VENDOR_AMD:
1623 mce_amd_feature_init(c);
1630 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1632 unsigned long iv = mce_adjust_timer(check_interval * HZ);
1634 __this_cpu_write(mce_next_interval, iv);
1636 if (mca_cfg.ignore_ce || !iv)
1639 t->expires = round_jiffies(jiffies + iv);
1640 add_timer_on(t, smp_processor_id());
1643 static void __mcheck_cpu_init_timer(void)
1645 struct timer_list *t = &__get_cpu_var(mce_timer);
1646 unsigned int cpu = smp_processor_id();
1648 setup_timer(t, mce_timer_fn, cpu);
1649 mce_start_timer(cpu, t);
1652 /* Handle unconfigured int18 (should never happen) */
1653 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1655 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1656 smp_processor_id());
1659 /* Call the installed machine check handler for this CPU setup. */
1660 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1661 unexpected_machine_check;
1664 * Called for each booted CPU to set up machine checks.
1665 * Must be called with preempt off:
1667 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1669 if (mca_cfg.disabled)
1672 if (__mcheck_cpu_ancient_init(c))
1675 if (!mce_available(c))
1678 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1679 mca_cfg.disabled = true;
1683 machine_check_vector = do_machine_check;
1685 __mcheck_cpu_init_generic();
1686 __mcheck_cpu_init_vendor(c);
1687 __mcheck_cpu_init_timer();
1688 INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1689 init_irq_work(&__get_cpu_var(mce_irq_work), &mce_irq_work_cb);
1693 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1696 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1697 static int mce_chrdev_open_count; /* #times opened */
1698 static int mce_chrdev_open_exclu; /* already open exclusive? */
1700 static int mce_chrdev_open(struct inode *inode, struct file *file)
1702 spin_lock(&mce_chrdev_state_lock);
1704 if (mce_chrdev_open_exclu ||
1705 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1706 spin_unlock(&mce_chrdev_state_lock);
1711 if (file->f_flags & O_EXCL)
1712 mce_chrdev_open_exclu = 1;
1713 mce_chrdev_open_count++;
1715 spin_unlock(&mce_chrdev_state_lock);
1717 return nonseekable_open(inode, file);
1720 static int mce_chrdev_release(struct inode *inode, struct file *file)
1722 spin_lock(&mce_chrdev_state_lock);
1724 mce_chrdev_open_count--;
1725 mce_chrdev_open_exclu = 0;
1727 spin_unlock(&mce_chrdev_state_lock);
1732 static void collect_tscs(void *data)
1734 unsigned long *cpu_tsc = (unsigned long *)data;
1736 rdtscll(cpu_tsc[smp_processor_id()]);
1739 static int mce_apei_read_done;
1741 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1742 static int __mce_read_apei(char __user **ubuf, size_t usize)
1748 if (usize < sizeof(struct mce))
1751 rc = apei_read_mce(&m, &record_id);
1752 /* Error or no more MCE record */
1754 mce_apei_read_done = 1;
1756 * When ERST is disabled, mce_chrdev_read() should return
1757 * "no record" instead of "no device."
1764 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1767 * In fact, we should have cleared the record after that has
1768 * been flushed to the disk or sent to network in
1769 * /sbin/mcelog, but we have no interface to support that now,
1770 * so just clear it to avoid duplication.
1772 rc = apei_clear_mce(record_id);
1774 mce_apei_read_done = 1;
1777 *ubuf += sizeof(struct mce);
1782 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1783 size_t usize, loff_t *off)
1785 char __user *buf = ubuf;
1786 unsigned long *cpu_tsc;
1787 unsigned prev, next;
1790 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1794 mutex_lock(&mce_chrdev_read_mutex);
1796 if (!mce_apei_read_done) {
1797 err = __mce_read_apei(&buf, usize);
1798 if (err || buf != ubuf)
1802 next = rcu_dereference_check_mce(mcelog.next);
1804 /* Only supports full reads right now */
1806 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1812 for (i = prev; i < next; i++) {
1813 unsigned long start = jiffies;
1814 struct mce *m = &mcelog.entry[i];
1816 while (!m->finished) {
1817 if (time_after_eq(jiffies, start + 2)) {
1818 memset(m, 0, sizeof(*m));
1824 err |= copy_to_user(buf, m, sizeof(*m));
1830 memset(mcelog.entry + prev, 0,
1831 (next - prev) * sizeof(struct mce));
1833 next = cmpxchg(&mcelog.next, prev, 0);
1834 } while (next != prev);
1836 synchronize_sched();
1839 * Collect entries that were still getting written before the
1842 on_each_cpu(collect_tscs, cpu_tsc, 1);
1844 for (i = next; i < MCE_LOG_LEN; i++) {
1845 struct mce *m = &mcelog.entry[i];
1847 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1848 err |= copy_to_user(buf, m, sizeof(*m));
1851 memset(m, 0, sizeof(*m));
1859 mutex_unlock(&mce_chrdev_read_mutex);
1862 return err ? err : buf - ubuf;
1865 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1867 poll_wait(file, &mce_chrdev_wait, wait);
1868 if (rcu_access_index(mcelog.next))
1869 return POLLIN | POLLRDNORM;
1870 if (!mce_apei_read_done && apei_check_mce())
1871 return POLLIN | POLLRDNORM;
1875 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1878 int __user *p = (int __user *)arg;
1880 if (!capable(CAP_SYS_ADMIN))
1884 case MCE_GET_RECORD_LEN:
1885 return put_user(sizeof(struct mce), p);
1886 case MCE_GET_LOG_LEN:
1887 return put_user(MCE_LOG_LEN, p);
1888 case MCE_GETCLEAR_FLAGS: {
1892 flags = mcelog.flags;
1893 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1895 return put_user(flags, p);
1902 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1903 size_t usize, loff_t *off);
1905 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1906 const char __user *ubuf,
1907 size_t usize, loff_t *off))
1911 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1913 ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1914 size_t usize, loff_t *off)
1917 return mce_write(filp, ubuf, usize, off);
1922 static const struct file_operations mce_chrdev_ops = {
1923 .open = mce_chrdev_open,
1924 .release = mce_chrdev_release,
1925 .read = mce_chrdev_read,
1926 .write = mce_chrdev_write,
1927 .poll = mce_chrdev_poll,
1928 .unlocked_ioctl = mce_chrdev_ioctl,
1929 .llseek = no_llseek,
1932 static struct miscdevice mce_chrdev_device = {
1939 * mce=off Disables machine check
1940 * mce=no_cmci Disables CMCI
1941 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1942 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1943 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1944 * monarchtimeout is how long to wait for other CPUs on machine
1945 * check, or 0 to not wait
1946 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1947 * mce=nobootlog Don't log MCEs from before booting.
1948 * mce=bios_cmci_threshold Don't program the CMCI threshold
1950 static int __init mcheck_enable(char *str)
1952 struct mca_config *cfg = &mca_cfg;
1960 if (!strcmp(str, "off"))
1961 cfg->disabled = true;
1962 else if (!strcmp(str, "no_cmci"))
1963 cfg->cmci_disabled = true;
1964 else if (!strcmp(str, "dont_log_ce"))
1965 cfg->dont_log_ce = true;
1966 else if (!strcmp(str, "ignore_ce"))
1967 cfg->ignore_ce = true;
1968 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1969 cfg->bootlog = (str[0] == 'b');
1970 else if (!strcmp(str, "bios_cmci_threshold"))
1971 cfg->bios_cmci_threshold = true;
1972 else if (isdigit(str[0])) {
1973 get_option(&str, &(cfg->tolerant));
1976 get_option(&str, &(cfg->monarch_timeout));
1979 pr_info("mce argument %s ignored. Please use /sys\n", str);
1984 __setup("mce", mcheck_enable);
1986 int __init mcheck_init(void)
1988 mcheck_intel_therm_init();
1994 * mce_syscore: PM support
1998 * Disable machine checks on suspend and shutdown. We can't really handle
2001 static int mce_disable_error_reporting(void)
2005 for (i = 0; i < mca_cfg.banks; i++) {
2006 struct mce_bank *b = &mce_banks[i];
2009 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2014 static int mce_syscore_suspend(void)
2016 return mce_disable_error_reporting();
2019 static void mce_syscore_shutdown(void)
2021 mce_disable_error_reporting();
2025 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2026 * Only one CPU is active at this time, the others get re-added later using
2029 static void mce_syscore_resume(void)
2031 __mcheck_cpu_init_generic();
2032 __mcheck_cpu_init_vendor(__this_cpu_ptr(&cpu_info));
2035 static struct syscore_ops mce_syscore_ops = {
2036 .suspend = mce_syscore_suspend,
2037 .shutdown = mce_syscore_shutdown,
2038 .resume = mce_syscore_resume,
2042 * mce_device: Sysfs support
2045 static void mce_cpu_restart(void *data)
2047 if (!mce_available(__this_cpu_ptr(&cpu_info)))
2049 __mcheck_cpu_init_generic();
2050 __mcheck_cpu_init_timer();
2053 /* Reinit MCEs after user configuration changes */
2054 static void mce_restart(void)
2056 mce_timer_delete_all();
2057 on_each_cpu(mce_cpu_restart, NULL, 1);
2060 /* Toggle features for corrected errors */
2061 static void mce_disable_cmci(void *data)
2063 if (!mce_available(__this_cpu_ptr(&cpu_info)))
2068 static void mce_enable_ce(void *all)
2070 if (!mce_available(__this_cpu_ptr(&cpu_info)))
2075 __mcheck_cpu_init_timer();
2078 static struct bus_type mce_subsys = {
2079 .name = "machinecheck",
2080 .dev_name = "machinecheck",
2083 DEFINE_PER_CPU(struct device *, mce_device);
2085 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2087 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2089 return container_of(attr, struct mce_bank, attr);
2092 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2095 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2098 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2099 const char *buf, size_t size)
2103 if (strict_strtoull(buf, 0, &new) < 0)
2106 attr_to_bank(attr)->ctl = new;
2113 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2115 strcpy(buf, mce_helper);
2117 return strlen(mce_helper) + 1;
2120 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2121 const char *buf, size_t siz)
2125 strncpy(mce_helper, buf, sizeof(mce_helper));
2126 mce_helper[sizeof(mce_helper)-1] = 0;
2127 p = strchr(mce_helper, '\n');
2132 return strlen(mce_helper) + !!p;
2135 static ssize_t set_ignore_ce(struct device *s,
2136 struct device_attribute *attr,
2137 const char *buf, size_t size)
2141 if (strict_strtoull(buf, 0, &new) < 0)
2144 if (mca_cfg.ignore_ce ^ !!new) {
2146 /* disable ce features */
2147 mce_timer_delete_all();
2148 on_each_cpu(mce_disable_cmci, NULL, 1);
2149 mca_cfg.ignore_ce = true;
2151 /* enable ce features */
2152 mca_cfg.ignore_ce = false;
2153 on_each_cpu(mce_enable_ce, (void *)1, 1);
2159 static ssize_t set_cmci_disabled(struct device *s,
2160 struct device_attribute *attr,
2161 const char *buf, size_t size)
2165 if (strict_strtoull(buf, 0, &new) < 0)
2168 if (mca_cfg.cmci_disabled ^ !!new) {
2171 on_each_cpu(mce_disable_cmci, NULL, 1);
2172 mca_cfg.cmci_disabled = true;
2175 mca_cfg.cmci_disabled = false;
2176 on_each_cpu(mce_enable_ce, NULL, 1);
2182 static ssize_t store_int_with_restart(struct device *s,
2183 struct device_attribute *attr,
2184 const char *buf, size_t size)
2186 ssize_t ret = device_store_int(s, attr, buf, size);
2191 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2192 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2193 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2194 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2196 static struct dev_ext_attribute dev_attr_check_interval = {
2197 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2201 static struct dev_ext_attribute dev_attr_ignore_ce = {
2202 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2206 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2207 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2208 &mca_cfg.cmci_disabled
2211 static struct device_attribute *mce_device_attrs[] = {
2212 &dev_attr_tolerant.attr,
2213 &dev_attr_check_interval.attr,
2215 &dev_attr_monarch_timeout.attr,
2216 &dev_attr_dont_log_ce.attr,
2217 &dev_attr_ignore_ce.attr,
2218 &dev_attr_cmci_disabled.attr,
2222 static cpumask_var_t mce_device_initialized;
2224 static void mce_device_release(struct device *dev)
2229 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2230 static int mce_device_create(unsigned int cpu)
2236 if (!mce_available(&boot_cpu_data))
2239 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2243 dev->bus = &mce_subsys;
2244 dev->release = &mce_device_release;
2246 err = device_register(dev);
2250 for (i = 0; mce_device_attrs[i]; i++) {
2251 err = device_create_file(dev, mce_device_attrs[i]);
2255 for (j = 0; j < mca_cfg.banks; j++) {
2256 err = device_create_file(dev, &mce_banks[j].attr);
2260 cpumask_set_cpu(cpu, mce_device_initialized);
2261 per_cpu(mce_device, cpu) = dev;
2266 device_remove_file(dev, &mce_banks[j].attr);
2269 device_remove_file(dev, mce_device_attrs[i]);
2271 device_unregister(dev);
2276 static void mce_device_remove(unsigned int cpu)
2278 struct device *dev = per_cpu(mce_device, cpu);
2281 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2284 for (i = 0; mce_device_attrs[i]; i++)
2285 device_remove_file(dev, mce_device_attrs[i]);
2287 for (i = 0; i < mca_cfg.banks; i++)
2288 device_remove_file(dev, &mce_banks[i].attr);
2290 device_unregister(dev);
2291 cpumask_clear_cpu(cpu, mce_device_initialized);
2292 per_cpu(mce_device, cpu) = NULL;
2295 /* Make sure there are no machine checks on offlined CPUs. */
2296 static void mce_disable_cpu(void *h)
2298 unsigned long action = *(unsigned long *)h;
2301 if (!mce_available(__this_cpu_ptr(&cpu_info)))
2304 if (!(action & CPU_TASKS_FROZEN))
2306 for (i = 0; i < mca_cfg.banks; i++) {
2307 struct mce_bank *b = &mce_banks[i];
2310 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2314 static void mce_reenable_cpu(void *h)
2316 unsigned long action = *(unsigned long *)h;
2319 if (!mce_available(__this_cpu_ptr(&cpu_info)))
2322 if (!(action & CPU_TASKS_FROZEN))
2324 for (i = 0; i < mca_cfg.banks; i++) {
2325 struct mce_bank *b = &mce_banks[i];
2328 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2332 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2334 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2336 unsigned int cpu = (unsigned long)hcpu;
2337 struct timer_list *t = &per_cpu(mce_timer, cpu);
2339 switch (action & ~CPU_TASKS_FROZEN) {
2341 mce_device_create(cpu);
2342 if (threshold_cpu_callback)
2343 threshold_cpu_callback(action, cpu);
2346 if (threshold_cpu_callback)
2347 threshold_cpu_callback(action, cpu);
2348 mce_device_remove(cpu);
2349 mce_intel_hcpu_update(cpu);
2351 case CPU_DOWN_PREPARE:
2352 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2355 case CPU_DOWN_FAILED:
2356 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2357 mce_start_timer(cpu, t);
2361 if (action == CPU_POST_DEAD) {
2362 /* intentionally ignoring frozen here */
2369 static struct notifier_block mce_cpu_notifier = {
2370 .notifier_call = mce_cpu_callback,
2373 static __init void mce_init_banks(void)
2377 for (i = 0; i < mca_cfg.banks; i++) {
2378 struct mce_bank *b = &mce_banks[i];
2379 struct device_attribute *a = &b->attr;
2381 sysfs_attr_init(&a->attr);
2382 a->attr.name = b->attrname;
2383 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2385 a->attr.mode = 0644;
2386 a->show = show_bank;
2387 a->store = set_bank;
2391 static __init int mcheck_init_device(void)
2396 if (!mce_available(&boot_cpu_data))
2399 zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL);
2403 err = subsys_system_register(&mce_subsys, NULL);
2407 for_each_online_cpu(i) {
2408 err = mce_device_create(i);
2413 register_syscore_ops(&mce_syscore_ops);
2414 register_hotcpu_notifier(&mce_cpu_notifier);
2416 /* register character device /dev/mcelog */
2417 misc_register(&mce_chrdev_device);
2421 device_initcall_sync(mcheck_init_device);
2424 * Old style boot options parsing. Only for compatibility.
2426 static int __init mcheck_disable(char *str)
2428 mca_cfg.disabled = true;
2431 __setup("nomce", mcheck_disable);
2433 #ifdef CONFIG_DEBUG_FS
2434 struct dentry *mce_get_debugfs_dir(void)
2436 static struct dentry *dmce;
2439 dmce = debugfs_create_dir("mce", NULL);
2444 static void mce_reset(void)
2447 atomic_set(&mce_fake_paniced, 0);
2448 atomic_set(&mce_executing, 0);
2449 atomic_set(&mce_callin, 0);
2450 atomic_set(&global_nwo, 0);
2453 static int fake_panic_get(void *data, u64 *val)
2459 static int fake_panic_set(void *data, u64 val)
2466 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2467 fake_panic_set, "%llu\n");
2469 static int __init mcheck_debugfs_init(void)
2471 struct dentry *dmce, *ffake_panic;
2473 dmce = mce_get_debugfs_dir();
2476 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2483 late_initcall(mcheck_debugfs_init);