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/intel-family.h>
47 #include <asm/processor.h>
48 #include <asm/traps.h>
49 #include <asm/tlbflush.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 #define CREATE_TRACE_POINTS
66 #include <trace/events/mce.h>
68 #define SPINUNIT 100 /* 100ns */
70 DEFINE_PER_CPU(unsigned, mce_exception_count);
72 struct mce_bank *mce_banks __read_mostly;
73 struct mce_vendor_flags mce_flags __read_mostly;
75 struct mca_config mca_cfg __read_mostly = {
79 * 0: always panic on uncorrected errors, log corrected errors
80 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
81 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
82 * 3: never panic or SIGBUS, log all errors (for testing only)
88 /* User mode helper program triggered by machine check event */
89 static unsigned long mce_need_notify;
90 static char mce_helper[128];
91 static char *mce_helper_argv[2] = { mce_helper, NULL };
93 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
95 static DEFINE_PER_CPU(struct mce, mces_seen);
96 static int cpu_missing;
99 * MCA banks polled by the period polling timer for corrected events.
100 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
102 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
103 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
107 * MCA banks controlled through firmware first for corrected errors.
108 * This is a global list of banks for which we won't enable CMCI and we
109 * won't poll. Firmware controls these banks and is responsible for
110 * reporting corrected errors through GHES. Uncorrected/recoverable
111 * errors are still notified through a machine check.
113 mce_banks_t mce_banks_ce_disabled;
115 static struct work_struct mce_work;
116 static struct irq_work mce_irq_work;
118 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
121 * CPU/chipset specific EDAC code can register a notifier call here to print
122 * MCE errors in a human-readable form.
124 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
126 /* Do initial initialization of a struct mce */
127 void mce_setup(struct mce *m)
129 memset(m, 0, sizeof(struct mce));
130 m->cpu = m->extcpu = smp_processor_id();
131 /* We hope get_seconds stays lockless */
132 m->time = get_seconds();
133 m->cpuvendor = boot_cpu_data.x86_vendor;
134 m->cpuid = cpuid_eax(1);
135 m->socketid = cpu_data(m->extcpu).phys_proc_id;
136 m->apicid = cpu_data(m->extcpu).initial_apicid;
137 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
139 if (this_cpu_has(X86_FEATURE_INTEL_PPIN))
140 rdmsrl(MSR_PPIN, m->ppin);
143 DEFINE_PER_CPU(struct mce, injectm);
144 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
147 * Lockless MCE logging infrastructure.
148 * This avoids deadlocks on printk locks without having to break locks. Also
149 * separate MCEs from kernel messages to avoid bogus bug reports.
152 static struct mce_log mcelog = {
153 .signature = MCE_LOG_SIGNATURE,
155 .recordlen = sizeof(struct mce),
158 void mce_log(struct mce *mce)
160 unsigned next, entry;
162 /* Emit the trace record: */
163 trace_mce_record(mce);
165 if (!mce_gen_pool_add(mce))
166 irq_work_queue(&mce_irq_work);
170 entry = mce_log_get_idx_check(mcelog.next);
174 * When the buffer fills up discard new entries.
175 * Assume that the earlier errors are the more
178 if (entry >= MCE_LOG_LEN) {
179 set_bit(MCE_OVERFLOW,
180 (unsigned long *)&mcelog.flags);
183 /* Old left over entry. Skip: */
184 if (mcelog.entry[entry].finished) {
192 if (cmpxchg(&mcelog.next, entry, next) == entry)
195 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
197 mcelog.entry[entry].finished = 1;
200 set_bit(0, &mce_need_notify);
203 void mce_inject_log(struct mce *m)
205 mutex_lock(&mce_chrdev_read_mutex);
207 mutex_unlock(&mce_chrdev_read_mutex);
209 EXPORT_SYMBOL_GPL(mce_inject_log);
211 static struct notifier_block mce_srao_nb;
213 static atomic_t num_notifiers;
215 void mce_register_decode_chain(struct notifier_block *nb)
217 atomic_inc(&num_notifiers);
219 WARN_ON(nb->priority > MCE_PRIO_LOWEST && nb->priority < MCE_PRIO_EDAC);
221 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
223 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
225 void mce_unregister_decode_chain(struct notifier_block *nb)
227 atomic_dec(&num_notifiers);
229 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
231 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
233 static inline u32 ctl_reg(int bank)
235 return MSR_IA32_MCx_CTL(bank);
238 static inline u32 status_reg(int bank)
240 return MSR_IA32_MCx_STATUS(bank);
243 static inline u32 addr_reg(int bank)
245 return MSR_IA32_MCx_ADDR(bank);
248 static inline u32 misc_reg(int bank)
250 return MSR_IA32_MCx_MISC(bank);
253 static inline u32 smca_ctl_reg(int bank)
255 return MSR_AMD64_SMCA_MCx_CTL(bank);
258 static inline u32 smca_status_reg(int bank)
260 return MSR_AMD64_SMCA_MCx_STATUS(bank);
263 static inline u32 smca_addr_reg(int bank)
265 return MSR_AMD64_SMCA_MCx_ADDR(bank);
268 static inline u32 smca_misc_reg(int bank)
270 return MSR_AMD64_SMCA_MCx_MISC(bank);
273 struct mca_msr_regs msr_ops = {
275 .status = status_reg,
280 static void __print_mce(struct mce *m)
282 pr_emerg(HW_ERR "CPU %d: Machine Check%s: %Lx Bank %d: %016Lx\n",
284 (m->mcgstatus & MCG_STATUS_MCIP ? " Exception" : ""),
285 m->mcgstatus, m->bank, m->status);
288 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
289 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
292 if (m->cs == __KERNEL_CS)
293 print_symbol("{%s}", m->ip);
297 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
299 pr_cont("ADDR %llx ", m->addr);
301 pr_cont("MISC %llx ", m->misc);
303 if (mce_flags.smca) {
305 pr_cont("SYND %llx ", m->synd);
307 pr_cont("IPID %llx ", m->ipid);
312 * Note this output is parsed by external tools and old fields
313 * should not be changed.
315 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
316 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
317 cpu_data(m->extcpu).microcode);
320 static void print_mce(struct mce *m)
327 * Print out human-readable details about the MCE error,
328 * (if the CPU has an implementation for that)
330 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
331 if (ret == NOTIFY_STOP)
334 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
337 #define PANIC_TIMEOUT 5 /* 5 seconds */
339 static atomic_t mce_panicked;
341 static int fake_panic;
342 static atomic_t mce_fake_panicked;
344 /* Panic in progress. Enable interrupts and wait for final IPI */
345 static void wait_for_panic(void)
347 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
351 while (timeout-- > 0)
353 if (panic_timeout == 0)
354 panic_timeout = mca_cfg.panic_timeout;
355 panic("Panicing machine check CPU died");
358 static void mce_panic(const char *msg, struct mce *final, char *exp)
361 struct llist_node *pending;
362 struct mce_evt_llist *l;
366 * Make sure only one CPU runs in machine check panic
368 if (atomic_inc_return(&mce_panicked) > 1)
375 /* Don't log too much for fake panic */
376 if (atomic_inc_return(&mce_fake_panicked) > 1)
379 pending = mce_gen_pool_prepare_records();
380 /* First print corrected ones that are still unlogged */
381 llist_for_each_entry(l, pending, llnode) {
382 struct mce *m = &l->mce;
383 if (!(m->status & MCI_STATUS_UC)) {
386 apei_err = apei_write_mce(m);
389 /* Now print uncorrected but with the final one last */
390 llist_for_each_entry(l, pending, llnode) {
391 struct mce *m = &l->mce;
392 if (!(m->status & MCI_STATUS_UC))
394 if (!final || mce_cmp(m, final)) {
397 apei_err = apei_write_mce(m);
403 apei_err = apei_write_mce(final);
406 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
408 pr_emerg(HW_ERR "Machine check: %s\n", exp);
410 if (panic_timeout == 0)
411 panic_timeout = mca_cfg.panic_timeout;
414 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
417 /* Support code for software error injection */
419 static int msr_to_offset(u32 msr)
421 unsigned bank = __this_cpu_read(injectm.bank);
423 if (msr == mca_cfg.rip_msr)
424 return offsetof(struct mce, ip);
425 if (msr == msr_ops.status(bank))
426 return offsetof(struct mce, status);
427 if (msr == msr_ops.addr(bank))
428 return offsetof(struct mce, addr);
429 if (msr == msr_ops.misc(bank))
430 return offsetof(struct mce, misc);
431 if (msr == MSR_IA32_MCG_STATUS)
432 return offsetof(struct mce, mcgstatus);
436 /* MSR access wrappers used for error injection */
437 static u64 mce_rdmsrl(u32 msr)
441 if (__this_cpu_read(injectm.finished)) {
442 int offset = msr_to_offset(msr);
446 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
449 if (rdmsrl_safe(msr, &v)) {
450 WARN_ONCE(1, "mce: Unable to read MSR 0x%x!\n", msr);
452 * Return zero in case the access faulted. This should
453 * not happen normally but can happen if the CPU does
454 * something weird, or if the code is buggy.
462 static void mce_wrmsrl(u32 msr, u64 v)
464 if (__this_cpu_read(injectm.finished)) {
465 int offset = msr_to_offset(msr);
468 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
475 * Collect all global (w.r.t. this processor) status about this machine
476 * check into our "mce" struct so that we can use it later to assess
477 * the severity of the problem as we read per-bank specific details.
479 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
483 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
486 * Get the address of the instruction at the time of
487 * the machine check error.
489 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
494 * When in VM86 mode make the cs look like ring 3
495 * always. This is a lie, but it's better than passing
496 * the additional vm86 bit around everywhere.
498 if (v8086_mode(regs))
501 /* Use accurate RIP reporting if available. */
503 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
507 int mce_available(struct cpuinfo_x86 *c)
509 if (mca_cfg.disabled)
511 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
514 static void mce_schedule_work(void)
516 if (!mce_gen_pool_empty())
517 schedule_work(&mce_work);
520 static void mce_irq_work_cb(struct irq_work *entry)
526 static void mce_report_event(struct pt_regs *regs)
528 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
531 * Triggering the work queue here is just an insurance
532 * policy in case the syscall exit notify handler
533 * doesn't run soon enough or ends up running on the
534 * wrong CPU (can happen when audit sleeps)
540 irq_work_queue(&mce_irq_work);
544 * Check if the address reported by the CPU is in a format we can parse.
545 * It would be possible to add code for most other cases, but all would
546 * be somewhat complicated (e.g. segment offset would require an instruction
547 * parser). So only support physical addresses up to page granuality for now.
549 static int mce_usable_address(struct mce *m)
551 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
554 /* Checks after this one are Intel-specific: */
555 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
558 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
560 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
565 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
568 struct mce *mce = (struct mce *)data;
574 if (mce_usable_address(mce) && (mce->severity == MCE_AO_SEVERITY)) {
575 pfn = mce->addr >> PAGE_SHIFT;
576 memory_failure(pfn, MCE_VECTOR, 0);
581 static struct notifier_block mce_srao_nb = {
582 .notifier_call = srao_decode_notifier,
583 .priority = MCE_PRIO_SRAO,
586 static int mce_default_notifier(struct notifier_block *nb, unsigned long val,
589 struct mce *m = (struct mce *)data;
595 * Run the default notifier if we have only the SRAO
596 * notifier and us registered.
598 if (atomic_read(&num_notifiers) > 2)
606 static struct notifier_block mce_default_nb = {
607 .notifier_call = mce_default_notifier,
608 /* lowest prio, we want it to run last. */
609 .priority = MCE_PRIO_LOWEST,
613 * Read ADDR and MISC registers.
615 static void mce_read_aux(struct mce *m, int i)
617 if (m->status & MCI_STATUS_MISCV)
618 m->misc = mce_rdmsrl(msr_ops.misc(i));
620 if (m->status & MCI_STATUS_ADDRV) {
621 m->addr = mce_rdmsrl(msr_ops.addr(i));
624 * Mask the reported address by the reported granularity.
626 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
627 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
633 * Extract [55:<lsb>] where lsb is the least significant
634 * *valid* bit of the address bits.
636 if (mce_flags.smca) {
637 u8 lsb = (m->addr >> 56) & 0x3f;
639 m->addr &= GENMASK_ULL(55, lsb);
643 if (mce_flags.smca) {
644 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
646 if (m->status & MCI_STATUS_SYNDV)
647 m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
651 static bool memory_error(struct mce *m)
653 struct cpuinfo_x86 *c = &boot_cpu_data;
655 if (c->x86_vendor == X86_VENDOR_AMD) {
656 /* ErrCodeExt[20:16] */
657 u8 xec = (m->status >> 16) & 0x1f;
659 return (xec == 0x0 || xec == 0x8);
660 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
662 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
664 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
665 * indicating a memory error. Bit 8 is used for indicating a
666 * cache hierarchy error. The combination of bit 2 and bit 3
667 * is used for indicating a `generic' cache hierarchy error
668 * But we can't just blindly check the above bits, because if
669 * bit 11 is set, then it is a bus/interconnect error - and
670 * either way the above bits just gives more detail on what
671 * bus/interconnect error happened. Note that bit 12 can be
672 * ignored, as it's the "filter" bit.
674 return (m->status & 0xef80) == BIT(7) ||
675 (m->status & 0xef00) == BIT(8) ||
676 (m->status & 0xeffc) == 0xc;
682 DEFINE_PER_CPU(unsigned, mce_poll_count);
685 * Poll for corrected events or events that happened before reset.
686 * Those are just logged through /dev/mcelog.
688 * This is executed in standard interrupt context.
690 * Note: spec recommends to panic for fatal unsignalled
691 * errors here. However this would be quite problematic --
692 * we would need to reimplement the Monarch handling and
693 * it would mess up the exclusion between exception handler
694 * and poll hander -- * so we skip this for now.
695 * These cases should not happen anyways, or only when the CPU
696 * is already totally * confused. In this case it's likely it will
697 * not fully execute the machine check handler either.
699 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
701 bool error_seen = false;
706 this_cpu_inc(mce_poll_count);
708 mce_gather_info(&m, NULL);
710 if (flags & MCP_TIMESTAMP)
713 for (i = 0; i < mca_cfg.banks; i++) {
714 if (!mce_banks[i].ctl || !test_bit(i, *b))
722 m.status = mce_rdmsrl(msr_ops.status(i));
723 if (!(m.status & MCI_STATUS_VAL))
727 * Uncorrected or signalled events are handled by the exception
728 * handler when it is enabled, so don't process those here.
730 * TBD do the same check for MCI_STATUS_EN here?
732 if (!(flags & MCP_UC) &&
733 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
740 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
742 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m))
743 if (m.status & MCI_STATUS_ADDRV)
744 m.severity = severity;
747 * Don't get the IP here because it's unlikely to
748 * have anything to do with the actual error location.
750 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
752 else if (mce_usable_address(&m)) {
754 * Although we skipped logging this, we still want
755 * to take action. Add to the pool so the registered
756 * notifiers will see it.
758 if (!mce_gen_pool_add(&m))
763 * Clear state for this bank.
765 mce_wrmsrl(msr_ops.status(i), 0);
769 * Don't clear MCG_STATUS here because it's only defined for
777 EXPORT_SYMBOL_GPL(machine_check_poll);
780 * Do a quick check if any of the events requires a panic.
781 * This decides if we keep the events around or clear them.
783 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
784 struct pt_regs *regs)
789 for (i = 0; i < mca_cfg.banks; i++) {
790 m->status = mce_rdmsrl(msr_ops.status(i));
791 if (m->status & MCI_STATUS_VAL) {
792 __set_bit(i, validp);
793 if (quirk_no_way_out)
794 quirk_no_way_out(i, m, regs);
797 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
806 * Variable to establish order between CPUs while scanning.
807 * Each CPU spins initially until executing is equal its number.
809 static atomic_t mce_executing;
812 * Defines order of CPUs on entry. First CPU becomes Monarch.
814 static atomic_t mce_callin;
817 * Check if a timeout waiting for other CPUs happened.
819 static int mce_timed_out(u64 *t, const char *msg)
822 * The others already did panic for some reason.
823 * Bail out like in a timeout.
824 * rmb() to tell the compiler that system_state
825 * might have been modified by someone else.
828 if (atomic_read(&mce_panicked))
830 if (!mca_cfg.monarch_timeout)
832 if ((s64)*t < SPINUNIT) {
833 if (mca_cfg.tolerant <= 1)
834 mce_panic(msg, NULL, NULL);
840 touch_nmi_watchdog();
845 * The Monarch's reign. The Monarch is the CPU who entered
846 * the machine check handler first. It waits for the others to
847 * raise the exception too and then grades them. When any
848 * error is fatal panic. Only then let the others continue.
850 * The other CPUs entering the MCE handler will be controlled by the
851 * Monarch. They are called Subjects.
853 * This way we prevent any potential data corruption in a unrecoverable case
854 * and also makes sure always all CPU's errors are examined.
856 * Also this detects the case of a machine check event coming from outer
857 * space (not detected by any CPUs) In this case some external agent wants
858 * us to shut down, so panic too.
860 * The other CPUs might still decide to panic if the handler happens
861 * in a unrecoverable place, but in this case the system is in a semi-stable
862 * state and won't corrupt anything by itself. It's ok to let the others
863 * continue for a bit first.
865 * All the spin loops have timeouts; when a timeout happens a CPU
866 * typically elects itself to be Monarch.
868 static void mce_reign(void)
871 struct mce *m = NULL;
872 int global_worst = 0;
877 * This CPU is the Monarch and the other CPUs have run
878 * through their handlers.
879 * Grade the severity of the errors of all the CPUs.
881 for_each_possible_cpu(cpu) {
882 int severity = mce_severity(&per_cpu(mces_seen, cpu),
885 if (severity > global_worst) {
887 global_worst = severity;
888 m = &per_cpu(mces_seen, cpu);
893 * Cannot recover? Panic here then.
894 * This dumps all the mces in the log buffer and stops the
897 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
898 mce_panic("Fatal machine check", m, msg);
901 * For UC somewhere we let the CPU who detects it handle it.
902 * Also must let continue the others, otherwise the handling
903 * CPU could deadlock on a lock.
907 * No machine check event found. Must be some external
908 * source or one CPU is hung. Panic.
910 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
911 mce_panic("Fatal machine check from unknown source", NULL, NULL);
914 * Now clear all the mces_seen so that they don't reappear on
917 for_each_possible_cpu(cpu)
918 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
921 static atomic_t global_nwo;
924 * Start of Monarch synchronization. This waits until all CPUs have
925 * entered the exception handler and then determines if any of them
926 * saw a fatal event that requires panic. Then it executes them
927 * in the entry order.
928 * TBD double check parallel CPU hotunplug
930 static int mce_start(int *no_way_out)
933 int cpus = num_online_cpus();
934 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
939 atomic_add(*no_way_out, &global_nwo);
941 * Rely on the implied barrier below, such that global_nwo
942 * is updated before mce_callin.
944 order = atomic_inc_return(&mce_callin);
949 while (atomic_read(&mce_callin) != cpus) {
950 if (mce_timed_out(&timeout,
951 "Timeout: Not all CPUs entered broadcast exception handler")) {
952 atomic_set(&global_nwo, 0);
959 * mce_callin should be read before global_nwo
965 * Monarch: Starts executing now, the others wait.
967 atomic_set(&mce_executing, 1);
970 * Subject: Now start the scanning loop one by one in
971 * the original callin order.
972 * This way when there are any shared banks it will be
973 * only seen by one CPU before cleared, avoiding duplicates.
975 while (atomic_read(&mce_executing) < order) {
976 if (mce_timed_out(&timeout,
977 "Timeout: Subject CPUs unable to finish machine check processing")) {
978 atomic_set(&global_nwo, 0);
986 * Cache the global no_way_out state.
988 *no_way_out = atomic_read(&global_nwo);
994 * Synchronize between CPUs after main scanning loop.
995 * This invokes the bulk of the Monarch processing.
997 static int mce_end(int order)
1000 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
1008 * Allow others to run.
1010 atomic_inc(&mce_executing);
1013 /* CHECKME: Can this race with a parallel hotplug? */
1014 int cpus = num_online_cpus();
1017 * Monarch: Wait for everyone to go through their scanning
1020 while (atomic_read(&mce_executing) <= cpus) {
1021 if (mce_timed_out(&timeout,
1022 "Timeout: Monarch CPU unable to finish machine check processing"))
1032 * Subject: Wait for Monarch to finish.
1034 while (atomic_read(&mce_executing) != 0) {
1035 if (mce_timed_out(&timeout,
1036 "Timeout: Monarch CPU did not finish machine check processing"))
1042 * Don't reset anything. That's done by the Monarch.
1048 * Reset all global state.
1051 atomic_set(&global_nwo, 0);
1052 atomic_set(&mce_callin, 0);
1056 * Let others run again.
1058 atomic_set(&mce_executing, 0);
1062 static void mce_clear_state(unsigned long *toclear)
1066 for (i = 0; i < mca_cfg.banks; i++) {
1067 if (test_bit(i, toclear))
1068 mce_wrmsrl(msr_ops.status(i), 0);
1072 static int do_memory_failure(struct mce *m)
1074 int flags = MF_ACTION_REQUIRED;
1077 pr_err("Uncorrected hardware memory error in user-access at %llx", m->addr);
1078 if (!(m->mcgstatus & MCG_STATUS_RIPV))
1079 flags |= MF_MUST_KILL;
1080 ret = memory_failure(m->addr >> PAGE_SHIFT, MCE_VECTOR, flags);
1082 pr_err("Memory error not recovered");
1087 * The actual machine check handler. This only handles real
1088 * exceptions when something got corrupted coming in through int 18.
1090 * This is executed in NMI context not subject to normal locking rules. This
1091 * implies that most kernel services cannot be safely used. Don't even
1092 * think about putting a printk in there!
1094 * On Intel systems this is entered on all CPUs in parallel through
1095 * MCE broadcast. However some CPUs might be broken beyond repair,
1096 * so be always careful when synchronizing with others.
1098 void do_machine_check(struct pt_regs *regs, long error_code)
1100 struct mca_config *cfg = &mca_cfg;
1101 struct mce m, *final;
1107 * Establish sequential order between the CPUs entering the machine
1112 * If no_way_out gets set, there is no safe way to recover from this
1113 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1117 * If kill_it gets set, there might be a way to recover from this
1121 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1122 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1123 char *msg = "Unknown";
1126 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1131 /* If this CPU is offline, just bail out. */
1132 if (cpu_is_offline(smp_processor_id())) {
1135 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1136 if (mcgstatus & MCG_STATUS_RIPV) {
1137 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1144 this_cpu_inc(mce_exception_count);
1149 mce_gather_info(&m, regs);
1152 final = this_cpu_ptr(&mces_seen);
1155 memset(valid_banks, 0, sizeof(valid_banks));
1156 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1161 * When no restart IP might need to kill or panic.
1162 * Assume the worst for now, but if we find the
1163 * severity is MCE_AR_SEVERITY we have other options.
1165 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1169 * Check if this MCE is signaled to only this logical processor,
1172 if (m.cpuvendor == X86_VENDOR_INTEL)
1173 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1176 * Go through all banks in exclusion of the other CPUs. This way we
1177 * don't report duplicated events on shared banks because the first one
1178 * to see it will clear it. If this is a Local MCE, then no need to
1179 * perform rendezvous.
1182 order = mce_start(&no_way_out);
1184 for (i = 0; i < cfg->banks; i++) {
1185 __clear_bit(i, toclear);
1186 if (!test_bit(i, valid_banks))
1188 if (!mce_banks[i].ctl)
1195 m.status = mce_rdmsrl(msr_ops.status(i));
1196 if ((m.status & MCI_STATUS_VAL) == 0)
1200 * Non uncorrected or non signaled errors are handled by
1201 * machine_check_poll. Leave them alone, unless this panics.
1203 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1208 * Set taint even when machine check was not enabled.
1210 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1212 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1215 * When machine check was for corrected/deferred handler don't
1216 * touch, unless we're panicing.
1218 if ((severity == MCE_KEEP_SEVERITY ||
1219 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1221 __set_bit(i, toclear);
1222 if (severity == MCE_NO_SEVERITY) {
1224 * Machine check event was not enabled. Clear, but
1230 mce_read_aux(&m, i);
1232 /* assuming valid severity level != 0 */
1233 m.severity = severity;
1237 if (severity > worst) {
1243 /* mce_clear_state will clear *final, save locally for use later */
1247 mce_clear_state(toclear);
1250 * Do most of the synchronization with other CPUs.
1251 * When there's any problem use only local no_way_out state.
1254 if (mce_end(order) < 0)
1255 no_way_out = worst >= MCE_PANIC_SEVERITY;
1258 * Local MCE skipped calling mce_reign()
1259 * If we found a fatal error, we need to panic here.
1261 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1262 mce_panic("Machine check from unknown source",
1267 * If tolerant is at an insane level we drop requests to kill
1268 * processes and continue even when there is no way out.
1270 if (cfg->tolerant == 3)
1272 else if (no_way_out)
1273 mce_panic("Fatal machine check on current CPU", &m, msg);
1276 mce_report_event(regs);
1277 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1281 if (worst != MCE_AR_SEVERITY && !kill_it)
1284 /* Fault was in user mode and we need to take some action */
1285 if ((m.cs & 3) == 3) {
1286 ist_begin_non_atomic(regs);
1289 if (kill_it || do_memory_failure(&m))
1290 force_sig(SIGBUS, current);
1291 local_irq_disable();
1292 ist_end_non_atomic();
1294 if (!fixup_exception(regs, X86_TRAP_MC))
1295 mce_panic("Failed kernel mode recovery", &m, NULL);
1301 EXPORT_SYMBOL_GPL(do_machine_check);
1303 #ifndef CONFIG_MEMORY_FAILURE
1304 int memory_failure(unsigned long pfn, int vector, int flags)
1306 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1307 BUG_ON(flags & MF_ACTION_REQUIRED);
1308 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1309 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1317 * Periodic polling timer for "silent" machine check errors. If the
1318 * poller finds an MCE, poll 2x faster. When the poller finds no more
1319 * errors, poll 2x slower (up to check_interval seconds).
1321 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1323 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1324 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1326 static unsigned long mce_adjust_timer_default(unsigned long interval)
1331 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1333 static void __start_timer(struct timer_list *t, unsigned long interval)
1335 unsigned long when = jiffies + interval;
1336 unsigned long flags;
1338 local_irq_save(flags);
1340 if (!timer_pending(t) || time_before(when, t->expires))
1341 mod_timer(t, round_jiffies(when));
1343 local_irq_restore(flags);
1346 static void mce_timer_fn(unsigned long data)
1348 struct timer_list *t = this_cpu_ptr(&mce_timer);
1349 int cpu = smp_processor_id();
1352 WARN_ON(cpu != data);
1354 iv = __this_cpu_read(mce_next_interval);
1356 if (mce_available(this_cpu_ptr(&cpu_info))) {
1357 machine_check_poll(0, this_cpu_ptr(&mce_poll_banks));
1359 if (mce_intel_cmci_poll()) {
1360 iv = mce_adjust_timer(iv);
1366 * Alert userspace if needed. If we logged an MCE, reduce the polling
1367 * interval, otherwise increase the polling interval.
1369 if (mce_notify_irq())
1370 iv = max(iv / 2, (unsigned long) HZ/100);
1372 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1375 __this_cpu_write(mce_next_interval, iv);
1376 __start_timer(t, iv);
1380 * Ensure that the timer is firing in @interval from now.
1382 void mce_timer_kick(unsigned long interval)
1384 struct timer_list *t = this_cpu_ptr(&mce_timer);
1385 unsigned long iv = __this_cpu_read(mce_next_interval);
1387 __start_timer(t, interval);
1390 __this_cpu_write(mce_next_interval, interval);
1393 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1394 static void mce_timer_delete_all(void)
1398 for_each_online_cpu(cpu)
1399 del_timer_sync(&per_cpu(mce_timer, cpu));
1402 static void mce_do_trigger(struct work_struct *work)
1404 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1407 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1410 * Notify the user(s) about new machine check events.
1411 * Can be called from interrupt context, but not from machine check/NMI
1414 int mce_notify_irq(void)
1416 /* Not more than two messages every minute */
1417 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1419 if (test_and_clear_bit(0, &mce_need_notify)) {
1420 /* wake processes polling /dev/mcelog */
1421 wake_up_interruptible(&mce_chrdev_wait);
1424 schedule_work(&mce_trigger_work);
1426 if (__ratelimit(&ratelimit))
1427 pr_info(HW_ERR "Machine check events logged\n");
1433 EXPORT_SYMBOL_GPL(mce_notify_irq);
1435 static int __mcheck_cpu_mce_banks_init(void)
1438 u8 num_banks = mca_cfg.banks;
1440 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1444 for (i = 0; i < num_banks; i++) {
1445 struct mce_bank *b = &mce_banks[i];
1454 * Initialize Machine Checks for a CPU.
1456 static int __mcheck_cpu_cap_init(void)
1461 rdmsrl(MSR_IA32_MCG_CAP, cap);
1463 b = cap & MCG_BANKCNT_MASK;
1465 pr_info("CPU supports %d MCE banks\n", b);
1467 if (b > MAX_NR_BANKS) {
1468 pr_warn("Using only %u machine check banks out of %u\n",
1473 /* Don't support asymmetric configurations today */
1474 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1478 int err = __mcheck_cpu_mce_banks_init();
1484 /* Use accurate RIP reporting if available. */
1485 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1486 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1488 if (cap & MCG_SER_P)
1494 static void __mcheck_cpu_init_generic(void)
1496 enum mcp_flags m_fl = 0;
1497 mce_banks_t all_banks;
1500 if (!mca_cfg.bootlog)
1504 * Log the machine checks left over from the previous reset.
1506 bitmap_fill(all_banks, MAX_NR_BANKS);
1507 machine_check_poll(MCP_UC | m_fl, &all_banks);
1509 cr4_set_bits(X86_CR4_MCE);
1511 rdmsrl(MSR_IA32_MCG_CAP, cap);
1512 if (cap & MCG_CTL_P)
1513 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1516 static void __mcheck_cpu_init_clear_banks(void)
1520 for (i = 0; i < mca_cfg.banks; i++) {
1521 struct mce_bank *b = &mce_banks[i];
1525 wrmsrl(msr_ops.ctl(i), b->ctl);
1526 wrmsrl(msr_ops.status(i), 0);
1531 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1532 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1533 * Vol 3B Table 15-20). But this confuses both the code that determines
1534 * whether the machine check occurred in kernel or user mode, and also
1535 * the severity assessment code. Pretend that EIPV was set, and take the
1536 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1538 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1542 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1544 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1545 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1546 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1548 (MCI_STATUS_UC|MCI_STATUS_EN|
1549 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1550 MCI_STATUS_AR|MCACOD_INSTR))
1553 m->mcgstatus |= MCG_STATUS_EIPV;
1558 /* Add per CPU specific workarounds here */
1559 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1561 struct mca_config *cfg = &mca_cfg;
1563 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1564 pr_info("unknown CPU type - not enabling MCE support\n");
1568 /* This should be disabled by the BIOS, but isn't always */
1569 if (c->x86_vendor == X86_VENDOR_AMD) {
1570 if (c->x86 == 15 && cfg->banks > 4) {
1572 * disable GART TBL walk error reporting, which
1573 * trips off incorrectly with the IOMMU & 3ware
1576 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1578 if (c->x86 < 17 && cfg->bootlog < 0) {
1580 * Lots of broken BIOS around that don't clear them
1581 * by default and leave crap in there. Don't log:
1586 * Various K7s with broken bank 0 around. Always disable
1589 if (c->x86 == 6 && cfg->banks > 0)
1590 mce_banks[0].ctl = 0;
1593 * overflow_recov is supported for F15h Models 00h-0fh
1594 * even though we don't have a CPUID bit for it.
1596 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1597 mce_flags.overflow_recov = 1;
1600 * Turn off MC4_MISC thresholding banks on those models since
1601 * they're not supported there.
1603 if (c->x86 == 0x15 &&
1604 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1609 0x00000413, /* MC4_MISC0 */
1610 0xc0000408, /* MC4_MISC1 */
1613 rdmsrl(MSR_K7_HWCR, hwcr);
1615 /* McStatusWrEn has to be set */
1616 need_toggle = !(hwcr & BIT(18));
1619 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1621 /* Clear CntP bit safely */
1622 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1623 msr_clear_bit(msrs[i], 62);
1625 /* restore old settings */
1627 wrmsrl(MSR_K7_HWCR, hwcr);
1631 if (c->x86_vendor == X86_VENDOR_INTEL) {
1633 * SDM documents that on family 6 bank 0 should not be written
1634 * because it aliases to another special BIOS controlled
1636 * But it's not aliased anymore on model 0x1a+
1637 * Don't ignore bank 0 completely because there could be a
1638 * valid event later, merely don't write CTL0.
1641 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1642 mce_banks[0].init = 0;
1645 * All newer Intel systems support MCE broadcasting. Enable
1646 * synchronization with a one second timeout.
1648 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1649 cfg->monarch_timeout < 0)
1650 cfg->monarch_timeout = USEC_PER_SEC;
1653 * There are also broken BIOSes on some Pentium M and
1656 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1659 if (c->x86 == 6 && c->x86_model == 45)
1660 quirk_no_way_out = quirk_sandybridge_ifu;
1662 if (cfg->monarch_timeout < 0)
1663 cfg->monarch_timeout = 0;
1664 if (cfg->bootlog != 0)
1665 cfg->panic_timeout = 30;
1670 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1675 switch (c->x86_vendor) {
1676 case X86_VENDOR_INTEL:
1677 intel_p5_mcheck_init(c);
1680 case X86_VENDOR_CENTAUR:
1681 winchip_mcheck_init(c);
1691 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1693 switch (c->x86_vendor) {
1694 case X86_VENDOR_INTEL:
1695 mce_intel_feature_init(c);
1696 mce_adjust_timer = cmci_intel_adjust_timer;
1699 case X86_VENDOR_AMD: {
1700 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1701 mce_flags.succor = !!cpu_has(c, X86_FEATURE_SUCCOR);
1702 mce_flags.smca = !!cpu_has(c, X86_FEATURE_SMCA);
1705 * Install proper ops for Scalable MCA enabled processors
1707 if (mce_flags.smca) {
1708 msr_ops.ctl = smca_ctl_reg;
1709 msr_ops.status = smca_status_reg;
1710 msr_ops.addr = smca_addr_reg;
1711 msr_ops.misc = smca_misc_reg;
1713 mce_amd_feature_init(c);
1723 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1725 switch (c->x86_vendor) {
1726 case X86_VENDOR_INTEL:
1727 mce_intel_feature_clear(c);
1734 static void mce_start_timer(struct timer_list *t)
1736 unsigned long iv = check_interval * HZ;
1738 if (mca_cfg.ignore_ce || !iv)
1741 this_cpu_write(mce_next_interval, iv);
1742 __start_timer(t, iv);
1745 static void __mcheck_cpu_setup_timer(void)
1747 struct timer_list *t = this_cpu_ptr(&mce_timer);
1748 unsigned int cpu = smp_processor_id();
1750 setup_pinned_timer(t, mce_timer_fn, cpu);
1753 static void __mcheck_cpu_init_timer(void)
1755 struct timer_list *t = this_cpu_ptr(&mce_timer);
1756 unsigned int cpu = smp_processor_id();
1758 setup_pinned_timer(t, mce_timer_fn, cpu);
1762 /* Handle unconfigured int18 (should never happen) */
1763 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1765 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1766 smp_processor_id());
1769 /* Call the installed machine check handler for this CPU setup. */
1770 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1771 unexpected_machine_check;
1774 * Called for each booted CPU to set up machine checks.
1775 * Must be called with preempt off:
1777 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1779 if (mca_cfg.disabled)
1782 if (__mcheck_cpu_ancient_init(c))
1785 if (!mce_available(c))
1788 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1789 mca_cfg.disabled = true;
1793 if (mce_gen_pool_init()) {
1794 mca_cfg.disabled = true;
1795 pr_emerg("Couldn't allocate MCE records pool!\n");
1799 machine_check_vector = do_machine_check;
1801 __mcheck_cpu_init_generic();
1802 __mcheck_cpu_init_vendor(c);
1803 __mcheck_cpu_init_clear_banks();
1804 __mcheck_cpu_setup_timer();
1808 * Called for each booted CPU to clear some machine checks opt-ins
1810 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1812 if (mca_cfg.disabled)
1815 if (!mce_available(c))
1819 * Possibly to clear general settings generic to x86
1820 * __mcheck_cpu_clear_generic(c);
1822 __mcheck_cpu_clear_vendor(c);
1827 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1830 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1831 static int mce_chrdev_open_count; /* #times opened */
1832 static int mce_chrdev_open_exclu; /* already open exclusive? */
1834 static int mce_chrdev_open(struct inode *inode, struct file *file)
1836 spin_lock(&mce_chrdev_state_lock);
1838 if (mce_chrdev_open_exclu ||
1839 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1840 spin_unlock(&mce_chrdev_state_lock);
1845 if (file->f_flags & O_EXCL)
1846 mce_chrdev_open_exclu = 1;
1847 mce_chrdev_open_count++;
1849 spin_unlock(&mce_chrdev_state_lock);
1851 return nonseekable_open(inode, file);
1854 static int mce_chrdev_release(struct inode *inode, struct file *file)
1856 spin_lock(&mce_chrdev_state_lock);
1858 mce_chrdev_open_count--;
1859 mce_chrdev_open_exclu = 0;
1861 spin_unlock(&mce_chrdev_state_lock);
1866 static void collect_tscs(void *data)
1868 unsigned long *cpu_tsc = (unsigned long *)data;
1870 cpu_tsc[smp_processor_id()] = rdtsc();
1873 static int mce_apei_read_done;
1875 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1876 static int __mce_read_apei(char __user **ubuf, size_t usize)
1882 if (usize < sizeof(struct mce))
1885 rc = apei_read_mce(&m, &record_id);
1886 /* Error or no more MCE record */
1888 mce_apei_read_done = 1;
1890 * When ERST is disabled, mce_chrdev_read() should return
1891 * "no record" instead of "no device."
1898 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1901 * In fact, we should have cleared the record after that has
1902 * been flushed to the disk or sent to network in
1903 * /sbin/mcelog, but we have no interface to support that now,
1904 * so just clear it to avoid duplication.
1906 rc = apei_clear_mce(record_id);
1908 mce_apei_read_done = 1;
1911 *ubuf += sizeof(struct mce);
1916 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1917 size_t usize, loff_t *off)
1919 char __user *buf = ubuf;
1920 unsigned long *cpu_tsc;
1921 unsigned prev, next;
1924 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1928 mutex_lock(&mce_chrdev_read_mutex);
1930 if (!mce_apei_read_done) {
1931 err = __mce_read_apei(&buf, usize);
1932 if (err || buf != ubuf)
1936 next = mce_log_get_idx_check(mcelog.next);
1938 /* Only supports full reads right now */
1940 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1946 for (i = prev; i < next; i++) {
1947 unsigned long start = jiffies;
1948 struct mce *m = &mcelog.entry[i];
1950 while (!m->finished) {
1951 if (time_after_eq(jiffies, start + 2)) {
1952 memset(m, 0, sizeof(*m));
1958 err |= copy_to_user(buf, m, sizeof(*m));
1964 memset(mcelog.entry + prev, 0,
1965 (next - prev) * sizeof(struct mce));
1967 next = cmpxchg(&mcelog.next, prev, 0);
1968 } while (next != prev);
1970 synchronize_sched();
1973 * Collect entries that were still getting written before the
1976 on_each_cpu(collect_tscs, cpu_tsc, 1);
1978 for (i = next; i < MCE_LOG_LEN; i++) {
1979 struct mce *m = &mcelog.entry[i];
1981 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1982 err |= copy_to_user(buf, m, sizeof(*m));
1985 memset(m, 0, sizeof(*m));
1993 mutex_unlock(&mce_chrdev_read_mutex);
1996 return err ? err : buf - ubuf;
1999 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
2001 poll_wait(file, &mce_chrdev_wait, wait);
2002 if (READ_ONCE(mcelog.next))
2003 return POLLIN | POLLRDNORM;
2004 if (!mce_apei_read_done && apei_check_mce())
2005 return POLLIN | POLLRDNORM;
2009 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
2012 int __user *p = (int __user *)arg;
2014 if (!capable(CAP_SYS_ADMIN))
2018 case MCE_GET_RECORD_LEN:
2019 return put_user(sizeof(struct mce), p);
2020 case MCE_GET_LOG_LEN:
2021 return put_user(MCE_LOG_LEN, p);
2022 case MCE_GETCLEAR_FLAGS: {
2026 flags = mcelog.flags;
2027 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
2029 return put_user(flags, p);
2036 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
2037 size_t usize, loff_t *off);
2039 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
2040 const char __user *ubuf,
2041 size_t usize, loff_t *off))
2045 EXPORT_SYMBOL_GPL(register_mce_write_callback);
2047 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
2048 size_t usize, loff_t *off)
2051 return mce_write(filp, ubuf, usize, off);
2056 static const struct file_operations mce_chrdev_ops = {
2057 .open = mce_chrdev_open,
2058 .release = mce_chrdev_release,
2059 .read = mce_chrdev_read,
2060 .write = mce_chrdev_write,
2061 .poll = mce_chrdev_poll,
2062 .unlocked_ioctl = mce_chrdev_ioctl,
2063 .llseek = no_llseek,
2066 static struct miscdevice mce_chrdev_device = {
2072 static void __mce_disable_bank(void *arg)
2074 int bank = *((int *)arg);
2075 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2076 cmci_disable_bank(bank);
2079 void mce_disable_bank(int bank)
2081 if (bank >= mca_cfg.banks) {
2083 "Ignoring request to disable invalid MCA bank %d.\n",
2087 set_bit(bank, mce_banks_ce_disabled);
2088 on_each_cpu(__mce_disable_bank, &bank, 1);
2092 * mce=off Disables machine check
2093 * mce=no_cmci Disables CMCI
2094 * mce=no_lmce Disables LMCE
2095 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2096 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2097 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2098 * monarchtimeout is how long to wait for other CPUs on machine
2099 * check, or 0 to not wait
2100 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2101 * mce=nobootlog Don't log MCEs from before booting.
2102 * mce=bios_cmci_threshold Don't program the CMCI threshold
2103 * mce=recovery force enable memcpy_mcsafe()
2105 static int __init mcheck_enable(char *str)
2107 struct mca_config *cfg = &mca_cfg;
2115 if (!strcmp(str, "off"))
2116 cfg->disabled = true;
2117 else if (!strcmp(str, "no_cmci"))
2118 cfg->cmci_disabled = true;
2119 else if (!strcmp(str, "no_lmce"))
2120 cfg->lmce_disabled = true;
2121 else if (!strcmp(str, "dont_log_ce"))
2122 cfg->dont_log_ce = true;
2123 else if (!strcmp(str, "ignore_ce"))
2124 cfg->ignore_ce = true;
2125 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2126 cfg->bootlog = (str[0] == 'b');
2127 else if (!strcmp(str, "bios_cmci_threshold"))
2128 cfg->bios_cmci_threshold = true;
2129 else if (!strcmp(str, "recovery"))
2130 cfg->recovery = true;
2131 else if (isdigit(str[0])) {
2132 if (get_option(&str, &cfg->tolerant) == 2)
2133 get_option(&str, &(cfg->monarch_timeout));
2135 pr_info("mce argument %s ignored. Please use /sys\n", str);
2140 __setup("mce", mcheck_enable);
2142 int __init mcheck_init(void)
2144 mcheck_intel_therm_init();
2145 mce_register_decode_chain(&mce_srao_nb);
2146 mce_register_decode_chain(&mce_default_nb);
2147 mcheck_vendor_init_severity();
2149 INIT_WORK(&mce_work, mce_gen_pool_process);
2150 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2156 * mce_syscore: PM support
2160 * Disable machine checks on suspend and shutdown. We can't really handle
2163 static void mce_disable_error_reporting(void)
2167 for (i = 0; i < mca_cfg.banks; i++) {
2168 struct mce_bank *b = &mce_banks[i];
2171 wrmsrl(msr_ops.ctl(i), 0);
2176 static void vendor_disable_error_reporting(void)
2179 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2180 * Disabling them for just a single offlined CPU is bad, since it will
2181 * inhibit reporting for all shared resources on the socket like the
2182 * last level cache (LLC), the integrated memory controller (iMC), etc.
2184 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2187 mce_disable_error_reporting();
2190 static int mce_syscore_suspend(void)
2192 vendor_disable_error_reporting();
2196 static void mce_syscore_shutdown(void)
2198 vendor_disable_error_reporting();
2202 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2203 * Only one CPU is active at this time, the others get re-added later using
2206 static void mce_syscore_resume(void)
2208 __mcheck_cpu_init_generic();
2209 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2210 __mcheck_cpu_init_clear_banks();
2213 static struct syscore_ops mce_syscore_ops = {
2214 .suspend = mce_syscore_suspend,
2215 .shutdown = mce_syscore_shutdown,
2216 .resume = mce_syscore_resume,
2220 * mce_device: Sysfs support
2223 static void mce_cpu_restart(void *data)
2225 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2227 __mcheck_cpu_init_generic();
2228 __mcheck_cpu_init_clear_banks();
2229 __mcheck_cpu_init_timer();
2232 /* Reinit MCEs after user configuration changes */
2233 static void mce_restart(void)
2235 mce_timer_delete_all();
2236 on_each_cpu(mce_cpu_restart, NULL, 1);
2239 /* Toggle features for corrected errors */
2240 static void mce_disable_cmci(void *data)
2242 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2247 static void mce_enable_ce(void *all)
2249 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2254 __mcheck_cpu_init_timer();
2257 static struct bus_type mce_subsys = {
2258 .name = "machinecheck",
2259 .dev_name = "machinecheck",
2262 DEFINE_PER_CPU(struct device *, mce_device);
2264 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2266 return container_of(attr, struct mce_bank, attr);
2269 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2272 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2275 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2276 const char *buf, size_t size)
2280 if (kstrtou64(buf, 0, &new) < 0)
2283 attr_to_bank(attr)->ctl = new;
2290 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2292 strcpy(buf, mce_helper);
2294 return strlen(mce_helper) + 1;
2297 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2298 const char *buf, size_t siz)
2302 strncpy(mce_helper, buf, sizeof(mce_helper));
2303 mce_helper[sizeof(mce_helper)-1] = 0;
2304 p = strchr(mce_helper, '\n');
2309 return strlen(mce_helper) + !!p;
2312 static ssize_t set_ignore_ce(struct device *s,
2313 struct device_attribute *attr,
2314 const char *buf, size_t size)
2318 if (kstrtou64(buf, 0, &new) < 0)
2321 if (mca_cfg.ignore_ce ^ !!new) {
2323 /* disable ce features */
2324 mce_timer_delete_all();
2325 on_each_cpu(mce_disable_cmci, NULL, 1);
2326 mca_cfg.ignore_ce = true;
2328 /* enable ce features */
2329 mca_cfg.ignore_ce = false;
2330 on_each_cpu(mce_enable_ce, (void *)1, 1);
2336 static ssize_t set_cmci_disabled(struct device *s,
2337 struct device_attribute *attr,
2338 const char *buf, size_t size)
2342 if (kstrtou64(buf, 0, &new) < 0)
2345 if (mca_cfg.cmci_disabled ^ !!new) {
2348 on_each_cpu(mce_disable_cmci, NULL, 1);
2349 mca_cfg.cmci_disabled = true;
2352 mca_cfg.cmci_disabled = false;
2353 on_each_cpu(mce_enable_ce, NULL, 1);
2359 static ssize_t store_int_with_restart(struct device *s,
2360 struct device_attribute *attr,
2361 const char *buf, size_t size)
2363 ssize_t ret = device_store_int(s, attr, buf, size);
2368 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2369 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2370 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2371 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2373 static struct dev_ext_attribute dev_attr_check_interval = {
2374 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2378 static struct dev_ext_attribute dev_attr_ignore_ce = {
2379 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2383 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2384 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2385 &mca_cfg.cmci_disabled
2388 static struct device_attribute *mce_device_attrs[] = {
2389 &dev_attr_tolerant.attr,
2390 &dev_attr_check_interval.attr,
2392 &dev_attr_monarch_timeout.attr,
2393 &dev_attr_dont_log_ce.attr,
2394 &dev_attr_ignore_ce.attr,
2395 &dev_attr_cmci_disabled.attr,
2399 static cpumask_var_t mce_device_initialized;
2401 static void mce_device_release(struct device *dev)
2406 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2407 static int mce_device_create(unsigned int cpu)
2413 if (!mce_available(&boot_cpu_data))
2416 dev = per_cpu(mce_device, cpu);
2420 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2424 dev->bus = &mce_subsys;
2425 dev->release = &mce_device_release;
2427 err = device_register(dev);
2433 for (i = 0; mce_device_attrs[i]; i++) {
2434 err = device_create_file(dev, mce_device_attrs[i]);
2438 for (j = 0; j < mca_cfg.banks; j++) {
2439 err = device_create_file(dev, &mce_banks[j].attr);
2443 cpumask_set_cpu(cpu, mce_device_initialized);
2444 per_cpu(mce_device, cpu) = dev;
2449 device_remove_file(dev, &mce_banks[j].attr);
2452 device_remove_file(dev, mce_device_attrs[i]);
2454 device_unregister(dev);
2459 static void mce_device_remove(unsigned int cpu)
2461 struct device *dev = per_cpu(mce_device, cpu);
2464 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2467 for (i = 0; mce_device_attrs[i]; i++)
2468 device_remove_file(dev, mce_device_attrs[i]);
2470 for (i = 0; i < mca_cfg.banks; i++)
2471 device_remove_file(dev, &mce_banks[i].attr);
2473 device_unregister(dev);
2474 cpumask_clear_cpu(cpu, mce_device_initialized);
2475 per_cpu(mce_device, cpu) = NULL;
2478 /* Make sure there are no machine checks on offlined CPUs. */
2479 static void mce_disable_cpu(void)
2481 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2484 if (!cpuhp_tasks_frozen)
2487 vendor_disable_error_reporting();
2490 static void mce_reenable_cpu(void)
2494 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2497 if (!cpuhp_tasks_frozen)
2499 for (i = 0; i < mca_cfg.banks; i++) {
2500 struct mce_bank *b = &mce_banks[i];
2503 wrmsrl(msr_ops.ctl(i), b->ctl);
2507 static int mce_cpu_dead(unsigned int cpu)
2509 mce_intel_hcpu_update(cpu);
2511 /* intentionally ignoring frozen here */
2512 if (!cpuhp_tasks_frozen)
2517 static int mce_cpu_online(unsigned int cpu)
2519 struct timer_list *t = this_cpu_ptr(&mce_timer);
2522 mce_device_create(cpu);
2524 ret = mce_threshold_create_device(cpu);
2526 mce_device_remove(cpu);
2534 static int mce_cpu_pre_down(unsigned int cpu)
2536 struct timer_list *t = this_cpu_ptr(&mce_timer);
2540 mce_threshold_remove_device(cpu);
2541 mce_device_remove(cpu);
2545 static __init void mce_init_banks(void)
2549 for (i = 0; i < mca_cfg.banks; i++) {
2550 struct mce_bank *b = &mce_banks[i];
2551 struct device_attribute *a = &b->attr;
2553 sysfs_attr_init(&a->attr);
2554 a->attr.name = b->attrname;
2555 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2557 a->attr.mode = 0644;
2558 a->show = show_bank;
2559 a->store = set_bank;
2563 static __init int mcheck_init_device(void)
2565 enum cpuhp_state hp_online;
2568 if (!mce_available(&boot_cpu_data)) {
2573 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2580 err = subsys_system_register(&mce_subsys, NULL);
2584 err = cpuhp_setup_state(CPUHP_X86_MCE_DEAD, "x86/mce:dead", NULL,
2589 err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/mce:online",
2590 mce_cpu_online, mce_cpu_pre_down);
2592 goto err_out_online;
2595 register_syscore_ops(&mce_syscore_ops);
2597 /* register character device /dev/mcelog */
2598 err = misc_register(&mce_chrdev_device);
2605 unregister_syscore_ops(&mce_syscore_ops);
2606 cpuhp_remove_state(hp_online);
2609 cpuhp_remove_state(CPUHP_X86_MCE_DEAD);
2612 free_cpumask_var(mce_device_initialized);
2615 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2619 device_initcall_sync(mcheck_init_device);
2622 * Old style boot options parsing. Only for compatibility.
2624 static int __init mcheck_disable(char *str)
2626 mca_cfg.disabled = true;
2629 __setup("nomce", mcheck_disable);
2631 #ifdef CONFIG_DEBUG_FS
2632 struct dentry *mce_get_debugfs_dir(void)
2634 static struct dentry *dmce;
2637 dmce = debugfs_create_dir("mce", NULL);
2642 static void mce_reset(void)
2645 atomic_set(&mce_fake_panicked, 0);
2646 atomic_set(&mce_executing, 0);
2647 atomic_set(&mce_callin, 0);
2648 atomic_set(&global_nwo, 0);
2651 static int fake_panic_get(void *data, u64 *val)
2657 static int fake_panic_set(void *data, u64 val)
2664 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2665 fake_panic_set, "%llu\n");
2667 static int __init mcheck_debugfs_init(void)
2669 struct dentry *dmce, *ffake_panic;
2671 dmce = mce_get_debugfs_dir();
2674 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2682 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2685 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2686 EXPORT_SYMBOL_GPL(mcsafe_key);
2688 static int __init mcheck_late_init(void)
2690 if (mca_cfg.recovery)
2691 static_branch_inc(&mcsafe_key);
2693 mcheck_debugfs_init();
2696 * Flush out everything that has been logged during early boot, now that
2697 * everything has been initialized (workqueues, decoders, ...).
2699 mce_schedule_work();
2703 late_initcall(mcheck_late_init);