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>
44 #include <linux/jump_label.h>
46 #include <asm/processor.h>
47 #include <asm/traps.h>
48 #include <asm/tlbflush.h>
51 #include <asm/reboot.h>
53 #include "mce-internal.h"
55 static DEFINE_MUTEX(mce_chrdev_read_mutex);
57 #define mce_log_get_idx_check(p) \
59 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
60 !lockdep_is_held(&mce_chrdev_read_mutex), \
61 "suspicious mce_log_get_idx_check() usage"); \
62 smp_load_acquire(&(p)); \
65 /* sysfs synchronization */
66 static DEFINE_MUTEX(mce_sysfs_mutex);
68 #define CREATE_TRACE_POINTS
69 #include <trace/events/mce.h>
71 #define SPINUNIT 100 /* 100ns */
73 DEFINE_PER_CPU(unsigned, mce_exception_count);
75 struct mce_bank *mce_banks __read_mostly;
76 struct mce_vendor_flags mce_flags __read_mostly;
78 struct mca_config mca_cfg __read_mostly = {
82 * 0: always panic on uncorrected errors, log corrected errors
83 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
84 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
85 * 3: never panic or SIGBUS, log all errors (for testing only)
91 /* User mode helper program triggered by machine check event */
92 static unsigned long mce_need_notify;
93 static char mce_helper[128];
94 static char *mce_helper_argv[2] = { mce_helper, NULL };
96 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
98 static DEFINE_PER_CPU(struct mce, mces_seen);
99 static int cpu_missing;
102 * MCA banks polled by the period polling timer for corrected events.
103 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
105 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
106 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
110 * MCA banks controlled through firmware first for corrected errors.
111 * This is a global list of banks for which we won't enable CMCI and we
112 * won't poll. Firmware controls these banks and is responsible for
113 * reporting corrected errors through GHES. Uncorrected/recoverable
114 * errors are still notified through a machine check.
116 mce_banks_t mce_banks_ce_disabled;
118 static struct work_struct mce_work;
119 static struct irq_work mce_irq_work;
121 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
124 * CPU/chipset specific EDAC code can register a notifier call here to print
125 * MCE errors in a human-readable form.
127 BLOCKING_NOTIFIER_HEAD(x86_mce_decoder_chain);
129 /* Do initial initialization of a struct mce */
130 void mce_setup(struct mce *m)
132 memset(m, 0, sizeof(struct mce));
133 m->cpu = m->extcpu = smp_processor_id();
135 /* We hope get_seconds stays lockless */
136 m->time = get_seconds();
137 m->cpuvendor = boot_cpu_data.x86_vendor;
138 m->cpuid = cpuid_eax(1);
139 m->socketid = cpu_data(m->extcpu).phys_proc_id;
140 m->apicid = cpu_data(m->extcpu).initial_apicid;
141 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
143 m->microcode = boot_cpu_data.microcode;
146 DEFINE_PER_CPU(struct mce, injectm);
147 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
150 * Lockless MCE logging infrastructure.
151 * This avoids deadlocks on printk locks without having to break locks. Also
152 * separate MCEs from kernel messages to avoid bogus bug reports.
155 static struct mce_log mcelog = {
156 .signature = MCE_LOG_SIGNATURE,
158 .recordlen = sizeof(struct mce),
161 void mce_log(struct mce *mce)
163 unsigned next, entry;
165 /* Emit the trace record: */
166 trace_mce_record(mce);
168 if (!mce_gen_pool_add(mce))
169 irq_work_queue(&mce_irq_work);
173 entry = mce_log_get_idx_check(mcelog.next);
177 * When the buffer fills up discard new entries.
178 * Assume that the earlier errors are the more
181 if (entry >= MCE_LOG_LEN) {
182 set_bit(MCE_OVERFLOW,
183 (unsigned long *)&mcelog.flags);
186 /* Old left over entry. Skip: */
187 if (mcelog.entry[entry].finished) {
195 if (cmpxchg(&mcelog.next, entry, next) == entry)
198 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
200 mcelog.entry[entry].finished = 1;
203 set_bit(0, &mce_need_notify);
206 void mce_inject_log(struct mce *m)
208 mutex_lock(&mce_chrdev_read_mutex);
210 mutex_unlock(&mce_chrdev_read_mutex);
212 EXPORT_SYMBOL_GPL(mce_inject_log);
214 static struct notifier_block mce_srao_nb;
216 void mce_register_decode_chain(struct notifier_block *nb)
218 /* Ensure SRAO notifier has the highest priority in the decode chain. */
219 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
222 blocking_notifier_chain_register(&x86_mce_decoder_chain, nb);
224 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
226 void mce_unregister_decode_chain(struct notifier_block *nb)
228 blocking_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
230 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
232 static inline u32 ctl_reg(int bank)
234 return MSR_IA32_MCx_CTL(bank);
237 static inline u32 status_reg(int bank)
239 return MSR_IA32_MCx_STATUS(bank);
242 static inline u32 addr_reg(int bank)
244 return MSR_IA32_MCx_ADDR(bank);
247 static inline u32 misc_reg(int bank)
249 return MSR_IA32_MCx_MISC(bank);
252 static inline u32 smca_ctl_reg(int bank)
254 return MSR_AMD64_SMCA_MCx_CTL(bank);
257 static inline u32 smca_status_reg(int bank)
259 return MSR_AMD64_SMCA_MCx_STATUS(bank);
262 static inline u32 smca_addr_reg(int bank)
264 return MSR_AMD64_SMCA_MCx_ADDR(bank);
267 static inline u32 smca_misc_reg(int bank)
269 return MSR_AMD64_SMCA_MCx_MISC(bank);
272 struct mca_msr_regs msr_ops = {
274 .status = status_reg,
279 static void print_mce(struct mce *m)
281 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
282 m->extcpu, m->mcgstatus, m->bank, m->status);
285 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
286 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
289 if (m->cs == __KERNEL_CS)
290 print_symbol("{%s}", m->ip);
294 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
296 pr_cont("ADDR %llx ", m->addr);
298 pr_cont("MISC %llx ", m->misc);
300 if (mce_flags.smca) {
302 pr_cont("SYND %llx ", m->synd);
304 pr_cont("IPID %llx ", m->ipid);
309 * Note this output is parsed by external tools and old fields
310 * should not be changed.
312 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
313 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
316 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
319 #define PANIC_TIMEOUT 5 /* 5 seconds */
321 static atomic_t mce_panicked;
323 static int fake_panic;
324 static atomic_t mce_fake_panicked;
326 /* Panic in progress. Enable interrupts and wait for final IPI */
327 static void wait_for_panic(void)
329 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
333 while (timeout-- > 0)
335 if (panic_timeout == 0)
336 panic_timeout = mca_cfg.panic_timeout;
337 panic("Panicing machine check CPU died");
340 static void mce_panic(const char *msg, struct mce *final, char *exp)
343 struct llist_node *pending;
344 struct mce_evt_llist *l;
348 * Make sure only one CPU runs in machine check panic
350 if (atomic_inc_return(&mce_panicked) > 1)
357 /* Don't log too much for fake panic */
358 if (atomic_inc_return(&mce_fake_panicked) > 1)
361 pending = mce_gen_pool_prepare_records();
362 /* First print corrected ones that are still unlogged */
363 llist_for_each_entry(l, pending, llnode) {
364 struct mce *m = &l->mce;
365 if (!(m->status & MCI_STATUS_UC)) {
368 apei_err = apei_write_mce(m);
371 /* Now print uncorrected but with the final one last */
372 llist_for_each_entry(l, pending, llnode) {
373 struct mce *m = &l->mce;
374 if (!(m->status & MCI_STATUS_UC))
376 if (!final || mce_cmp(m, final)) {
379 apei_err = apei_write_mce(m);
385 apei_err = apei_write_mce(final);
388 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
390 pr_emerg(HW_ERR "Machine check: %s\n", exp);
392 if (panic_timeout == 0)
393 panic_timeout = mca_cfg.panic_timeout;
396 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
399 /* Support code for software error injection */
401 static int msr_to_offset(u32 msr)
403 unsigned bank = __this_cpu_read(injectm.bank);
405 if (msr == mca_cfg.rip_msr)
406 return offsetof(struct mce, ip);
407 if (msr == msr_ops.status(bank))
408 return offsetof(struct mce, status);
409 if (msr == msr_ops.addr(bank))
410 return offsetof(struct mce, addr);
411 if (msr == msr_ops.misc(bank))
412 return offsetof(struct mce, misc);
413 if (msr == MSR_IA32_MCG_STATUS)
414 return offsetof(struct mce, mcgstatus);
418 /* MSR access wrappers used for error injection */
419 static u64 mce_rdmsrl(u32 msr)
423 if (__this_cpu_read(injectm.finished)) {
424 int offset = msr_to_offset(msr);
428 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
431 if (rdmsrl_safe(msr, &v)) {
432 WARN_ONCE(1, "mce: Unable to read MSR 0x%x!\n", msr);
434 * Return zero in case the access faulted. This should
435 * not happen normally but can happen if the CPU does
436 * something weird, or if the code is buggy.
444 static void mce_wrmsrl(u32 msr, u64 v)
446 if (__this_cpu_read(injectm.finished)) {
447 int offset = msr_to_offset(msr);
450 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
457 * Collect all global (w.r.t. this processor) status about this machine
458 * check into our "mce" struct so that we can use it later to assess
459 * the severity of the problem as we read per-bank specific details.
461 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
465 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
468 * Get the address of the instruction at the time of
469 * the machine check error.
471 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
476 * When in VM86 mode make the cs look like ring 3
477 * always. This is a lie, but it's better than passing
478 * the additional vm86 bit around everywhere.
480 if (v8086_mode(regs))
483 /* Use accurate RIP reporting if available. */
485 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
489 int mce_available(struct cpuinfo_x86 *c)
491 if (mca_cfg.disabled)
493 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
496 static void mce_schedule_work(void)
498 if (!mce_gen_pool_empty() && keventd_up())
499 schedule_work(&mce_work);
502 static void mce_irq_work_cb(struct irq_work *entry)
508 static void mce_report_event(struct pt_regs *regs)
510 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
513 * Triggering the work queue here is just an insurance
514 * policy in case the syscall exit notify handler
515 * doesn't run soon enough or ends up running on the
516 * wrong CPU (can happen when audit sleeps)
522 irq_work_queue(&mce_irq_work);
526 * Check if the address reported by the CPU is in a format we can parse.
527 * It would be possible to add code for most other cases, but all would
528 * be somewhat complicated (e.g. segment offset would require an instruction
529 * parser). So only support physical addresses up to page granuality for now.
531 static int mce_usable_address(struct mce *m)
533 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
536 /* Checks after this one are Intel-specific: */
537 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
540 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
542 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
547 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
550 struct mce *mce = (struct mce *)data;
556 if (mce_usable_address(mce) && (mce->severity == MCE_AO_SEVERITY)) {
557 pfn = mce->addr >> PAGE_SHIFT;
558 memory_failure(pfn, MCE_VECTOR, 0);
563 static struct notifier_block mce_srao_nb = {
564 .notifier_call = srao_decode_notifier,
569 * Read ADDR and MISC registers.
571 static void mce_read_aux(struct mce *m, int i)
573 if (m->status & MCI_STATUS_MISCV)
574 m->misc = mce_rdmsrl(msr_ops.misc(i));
576 if (m->status & MCI_STATUS_ADDRV) {
577 m->addr = mce_rdmsrl(msr_ops.addr(i));
580 * Mask the reported address by the reported granularity.
582 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
583 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
589 * Extract [55:<lsb>] where lsb is the least significant
590 * *valid* bit of the address bits.
592 if (mce_flags.smca) {
593 u8 lsb = (m->addr >> 56) & 0x3f;
595 m->addr &= GENMASK_ULL(55, lsb);
599 if (mce_flags.smca) {
600 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
602 if (m->status & MCI_STATUS_SYNDV)
603 m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
607 bool mce_is_memory_error(struct mce *m)
609 if (m->cpuvendor == X86_VENDOR_AMD) {
610 /* ErrCodeExt[20:16] */
611 u8 xec = (m->status >> 16) & 0x1f;
613 return (xec == 0x0 || xec == 0x8);
614 } else if (m->cpuvendor == X86_VENDOR_INTEL) {
616 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
618 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
619 * indicating a memory error. Bit 8 is used for indicating a
620 * cache hierarchy error. The combination of bit 2 and bit 3
621 * is used for indicating a `generic' cache hierarchy error
622 * But we can't just blindly check the above bits, because if
623 * bit 11 is set, then it is a bus/interconnect error - and
624 * either way the above bits just gives more detail on what
625 * bus/interconnect error happened. Note that bit 12 can be
626 * ignored, as it's the "filter" bit.
628 return (m->status & 0xef80) == BIT(7) ||
629 (m->status & 0xef00) == BIT(8) ||
630 (m->status & 0xeffc) == 0xc;
635 EXPORT_SYMBOL_GPL(mce_is_memory_error);
637 DEFINE_PER_CPU(unsigned, mce_poll_count);
640 * Poll for corrected events or events that happened before reset.
641 * Those are just logged through /dev/mcelog.
643 * This is executed in standard interrupt context.
645 * Note: spec recommends to panic for fatal unsignalled
646 * errors here. However this would be quite problematic --
647 * we would need to reimplement the Monarch handling and
648 * it would mess up the exclusion between exception handler
649 * and poll hander -- * so we skip this for now.
650 * These cases should not happen anyways, or only when the CPU
651 * is already totally * confused. In this case it's likely it will
652 * not fully execute the machine check handler either.
654 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
656 bool error_seen = false;
661 this_cpu_inc(mce_poll_count);
663 mce_gather_info(&m, NULL);
665 for (i = 0; i < mca_cfg.banks; i++) {
666 if (!mce_banks[i].ctl || !test_bit(i, *b))
675 m.status = mce_rdmsrl(msr_ops.status(i));
677 /* If this entry is not valid, ignore it */
678 if (!(m.status & MCI_STATUS_VAL))
683 * If we are logging everything (at CPU online) or this
684 * is a corrected error, then we must log it.
686 if ((flags & MCP_UC) || !(m.status & MCI_STATUS_UC))
690 * Newer Intel systems that support software error
691 * recovery need to make additional checks. Other
692 * CPUs should skip over uncorrected errors, but log
696 if (m.status & MCI_STATUS_UC)
701 /* Log "not enabled" (speculative) errors */
702 if (!(m.status & MCI_STATUS_EN))
706 * Log UCNA (SDM: 15.6.3 "UCR Error Classification")
707 * UC == 1 && PCC == 0 && S == 0
709 if (!(m.status & MCI_STATUS_PCC) && !(m.status & MCI_STATUS_S))
713 * Skip anything else. Presumption is that our read of this
714 * bank is racing with a machine check. Leave the log alone
715 * for do_machine_check() to deal with it.
724 if (!(flags & MCP_TIMESTAMP))
727 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
729 if (severity == MCE_DEFERRED_SEVERITY && mce_is_memory_error(&m))
730 if (m.status & MCI_STATUS_ADDRV)
731 m.severity = severity;
734 * Don't get the IP here because it's unlikely to
735 * have anything to do with the actual error location.
737 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
739 else if (mce_usable_address(&m)) {
741 * Although we skipped logging this, we still want
742 * to take action. Add to the pool so the registered
743 * notifiers will see it.
745 if (!mce_gen_pool_add(&m))
750 * Clear state for this bank.
752 mce_wrmsrl(msr_ops.status(i), 0);
756 * Don't clear MCG_STATUS here because it's only defined for
764 EXPORT_SYMBOL_GPL(machine_check_poll);
767 * Do a quick check if any of the events requires a panic.
768 * This decides if we keep the events around or clear them.
770 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
771 struct pt_regs *regs)
776 for (i = 0; i < mca_cfg.banks; i++) {
777 m->status = mce_rdmsrl(msr_ops.status(i));
778 if (!(m->status & MCI_STATUS_VAL))
781 __set_bit(i, validp);
782 if (quirk_no_way_out)
783 quirk_no_way_out(i, m, regs);
786 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
796 * Variable to establish order between CPUs while scanning.
797 * Each CPU spins initially until executing is equal its number.
799 static atomic_t mce_executing;
802 * Defines order of CPUs on entry. First CPU becomes Monarch.
804 static atomic_t mce_callin;
807 * Check if a timeout waiting for other CPUs happened.
809 static int mce_timed_out(u64 *t, const char *msg)
812 * The others already did panic for some reason.
813 * Bail out like in a timeout.
814 * rmb() to tell the compiler that system_state
815 * might have been modified by someone else.
818 if (atomic_read(&mce_panicked))
820 if (!mca_cfg.monarch_timeout)
822 if ((s64)*t < SPINUNIT) {
823 if (mca_cfg.tolerant <= 1)
824 mce_panic(msg, NULL, NULL);
830 touch_nmi_watchdog();
835 * The Monarch's reign. The Monarch is the CPU who entered
836 * the machine check handler first. It waits for the others to
837 * raise the exception too and then grades them. When any
838 * error is fatal panic. Only then let the others continue.
840 * The other CPUs entering the MCE handler will be controlled by the
841 * Monarch. They are called Subjects.
843 * This way we prevent any potential data corruption in a unrecoverable case
844 * and also makes sure always all CPU's errors are examined.
846 * Also this detects the case of a machine check event coming from outer
847 * space (not detected by any CPUs) In this case some external agent wants
848 * us to shut down, so panic too.
850 * The other CPUs might still decide to panic if the handler happens
851 * in a unrecoverable place, but in this case the system is in a semi-stable
852 * state and won't corrupt anything by itself. It's ok to let the others
853 * continue for a bit first.
855 * All the spin loops have timeouts; when a timeout happens a CPU
856 * typically elects itself to be Monarch.
858 static void mce_reign(void)
861 struct mce *m = NULL;
862 int global_worst = 0;
867 * This CPU is the Monarch and the other CPUs have run
868 * through their handlers.
869 * Grade the severity of the errors of all the CPUs.
871 for_each_possible_cpu(cpu) {
872 int severity = mce_severity(&per_cpu(mces_seen, cpu),
875 if (severity > global_worst) {
877 global_worst = severity;
878 m = &per_cpu(mces_seen, cpu);
883 * Cannot recover? Panic here then.
884 * This dumps all the mces in the log buffer and stops the
887 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
888 mce_panic("Fatal machine check", m, msg);
891 * For UC somewhere we let the CPU who detects it handle it.
892 * Also must let continue the others, otherwise the handling
893 * CPU could deadlock on a lock.
897 * No machine check event found. Must be some external
898 * source or one CPU is hung. Panic.
900 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
901 mce_panic("Fatal machine check from unknown source", NULL, NULL);
904 * Now clear all the mces_seen so that they don't reappear on
907 for_each_possible_cpu(cpu)
908 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
911 static atomic_t global_nwo;
914 * Start of Monarch synchronization. This waits until all CPUs have
915 * entered the exception handler and then determines if any of them
916 * saw a fatal event that requires panic. Then it executes them
917 * in the entry order.
918 * TBD double check parallel CPU hotunplug
920 static int mce_start(int *no_way_out)
923 int cpus = num_online_cpus();
924 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
929 atomic_add(*no_way_out, &global_nwo);
931 * Rely on the implied barrier below, such that global_nwo
932 * is updated before mce_callin.
934 order = atomic_inc_return(&mce_callin);
939 while (atomic_read(&mce_callin) != cpus) {
940 if (mce_timed_out(&timeout,
941 "Timeout: Not all CPUs entered broadcast exception handler")) {
942 atomic_set(&global_nwo, 0);
949 * mce_callin should be read before global_nwo
955 * Monarch: Starts executing now, the others wait.
957 atomic_set(&mce_executing, 1);
960 * Subject: Now start the scanning loop one by one in
961 * the original callin order.
962 * This way when there are any shared banks it will be
963 * only seen by one CPU before cleared, avoiding duplicates.
965 while (atomic_read(&mce_executing) < order) {
966 if (mce_timed_out(&timeout,
967 "Timeout: Subject CPUs unable to finish machine check processing")) {
968 atomic_set(&global_nwo, 0);
976 * Cache the global no_way_out state.
978 *no_way_out = atomic_read(&global_nwo);
984 * Synchronize between CPUs after main scanning loop.
985 * This invokes the bulk of the Monarch processing.
987 static int mce_end(int order)
990 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
998 * Allow others to run.
1000 atomic_inc(&mce_executing);
1003 /* CHECKME: Can this race with a parallel hotplug? */
1004 int cpus = num_online_cpus();
1007 * Monarch: Wait for everyone to go through their scanning
1010 while (atomic_read(&mce_executing) <= cpus) {
1011 if (mce_timed_out(&timeout,
1012 "Timeout: Monarch CPU unable to finish machine check processing"))
1022 * Subject: Wait for Monarch to finish.
1024 while (atomic_read(&mce_executing) != 0) {
1025 if (mce_timed_out(&timeout,
1026 "Timeout: Monarch CPU did not finish machine check processing"))
1032 * Don't reset anything. That's done by the Monarch.
1038 * Reset all global state.
1041 atomic_set(&global_nwo, 0);
1042 atomic_set(&mce_callin, 0);
1046 * Let others run again.
1048 atomic_set(&mce_executing, 0);
1052 static void mce_clear_state(unsigned long *toclear)
1056 for (i = 0; i < mca_cfg.banks; i++) {
1057 if (test_bit(i, toclear))
1058 mce_wrmsrl(msr_ops.status(i), 0);
1062 static int do_memory_failure(struct mce *m)
1064 int flags = MF_ACTION_REQUIRED;
1067 pr_err("Uncorrected hardware memory error in user-access at %llx", m->addr);
1068 if (!(m->mcgstatus & MCG_STATUS_RIPV))
1069 flags |= MF_MUST_KILL;
1070 ret = memory_failure(m->addr >> PAGE_SHIFT, MCE_VECTOR, flags);
1072 pr_err("Memory error not recovered");
1077 * The actual machine check handler. This only handles real
1078 * exceptions when something got corrupted coming in through int 18.
1080 * This is executed in NMI context not subject to normal locking rules. This
1081 * implies that most kernel services cannot be safely used. Don't even
1082 * think about putting a printk in there!
1084 * On Intel systems this is entered on all CPUs in parallel through
1085 * MCE broadcast. However some CPUs might be broken beyond repair,
1086 * so be always careful when synchronizing with others.
1088 void do_machine_check(struct pt_regs *regs, long error_code)
1090 struct mca_config *cfg = &mca_cfg;
1091 struct mce m, *final;
1097 * Establish sequential order between the CPUs entering the machine
1102 * If no_way_out gets set, there is no safe way to recover from this
1103 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1107 * If kill_it gets set, there might be a way to recover from this
1111 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1112 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1113 char *msg = "Unknown";
1116 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1120 int cpu = smp_processor_id();
1123 * Cases where we avoid rendezvous handler timeout:
1124 * 1) If this CPU is offline.
1126 * 2) If crashing_cpu was set, e.g. we're entering kdump and we need to
1127 * skip those CPUs which remain looping in the 1st kernel - see
1128 * crash_nmi_callback().
1130 * Note: there still is a small window between kexec-ing and the new,
1131 * kdump kernel establishing a new #MC handler where a broadcasted MCE
1132 * might not get handled properly.
1134 if (cpu_is_offline(cpu) ||
1135 (crashing_cpu != -1 && crashing_cpu != cpu)) {
1138 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1139 if (mcgstatus & MCG_STATUS_RIPV) {
1140 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1147 this_cpu_inc(mce_exception_count);
1152 mce_gather_info(&m, regs);
1154 final = this_cpu_ptr(&mces_seen);
1157 memset(valid_banks, 0, sizeof(valid_banks));
1158 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1163 * When no restart IP might need to kill or panic.
1164 * Assume the worst for now, but if we find the
1165 * severity is MCE_AR_SEVERITY we have other options.
1167 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1171 * Check if this MCE is signaled to only this logical processor,
1174 if (m.cpuvendor == X86_VENDOR_INTEL)
1175 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1178 * Local machine check may already know that we have to panic.
1179 * Broadcast machine check begins rendezvous in mce_start()
1180 * Go through all banks in exclusion of the other CPUs. This way we
1181 * don't report duplicated events on shared banks because the first one
1182 * to see it will clear it.
1186 mce_panic("Fatal local machine check", &m, msg);
1188 order = mce_start(&no_way_out);
1191 for (i = 0; i < cfg->banks; i++) {
1192 __clear_bit(i, toclear);
1193 if (!test_bit(i, valid_banks))
1195 if (!mce_banks[i].ctl)
1202 m.status = mce_rdmsrl(msr_ops.status(i));
1203 if ((m.status & MCI_STATUS_VAL) == 0)
1207 * Non uncorrected or non signaled errors are handled by
1208 * machine_check_poll. Leave them alone, unless this panics.
1210 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1215 * Set taint even when machine check was not enabled.
1217 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1219 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1222 * When machine check was for corrected/deferred handler don't
1223 * touch, unless we're panicing.
1225 if ((severity == MCE_KEEP_SEVERITY ||
1226 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1228 __set_bit(i, toclear);
1229 if (severity == MCE_NO_SEVERITY) {
1231 * Machine check event was not enabled. Clear, but
1237 mce_read_aux(&m, i);
1239 /* assuming valid severity level != 0 */
1240 m.severity = severity;
1244 if (severity > worst) {
1250 /* mce_clear_state will clear *final, save locally for use later */
1254 mce_clear_state(toclear);
1257 * Do most of the synchronization with other CPUs.
1258 * When there's any problem use only local no_way_out state.
1261 if (mce_end(order) < 0)
1262 no_way_out = worst >= MCE_PANIC_SEVERITY;
1265 * If there was a fatal machine check we should have
1266 * already called mce_panic earlier in this function.
1267 * Since we re-read the banks, we might have found
1268 * something new. Check again to see if we found a
1269 * fatal error. We call "mce_severity()" again to
1270 * make sure we have the right "msg".
1272 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3) {
1273 mce_severity(&m, cfg->tolerant, &msg, true);
1274 mce_panic("Local fatal machine check!", &m, msg);
1279 * If tolerant is at an insane level we drop requests to kill
1280 * processes and continue even when there is no way out.
1282 if (cfg->tolerant == 3)
1284 else if (no_way_out)
1285 mce_panic("Fatal machine check on current CPU", &m, msg);
1288 mce_report_event(regs);
1289 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1293 if (worst != MCE_AR_SEVERITY && !kill_it)
1296 /* Fault was in user mode and we need to take some action */
1297 if ((m.cs & 3) == 3) {
1298 ist_begin_non_atomic(regs);
1301 if (kill_it || do_memory_failure(&m))
1302 force_sig(SIGBUS, current);
1303 local_irq_disable();
1304 ist_end_non_atomic();
1306 if (!fixup_exception(regs, X86_TRAP_MC))
1307 mce_panic("Failed kernel mode recovery", &m, NULL);
1313 EXPORT_SYMBOL_GPL(do_machine_check);
1315 #ifndef CONFIG_MEMORY_FAILURE
1316 int memory_failure(unsigned long pfn, int vector, int flags)
1318 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1319 BUG_ON(flags & MF_ACTION_REQUIRED);
1320 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1321 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1329 * Action optional processing happens here (picking up
1330 * from the list of faulting pages that do_machine_check()
1331 * placed into the genpool).
1333 static void mce_process_work(struct work_struct *dummy)
1335 mce_gen_pool_process();
1338 #ifdef CONFIG_X86_MCE_INTEL
1340 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1341 * @cpu: The CPU on which the event occurred.
1342 * @status: Event status information
1344 * This function should be called by the thermal interrupt after the
1345 * event has been processed and the decision was made to log the event
1348 * The status parameter will be saved to the 'status' field of 'struct mce'
1349 * and historically has been the register value of the
1350 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1352 void mce_log_therm_throt_event(__u64 status)
1357 m.bank = MCE_THERMAL_BANK;
1361 #endif /* CONFIG_X86_MCE_INTEL */
1364 * Periodic polling timer for "silent" machine check errors. If the
1365 * poller finds an MCE, poll 2x faster. When the poller finds no more
1366 * errors, poll 2x slower (up to check_interval seconds).
1368 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1370 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1371 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1373 static unsigned long mce_adjust_timer_default(unsigned long interval)
1378 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1380 static void __restart_timer(struct timer_list *t, unsigned long interval)
1382 unsigned long when = jiffies + interval;
1383 unsigned long flags;
1385 local_irq_save(flags);
1387 if (timer_pending(t)) {
1388 if (time_before(when, t->expires))
1391 t->expires = round_jiffies(when);
1392 add_timer_on(t, smp_processor_id());
1395 local_irq_restore(flags);
1398 static void mce_timer_fn(unsigned long data)
1400 struct timer_list *t = this_cpu_ptr(&mce_timer);
1401 int cpu = smp_processor_id();
1404 WARN_ON(cpu != data);
1406 iv = __this_cpu_read(mce_next_interval);
1408 if (mce_available(this_cpu_ptr(&cpu_info))) {
1409 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1411 if (mce_intel_cmci_poll()) {
1412 iv = mce_adjust_timer(iv);
1418 * Alert userspace if needed. If we logged an MCE, reduce the polling
1419 * interval, otherwise increase the polling interval.
1421 if (mce_notify_irq())
1422 iv = max(iv / 2, (unsigned long) HZ/100);
1424 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1427 __this_cpu_write(mce_next_interval, iv);
1428 __restart_timer(t, iv);
1432 * Ensure that the timer is firing in @interval from now.
1434 void mce_timer_kick(unsigned long interval)
1436 struct timer_list *t = this_cpu_ptr(&mce_timer);
1437 unsigned long iv = __this_cpu_read(mce_next_interval);
1439 __restart_timer(t, interval);
1442 __this_cpu_write(mce_next_interval, interval);
1445 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1446 static void mce_timer_delete_all(void)
1450 for_each_online_cpu(cpu)
1451 del_timer_sync(&per_cpu(mce_timer, cpu));
1454 static void mce_do_trigger(struct work_struct *work)
1456 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1459 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1462 * Notify the user(s) about new machine check events.
1463 * Can be called from interrupt context, but not from machine check/NMI
1466 int mce_notify_irq(void)
1468 /* Not more than two messages every minute */
1469 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1471 if (test_and_clear_bit(0, &mce_need_notify)) {
1472 /* wake processes polling /dev/mcelog */
1473 wake_up_interruptible(&mce_chrdev_wait);
1476 schedule_work(&mce_trigger_work);
1478 if (__ratelimit(&ratelimit))
1479 pr_info(HW_ERR "Machine check events logged\n");
1485 EXPORT_SYMBOL_GPL(mce_notify_irq);
1487 static int __mcheck_cpu_mce_banks_init(void)
1490 u8 num_banks = mca_cfg.banks;
1492 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1496 for (i = 0; i < num_banks; i++) {
1497 struct mce_bank *b = &mce_banks[i];
1506 * Initialize Machine Checks for a CPU.
1508 static int __mcheck_cpu_cap_init(void)
1513 rdmsrl(MSR_IA32_MCG_CAP, cap);
1515 b = cap & MCG_BANKCNT_MASK;
1517 pr_info("CPU supports %d MCE banks\n", b);
1519 if (b > MAX_NR_BANKS) {
1520 pr_warn("Using only %u machine check banks out of %u\n",
1525 /* Don't support asymmetric configurations today */
1526 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1530 int err = __mcheck_cpu_mce_banks_init();
1536 /* Use accurate RIP reporting if available. */
1537 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1538 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1540 if (cap & MCG_SER_P)
1546 static void __mcheck_cpu_init_generic(void)
1548 enum mcp_flags m_fl = 0;
1549 mce_banks_t all_banks;
1552 if (!mca_cfg.bootlog)
1556 * Log the machine checks left over from the previous reset.
1558 bitmap_fill(all_banks, MAX_NR_BANKS);
1559 machine_check_poll(MCP_UC | m_fl, &all_banks);
1561 cr4_set_bits(X86_CR4_MCE);
1563 rdmsrl(MSR_IA32_MCG_CAP, cap);
1564 if (cap & MCG_CTL_P)
1565 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1568 static void __mcheck_cpu_init_clear_banks(void)
1572 for (i = 0; i < mca_cfg.banks; i++) {
1573 struct mce_bank *b = &mce_banks[i];
1577 wrmsrl(msr_ops.ctl(i), b->ctl);
1578 wrmsrl(msr_ops.status(i), 0);
1583 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1584 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1585 * Vol 3B Table 15-20). But this confuses both the code that determines
1586 * whether the machine check occurred in kernel or user mode, and also
1587 * the severity assessment code. Pretend that EIPV was set, and take the
1588 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1590 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1594 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1596 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1597 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1598 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1600 (MCI_STATUS_UC|MCI_STATUS_EN|
1601 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1602 MCI_STATUS_AR|MCACOD_INSTR))
1605 m->mcgstatus |= MCG_STATUS_EIPV;
1610 /* Add per CPU specific workarounds here */
1611 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1613 struct mca_config *cfg = &mca_cfg;
1615 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1616 pr_info("unknown CPU type - not enabling MCE support\n");
1620 /* This should be disabled by the BIOS, but isn't always */
1621 if (c->x86_vendor == X86_VENDOR_AMD) {
1622 if (c->x86 == 15 && cfg->banks > 4) {
1624 * disable GART TBL walk error reporting, which
1625 * trips off incorrectly with the IOMMU & 3ware
1628 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1630 if (c->x86 < 17 && cfg->bootlog < 0) {
1632 * Lots of broken BIOS around that don't clear them
1633 * by default and leave crap in there. Don't log:
1638 * Various K7s with broken bank 0 around. Always disable
1641 if (c->x86 == 6 && cfg->banks > 0)
1642 mce_banks[0].ctl = 0;
1645 * overflow_recov is supported for F15h Models 00h-0fh
1646 * even though we don't have a CPUID bit for it.
1648 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1649 mce_flags.overflow_recov = 1;
1653 if (c->x86_vendor == X86_VENDOR_INTEL) {
1655 * SDM documents that on family 6 bank 0 should not be written
1656 * because it aliases to another special BIOS controlled
1658 * But it's not aliased anymore on model 0x1a+
1659 * Don't ignore bank 0 completely because there could be a
1660 * valid event later, merely don't write CTL0.
1663 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1664 mce_banks[0].init = 0;
1667 * All newer Intel systems support MCE broadcasting. Enable
1668 * synchronization with a one second timeout.
1670 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1671 cfg->monarch_timeout < 0)
1672 cfg->monarch_timeout = USEC_PER_SEC;
1675 * There are also broken BIOSes on some Pentium M and
1678 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1681 if (c->x86 == 6 && c->x86_model == 45)
1682 quirk_no_way_out = quirk_sandybridge_ifu;
1684 if (cfg->monarch_timeout < 0)
1685 cfg->monarch_timeout = 0;
1686 if (cfg->bootlog != 0)
1687 cfg->panic_timeout = 30;
1692 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1697 switch (c->x86_vendor) {
1698 case X86_VENDOR_INTEL:
1699 intel_p5_mcheck_init(c);
1702 case X86_VENDOR_CENTAUR:
1703 winchip_mcheck_init(c);
1714 * Init basic CPU features needed for early decoding of MCEs.
1716 static void __mcheck_cpu_init_early(struct cpuinfo_x86 *c)
1718 if (c->x86_vendor == X86_VENDOR_AMD) {
1719 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1720 mce_flags.succor = !!cpu_has(c, X86_FEATURE_SUCCOR);
1721 mce_flags.smca = !!cpu_has(c, X86_FEATURE_SMCA);
1723 if (mce_flags.smca) {
1724 msr_ops.ctl = smca_ctl_reg;
1725 msr_ops.status = smca_status_reg;
1726 msr_ops.addr = smca_addr_reg;
1727 msr_ops.misc = smca_misc_reg;
1732 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1734 switch (c->x86_vendor) {
1735 case X86_VENDOR_INTEL:
1736 mce_intel_feature_init(c);
1737 mce_adjust_timer = cmci_intel_adjust_timer;
1740 case X86_VENDOR_AMD: {
1741 mce_amd_feature_init(c);
1750 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1752 switch (c->x86_vendor) {
1753 case X86_VENDOR_INTEL:
1754 mce_intel_feature_clear(c);
1761 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1763 unsigned long iv = check_interval * HZ;
1765 if (mca_cfg.ignore_ce || !iv)
1768 per_cpu(mce_next_interval, cpu) = iv;
1770 t->expires = round_jiffies(jiffies + iv);
1771 add_timer_on(t, cpu);
1774 static void __mcheck_cpu_init_timer(void)
1776 struct timer_list *t = this_cpu_ptr(&mce_timer);
1777 unsigned int cpu = smp_processor_id();
1779 setup_pinned_timer(t, mce_timer_fn, cpu);
1780 mce_start_timer(cpu, t);
1783 /* Handle unconfigured int18 (should never happen) */
1784 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1786 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1787 smp_processor_id());
1790 /* Call the installed machine check handler for this CPU setup. */
1791 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1792 unexpected_machine_check;
1794 dotraplinkage void do_mce(struct pt_regs *regs, long error_code)
1796 machine_check_vector(regs, error_code);
1800 * Called for each booted CPU to set up machine checks.
1801 * Must be called with preempt off:
1803 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1805 if (mca_cfg.disabled)
1808 if (__mcheck_cpu_ancient_init(c))
1811 if (!mce_available(c))
1814 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1815 mca_cfg.disabled = true;
1819 if (mce_gen_pool_init()) {
1820 mca_cfg.disabled = true;
1821 pr_emerg("Couldn't allocate MCE records pool!\n");
1825 machine_check_vector = do_machine_check;
1827 __mcheck_cpu_init_early(c);
1828 __mcheck_cpu_init_generic();
1829 __mcheck_cpu_init_vendor(c);
1830 __mcheck_cpu_init_clear_banks();
1831 __mcheck_cpu_init_timer();
1835 * Called for each booted CPU to clear some machine checks opt-ins
1837 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1839 if (mca_cfg.disabled)
1842 if (!mce_available(c))
1846 * Possibly to clear general settings generic to x86
1847 * __mcheck_cpu_clear_generic(c);
1849 __mcheck_cpu_clear_vendor(c);
1854 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1857 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1858 static int mce_chrdev_open_count; /* #times opened */
1859 static int mce_chrdev_open_exclu; /* already open exclusive? */
1861 static int mce_chrdev_open(struct inode *inode, struct file *file)
1863 spin_lock(&mce_chrdev_state_lock);
1865 if (mce_chrdev_open_exclu ||
1866 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1867 spin_unlock(&mce_chrdev_state_lock);
1872 if (file->f_flags & O_EXCL)
1873 mce_chrdev_open_exclu = 1;
1874 mce_chrdev_open_count++;
1876 spin_unlock(&mce_chrdev_state_lock);
1878 return nonseekable_open(inode, file);
1881 static int mce_chrdev_release(struct inode *inode, struct file *file)
1883 spin_lock(&mce_chrdev_state_lock);
1885 mce_chrdev_open_count--;
1886 mce_chrdev_open_exclu = 0;
1888 spin_unlock(&mce_chrdev_state_lock);
1893 static void collect_tscs(void *data)
1895 unsigned long *cpu_tsc = (unsigned long *)data;
1897 cpu_tsc[smp_processor_id()] = rdtsc();
1900 static int mce_apei_read_done;
1902 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1903 static int __mce_read_apei(char __user **ubuf, size_t usize)
1909 if (usize < sizeof(struct mce))
1912 rc = apei_read_mce(&m, &record_id);
1913 /* Error or no more MCE record */
1915 mce_apei_read_done = 1;
1917 * When ERST is disabled, mce_chrdev_read() should return
1918 * "no record" instead of "no device."
1925 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1928 * In fact, we should have cleared the record after that has
1929 * been flushed to the disk or sent to network in
1930 * /sbin/mcelog, but we have no interface to support that now,
1931 * so just clear it to avoid duplication.
1933 rc = apei_clear_mce(record_id);
1935 mce_apei_read_done = 1;
1938 *ubuf += sizeof(struct mce);
1943 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1944 size_t usize, loff_t *off)
1946 char __user *buf = ubuf;
1947 unsigned long *cpu_tsc;
1948 unsigned prev, next;
1951 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1955 mutex_lock(&mce_chrdev_read_mutex);
1957 if (!mce_apei_read_done) {
1958 err = __mce_read_apei(&buf, usize);
1959 if (err || buf != ubuf)
1963 next = mce_log_get_idx_check(mcelog.next);
1965 /* Only supports full reads right now */
1967 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1973 for (i = prev; i < next; i++) {
1974 unsigned long start = jiffies;
1975 struct mce *m = &mcelog.entry[i];
1977 while (!m->finished) {
1978 if (time_after_eq(jiffies, start + 2)) {
1979 memset(m, 0, sizeof(*m));
1985 err |= copy_to_user(buf, m, sizeof(*m));
1991 memset(mcelog.entry + prev, 0,
1992 (next - prev) * sizeof(struct mce));
1994 next = cmpxchg(&mcelog.next, prev, 0);
1995 } while (next != prev);
1997 synchronize_sched();
2000 * Collect entries that were still getting written before the
2003 on_each_cpu(collect_tscs, cpu_tsc, 1);
2005 for (i = next; i < MCE_LOG_LEN; i++) {
2006 struct mce *m = &mcelog.entry[i];
2008 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
2009 err |= copy_to_user(buf, m, sizeof(*m));
2012 memset(m, 0, sizeof(*m));
2020 mutex_unlock(&mce_chrdev_read_mutex);
2023 return err ? err : buf - ubuf;
2026 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
2028 poll_wait(file, &mce_chrdev_wait, wait);
2029 if (READ_ONCE(mcelog.next))
2030 return POLLIN | POLLRDNORM;
2031 if (!mce_apei_read_done && apei_check_mce())
2032 return POLLIN | POLLRDNORM;
2036 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
2039 int __user *p = (int __user *)arg;
2041 if (!capable(CAP_SYS_ADMIN))
2045 case MCE_GET_RECORD_LEN:
2046 return put_user(sizeof(struct mce), p);
2047 case MCE_GET_LOG_LEN:
2048 return put_user(MCE_LOG_LEN, p);
2049 case MCE_GETCLEAR_FLAGS: {
2053 flags = mcelog.flags;
2054 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
2056 return put_user(flags, p);
2063 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
2064 size_t usize, loff_t *off);
2066 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
2067 const char __user *ubuf,
2068 size_t usize, loff_t *off))
2072 EXPORT_SYMBOL_GPL(register_mce_write_callback);
2074 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
2075 size_t usize, loff_t *off)
2078 return mce_write(filp, ubuf, usize, off);
2083 static const struct file_operations mce_chrdev_ops = {
2084 .open = mce_chrdev_open,
2085 .release = mce_chrdev_release,
2086 .read = mce_chrdev_read,
2087 .write = mce_chrdev_write,
2088 .poll = mce_chrdev_poll,
2089 .unlocked_ioctl = mce_chrdev_ioctl,
2090 .llseek = no_llseek,
2093 static struct miscdevice mce_chrdev_device = {
2099 static void __mce_disable_bank(void *arg)
2101 int bank = *((int *)arg);
2102 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2103 cmci_disable_bank(bank);
2106 void mce_disable_bank(int bank)
2108 if (bank >= mca_cfg.banks) {
2110 "Ignoring request to disable invalid MCA bank %d.\n",
2114 set_bit(bank, mce_banks_ce_disabled);
2115 on_each_cpu(__mce_disable_bank, &bank, 1);
2119 * mce=off Disables machine check
2120 * mce=no_cmci Disables CMCI
2121 * mce=no_lmce Disables LMCE
2122 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2123 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2124 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2125 * monarchtimeout is how long to wait for other CPUs on machine
2126 * check, or 0 to not wait
2127 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2128 * mce=nobootlog Don't log MCEs from before booting.
2129 * mce=bios_cmci_threshold Don't program the CMCI threshold
2130 * mce=recovery force enable memcpy_mcsafe()
2132 static int __init mcheck_enable(char *str)
2134 struct mca_config *cfg = &mca_cfg;
2142 if (!strcmp(str, "off"))
2143 cfg->disabled = true;
2144 else if (!strcmp(str, "no_cmci"))
2145 cfg->cmci_disabled = true;
2146 else if (!strcmp(str, "no_lmce"))
2147 cfg->lmce_disabled = true;
2148 else if (!strcmp(str, "dont_log_ce"))
2149 cfg->dont_log_ce = true;
2150 else if (!strcmp(str, "ignore_ce"))
2151 cfg->ignore_ce = true;
2152 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2153 cfg->bootlog = (str[0] == 'b');
2154 else if (!strcmp(str, "bios_cmci_threshold"))
2155 cfg->bios_cmci_threshold = true;
2156 else if (!strcmp(str, "recovery"))
2157 cfg->recovery = true;
2158 else if (isdigit(str[0])) {
2159 if (get_option(&str, &cfg->tolerant) == 2)
2160 get_option(&str, &(cfg->monarch_timeout));
2162 pr_info("mce argument %s ignored. Please use /sys\n", str);
2167 __setup("mce", mcheck_enable);
2169 int __init mcheck_init(void)
2171 mcheck_intel_therm_init();
2172 mce_register_decode_chain(&mce_srao_nb);
2173 mcheck_vendor_init_severity();
2175 INIT_WORK(&mce_work, mce_process_work);
2176 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2182 * mce_syscore: PM support
2186 * Disable machine checks on suspend and shutdown. We can't really handle
2189 static void mce_disable_error_reporting(void)
2193 for (i = 0; i < mca_cfg.banks; i++) {
2194 struct mce_bank *b = &mce_banks[i];
2197 wrmsrl(msr_ops.ctl(i), 0);
2202 static void vendor_disable_error_reporting(void)
2205 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2206 * Disabling them for just a single offlined CPU is bad, since it will
2207 * inhibit reporting for all shared resources on the socket like the
2208 * last level cache (LLC), the integrated memory controller (iMC), etc.
2210 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2213 mce_disable_error_reporting();
2216 static int mce_syscore_suspend(void)
2218 vendor_disable_error_reporting();
2222 static void mce_syscore_shutdown(void)
2224 vendor_disable_error_reporting();
2228 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2229 * Only one CPU is active at this time, the others get re-added later using
2232 static void mce_syscore_resume(void)
2234 __mcheck_cpu_init_generic();
2235 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2236 __mcheck_cpu_init_clear_banks();
2239 static struct syscore_ops mce_syscore_ops = {
2240 .suspend = mce_syscore_suspend,
2241 .shutdown = mce_syscore_shutdown,
2242 .resume = mce_syscore_resume,
2246 * mce_device: Sysfs support
2249 static void mce_cpu_restart(void *data)
2251 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2253 __mcheck_cpu_init_generic();
2254 __mcheck_cpu_init_clear_banks();
2255 __mcheck_cpu_init_timer();
2258 /* Reinit MCEs after user configuration changes */
2259 static void mce_restart(void)
2261 mce_timer_delete_all();
2262 on_each_cpu(mce_cpu_restart, NULL, 1);
2265 /* Toggle features for corrected errors */
2266 static void mce_disable_cmci(void *data)
2268 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2273 static void mce_enable_ce(void *all)
2275 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2280 __mcheck_cpu_init_timer();
2283 static struct bus_type mce_subsys = {
2284 .name = "machinecheck",
2285 .dev_name = "machinecheck",
2288 DEFINE_PER_CPU(struct device *, mce_device);
2290 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2292 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2294 return container_of(attr, struct mce_bank, attr);
2297 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2300 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2303 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2304 const char *buf, size_t size)
2308 if (kstrtou64(buf, 0, &new) < 0)
2311 attr_to_bank(attr)->ctl = new;
2318 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2320 strcpy(buf, mce_helper);
2322 return strlen(mce_helper) + 1;
2325 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2326 const char *buf, size_t siz)
2330 strncpy(mce_helper, buf, sizeof(mce_helper));
2331 mce_helper[sizeof(mce_helper)-1] = 0;
2332 p = strchr(mce_helper, '\n');
2337 return strlen(mce_helper) + !!p;
2340 static ssize_t set_ignore_ce(struct device *s,
2341 struct device_attribute *attr,
2342 const char *buf, size_t size)
2346 if (kstrtou64(buf, 0, &new) < 0)
2349 mutex_lock(&mce_sysfs_mutex);
2350 if (mca_cfg.ignore_ce ^ !!new) {
2352 /* disable ce features */
2353 mce_timer_delete_all();
2354 on_each_cpu(mce_disable_cmci, NULL, 1);
2355 mca_cfg.ignore_ce = true;
2357 /* enable ce features */
2358 mca_cfg.ignore_ce = false;
2359 on_each_cpu(mce_enable_ce, (void *)1, 1);
2362 mutex_unlock(&mce_sysfs_mutex);
2367 static ssize_t set_cmci_disabled(struct device *s,
2368 struct device_attribute *attr,
2369 const char *buf, size_t size)
2373 if (kstrtou64(buf, 0, &new) < 0)
2376 mutex_lock(&mce_sysfs_mutex);
2377 if (mca_cfg.cmci_disabled ^ !!new) {
2380 on_each_cpu(mce_disable_cmci, NULL, 1);
2381 mca_cfg.cmci_disabled = true;
2384 mca_cfg.cmci_disabled = false;
2385 on_each_cpu(mce_enable_ce, NULL, 1);
2388 mutex_unlock(&mce_sysfs_mutex);
2393 static ssize_t store_int_with_restart(struct device *s,
2394 struct device_attribute *attr,
2395 const char *buf, size_t size)
2397 unsigned long old_check_interval = check_interval;
2398 ssize_t ret = device_store_ulong(s, attr, buf, size);
2400 if (check_interval == old_check_interval)
2403 mutex_lock(&mce_sysfs_mutex);
2405 mutex_unlock(&mce_sysfs_mutex);
2410 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2411 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2412 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2413 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2415 static struct dev_ext_attribute dev_attr_check_interval = {
2416 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2420 static struct dev_ext_attribute dev_attr_ignore_ce = {
2421 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2425 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2426 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2427 &mca_cfg.cmci_disabled
2430 static struct device_attribute *mce_device_attrs[] = {
2431 &dev_attr_tolerant.attr,
2432 &dev_attr_check_interval.attr,
2434 &dev_attr_monarch_timeout.attr,
2435 &dev_attr_dont_log_ce.attr,
2436 &dev_attr_ignore_ce.attr,
2437 &dev_attr_cmci_disabled.attr,
2441 static cpumask_var_t mce_device_initialized;
2443 static void mce_device_release(struct device *dev)
2448 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2449 static int mce_device_create(unsigned int cpu)
2455 if (!mce_available(&boot_cpu_data))
2458 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2462 dev->bus = &mce_subsys;
2463 dev->release = &mce_device_release;
2465 err = device_register(dev);
2471 for (i = 0; mce_device_attrs[i]; i++) {
2472 err = device_create_file(dev, mce_device_attrs[i]);
2476 for (j = 0; j < mca_cfg.banks; j++) {
2477 err = device_create_file(dev, &mce_banks[j].attr);
2481 cpumask_set_cpu(cpu, mce_device_initialized);
2482 per_cpu(mce_device, cpu) = dev;
2487 device_remove_file(dev, &mce_banks[j].attr);
2490 device_remove_file(dev, mce_device_attrs[i]);
2492 device_unregister(dev);
2497 static void mce_device_remove(unsigned int cpu)
2499 struct device *dev = per_cpu(mce_device, cpu);
2502 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2505 for (i = 0; mce_device_attrs[i]; i++)
2506 device_remove_file(dev, mce_device_attrs[i]);
2508 for (i = 0; i < mca_cfg.banks; i++)
2509 device_remove_file(dev, &mce_banks[i].attr);
2511 device_unregister(dev);
2512 cpumask_clear_cpu(cpu, mce_device_initialized);
2513 per_cpu(mce_device, cpu) = NULL;
2516 /* Make sure there are no machine checks on offlined CPUs. */
2517 static void mce_disable_cpu(void *h)
2519 unsigned long action = *(unsigned long *)h;
2521 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2524 if (!(action & CPU_TASKS_FROZEN))
2527 vendor_disable_error_reporting();
2530 static void mce_reenable_cpu(void *h)
2532 unsigned long action = *(unsigned long *)h;
2535 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2538 if (!(action & CPU_TASKS_FROZEN))
2540 for (i = 0; i < mca_cfg.banks; i++) {
2541 struct mce_bank *b = &mce_banks[i];
2544 wrmsrl(msr_ops.ctl(i), b->ctl);
2548 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2550 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2552 unsigned int cpu = (unsigned long)hcpu;
2553 struct timer_list *t = &per_cpu(mce_timer, cpu);
2555 switch (action & ~CPU_TASKS_FROZEN) {
2557 mce_device_create(cpu);
2558 if (threshold_cpu_callback)
2559 threshold_cpu_callback(action, cpu);
2562 if (threshold_cpu_callback)
2563 threshold_cpu_callback(action, cpu);
2564 mce_device_remove(cpu);
2565 mce_intel_hcpu_update(cpu);
2567 /* intentionally ignoring frozen here */
2568 if (!(action & CPU_TASKS_FROZEN))
2571 case CPU_DOWN_PREPARE:
2572 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2575 case CPU_DOWN_FAILED:
2576 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2577 mce_start_timer(cpu, t);
2584 static struct notifier_block mce_cpu_notifier = {
2585 .notifier_call = mce_cpu_callback,
2588 static __init void mce_init_banks(void)
2592 for (i = 0; i < mca_cfg.banks; i++) {
2593 struct mce_bank *b = &mce_banks[i];
2594 struct device_attribute *a = &b->attr;
2596 sysfs_attr_init(&a->attr);
2597 a->attr.name = b->attrname;
2598 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2600 a->attr.mode = 0644;
2601 a->show = show_bank;
2602 a->store = set_bank;
2606 static __init int mcheck_init_device(void)
2611 if (!mce_available(&boot_cpu_data)) {
2616 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2623 err = subsys_system_register(&mce_subsys, NULL);
2627 cpu_notifier_register_begin();
2628 for_each_online_cpu(i) {
2629 err = mce_device_create(i);
2632 * Register notifier anyway (and do not unreg it) so
2633 * that we don't leave undeleted timers, see notifier
2636 __register_hotcpu_notifier(&mce_cpu_notifier);
2637 cpu_notifier_register_done();
2638 goto err_device_create;
2642 __register_hotcpu_notifier(&mce_cpu_notifier);
2643 cpu_notifier_register_done();
2645 register_syscore_ops(&mce_syscore_ops);
2647 /* register character device /dev/mcelog */
2648 err = misc_register(&mce_chrdev_device);
2655 unregister_syscore_ops(&mce_syscore_ops);
2659 * We didn't keep track of which devices were created above, but
2660 * even if we had, the set of online cpus might have changed.
2661 * Play safe and remove for every possible cpu, since
2662 * mce_device_remove() will do the right thing.
2664 for_each_possible_cpu(i)
2665 mce_device_remove(i);
2668 free_cpumask_var(mce_device_initialized);
2671 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2675 device_initcall_sync(mcheck_init_device);
2678 * Old style boot options parsing. Only for compatibility.
2680 static int __init mcheck_disable(char *str)
2682 mca_cfg.disabled = true;
2685 __setup("nomce", mcheck_disable);
2687 #ifdef CONFIG_DEBUG_FS
2688 struct dentry *mce_get_debugfs_dir(void)
2690 static struct dentry *dmce;
2693 dmce = debugfs_create_dir("mce", NULL);
2698 static void mce_reset(void)
2701 atomic_set(&mce_fake_panicked, 0);
2702 atomic_set(&mce_executing, 0);
2703 atomic_set(&mce_callin, 0);
2704 atomic_set(&global_nwo, 0);
2707 static int fake_panic_get(void *data, u64 *val)
2713 static int fake_panic_set(void *data, u64 val)
2720 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2721 fake_panic_set, "%llu\n");
2723 static int __init mcheck_debugfs_init(void)
2725 struct dentry *dmce, *ffake_panic;
2727 dmce = mce_get_debugfs_dir();
2730 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2738 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2741 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2742 EXPORT_SYMBOL_GPL(mcsafe_key);
2744 static int __init mcheck_late_init(void)
2746 if (mca_cfg.recovery)
2747 static_branch_inc(&mcsafe_key);
2749 mcheck_debugfs_init();
2752 * Flush out everything that has been logged during early boot, now that
2753 * everything has been initialized (workqueues, decoders, ...).
2755 mce_schedule_work();
2759 late_initcall(mcheck_late_init);