1 // SPDX-License-Identifier: GPL-2.0-only
3 * Machine check handler.
5 * K8 parts Copyright 2002,2003 Andi Kleen, SuSE Labs.
6 * Rest from unknown author(s).
7 * 2004 Andi Kleen. Rewrote most of it.
8 * Copyright 2008 Intel Corporation
12 #include <linux/thread_info.h>
13 #include <linux/capability.h>
14 #include <linux/miscdevice.h>
15 #include <linux/ratelimit.h>
16 #include <linux/rcupdate.h>
17 #include <linux/kobject.h>
18 #include <linux/uaccess.h>
19 #include <linux/kdebug.h>
20 #include <linux/kernel.h>
21 #include <linux/percpu.h>
22 #include <linux/string.h>
23 #include <linux/device.h>
24 #include <linux/syscore_ops.h>
25 #include <linux/delay.h>
26 #include <linux/ctype.h>
27 #include <linux/sched.h>
28 #include <linux/sysfs.h>
29 #include <linux/types.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/kmod.h>
33 #include <linux/poll.h>
34 #include <linux/nmi.h>
35 #include <linux/cpu.h>
36 #include <linux/ras.h>
37 #include <linux/smp.h>
40 #include <linux/debugfs.h>
41 #include <linux/irq_work.h>
42 #include <linux/export.h>
43 #include <linux/jump_label.h>
44 #include <linux/set_memory.h>
45 #include <linux/sync_core.h>
46 #include <linux/task_work.h>
47 #include <linux/hardirq.h>
49 #include <asm/intel-family.h>
50 #include <asm/processor.h>
51 #include <asm/traps.h>
52 #include <asm/tlbflush.h>
55 #include <asm/reboot.h>
59 /* sysfs synchronization */
60 static DEFINE_MUTEX(mce_sysfs_mutex);
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/mce.h>
65 #define SPINUNIT 100 /* 100ns */
67 DEFINE_PER_CPU(unsigned, mce_exception_count);
69 DEFINE_PER_CPU_READ_MOSTLY(unsigned int, mce_num_banks);
72 u64 ctl; /* subevents to enable */
73 bool init; /* initialise bank? */
75 static DEFINE_PER_CPU_READ_MOSTLY(struct mce_bank[MAX_NR_BANKS], mce_banks_array);
78 /* One object for each MCE bank, shared by all CPUs */
80 struct device_attribute attr; /* device attribute */
81 char attrname[ATTR_LEN]; /* attribute name */
82 u8 bank; /* bank number */
84 static struct mce_bank_dev mce_bank_devs[MAX_NR_BANKS];
86 struct mce_vendor_flags mce_flags __read_mostly;
88 struct mca_config mca_cfg __read_mostly = {
92 * 0: always panic on uncorrected errors, log corrected errors
93 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
94 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
95 * 3: never panic or SIGBUS, log all errors (for testing only)
101 static DEFINE_PER_CPU(struct mce, mces_seen);
102 static unsigned long mce_need_notify;
103 static int cpu_missing;
106 * MCA banks polled by the period polling timer for corrected events.
107 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
109 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
110 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
114 * MCA banks controlled through firmware first for corrected errors.
115 * This is a global list of banks for which we won't enable CMCI and we
116 * won't poll. Firmware controls these banks and is responsible for
117 * reporting corrected errors through GHES. Uncorrected/recoverable
118 * errors are still notified through a machine check.
120 mce_banks_t mce_banks_ce_disabled;
122 static struct work_struct mce_work;
123 static struct irq_work mce_irq_work;
125 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
128 * CPU/chipset specific EDAC code can register a notifier call here to print
129 * MCE errors in a human-readable form.
131 BLOCKING_NOTIFIER_HEAD(x86_mce_decoder_chain);
133 /* Do initial initialization of a struct mce */
134 noinstr void mce_setup(struct mce *m)
136 memset(m, 0, sizeof(struct mce));
137 m->cpu = m->extcpu = smp_processor_id();
138 /* need the internal __ version to avoid deadlocks */
139 m->time = __ktime_get_real_seconds();
140 m->cpuvendor = boot_cpu_data.x86_vendor;
141 m->cpuid = cpuid_eax(1);
142 m->socketid = cpu_data(m->extcpu).phys_proc_id;
143 m->apicid = cpu_data(m->extcpu).initial_apicid;
144 m->mcgcap = __rdmsr(MSR_IA32_MCG_CAP);
146 if (this_cpu_has(X86_FEATURE_INTEL_PPIN))
147 m->ppin = __rdmsr(MSR_PPIN);
148 else if (this_cpu_has(X86_FEATURE_AMD_PPIN))
149 m->ppin = __rdmsr(MSR_AMD_PPIN);
151 m->microcode = boot_cpu_data.microcode;
154 DEFINE_PER_CPU(struct mce, injectm);
155 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
157 void mce_log(struct mce *m)
159 if (!mce_gen_pool_add(m))
160 irq_work_queue(&mce_irq_work);
162 EXPORT_SYMBOL_GPL(mce_log);
164 void mce_register_decode_chain(struct notifier_block *nb)
166 if (WARN_ON(nb->priority > MCE_PRIO_MCELOG && nb->priority < MCE_PRIO_EDAC))
169 blocking_notifier_chain_register(&x86_mce_decoder_chain, nb);
171 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
173 void mce_unregister_decode_chain(struct notifier_block *nb)
175 blocking_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
177 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
179 static inline u32 ctl_reg(int bank)
181 return MSR_IA32_MCx_CTL(bank);
184 static inline u32 status_reg(int bank)
186 return MSR_IA32_MCx_STATUS(bank);
189 static inline u32 addr_reg(int bank)
191 return MSR_IA32_MCx_ADDR(bank);
194 static inline u32 misc_reg(int bank)
196 return MSR_IA32_MCx_MISC(bank);
199 static inline u32 smca_ctl_reg(int bank)
201 return MSR_AMD64_SMCA_MCx_CTL(bank);
204 static inline u32 smca_status_reg(int bank)
206 return MSR_AMD64_SMCA_MCx_STATUS(bank);
209 static inline u32 smca_addr_reg(int bank)
211 return MSR_AMD64_SMCA_MCx_ADDR(bank);
214 static inline u32 smca_misc_reg(int bank)
216 return MSR_AMD64_SMCA_MCx_MISC(bank);
219 struct mca_msr_regs msr_ops = {
221 .status = status_reg,
226 static void __print_mce(struct mce *m)
228 pr_emerg(HW_ERR "CPU %d: Machine Check%s: %Lx Bank %d: %016Lx\n",
230 (m->mcgstatus & MCG_STATUS_MCIP ? " Exception" : ""),
231 m->mcgstatus, m->bank, m->status);
234 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
235 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
238 if (m->cs == __KERNEL_CS)
239 pr_cont("{%pS}", (void *)(unsigned long)m->ip);
243 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
245 pr_cont("ADDR %llx ", m->addr);
247 pr_cont("MISC %llx ", m->misc);
249 pr_cont("PPIN %llx ", m->ppin);
251 if (mce_flags.smca) {
253 pr_cont("SYND %llx ", m->synd);
255 pr_cont("IPID %llx ", m->ipid);
261 * Note this output is parsed by external tools and old fields
262 * should not be changed.
264 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
265 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
269 static void print_mce(struct mce *m)
273 if (m->cpuvendor != X86_VENDOR_AMD && m->cpuvendor != X86_VENDOR_HYGON)
274 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
277 #define PANIC_TIMEOUT 5 /* 5 seconds */
279 static atomic_t mce_panicked;
281 static int fake_panic;
282 static atomic_t mce_fake_panicked;
284 /* Panic in progress. Enable interrupts and wait for final IPI */
285 static void wait_for_panic(void)
287 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
291 while (timeout-- > 0)
293 if (panic_timeout == 0)
294 panic_timeout = mca_cfg.panic_timeout;
295 panic("Panicing machine check CPU died");
298 static void mce_panic(const char *msg, struct mce *final, char *exp)
301 struct llist_node *pending;
302 struct mce_evt_llist *l;
306 * Make sure only one CPU runs in machine check panic
308 if (atomic_inc_return(&mce_panicked) > 1)
315 /* Don't log too much for fake panic */
316 if (atomic_inc_return(&mce_fake_panicked) > 1)
319 pending = mce_gen_pool_prepare_records();
320 /* First print corrected ones that are still unlogged */
321 llist_for_each_entry(l, pending, llnode) {
322 struct mce *m = &l->mce;
323 if (!(m->status & MCI_STATUS_UC)) {
326 apei_err = apei_write_mce(m);
329 /* Now print uncorrected but with the final one last */
330 llist_for_each_entry(l, pending, llnode) {
331 struct mce *m = &l->mce;
332 if (!(m->status & MCI_STATUS_UC))
334 if (!final || mce_cmp(m, final)) {
337 apei_err = apei_write_mce(m);
343 apei_err = apei_write_mce(final);
346 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
348 pr_emerg(HW_ERR "Machine check: %s\n", exp);
350 if (panic_timeout == 0)
351 panic_timeout = mca_cfg.panic_timeout;
354 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
357 /* Support code for software error injection */
359 static int msr_to_offset(u32 msr)
361 unsigned bank = __this_cpu_read(injectm.bank);
363 if (msr == mca_cfg.rip_msr)
364 return offsetof(struct mce, ip);
365 if (msr == msr_ops.status(bank))
366 return offsetof(struct mce, status);
367 if (msr == msr_ops.addr(bank))
368 return offsetof(struct mce, addr);
369 if (msr == msr_ops.misc(bank))
370 return offsetof(struct mce, misc);
371 if (msr == MSR_IA32_MCG_STATUS)
372 return offsetof(struct mce, mcgstatus);
376 __visible bool ex_handler_rdmsr_fault(const struct exception_table_entry *fixup,
377 struct pt_regs *regs, int trapnr,
378 unsigned long error_code,
379 unsigned long fault_addr)
381 pr_emerg("MSR access error: RDMSR from 0x%x at rIP: 0x%lx (%pS)\n",
382 (unsigned int)regs->cx, regs->ip, (void *)regs->ip);
384 show_stack_regs(regs);
386 panic("MCA architectural violation!\n");
394 /* MSR access wrappers used for error injection */
395 static u64 mce_rdmsrl(u32 msr)
397 DECLARE_ARGS(val, low, high);
399 if (__this_cpu_read(injectm.finished)) {
400 int offset = msr_to_offset(msr);
404 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
408 * RDMSR on MCA MSRs should not fault. If they do, this is very much an
409 * architectural violation and needs to be reported to hw vendor. Panic
410 * the box to not allow any further progress.
412 asm volatile("1: rdmsr\n"
414 _ASM_EXTABLE_HANDLE(1b, 2b, ex_handler_rdmsr_fault)
415 : EAX_EDX_RET(val, low, high) : "c" (msr));
418 return EAX_EDX_VAL(val, low, high);
421 __visible bool ex_handler_wrmsr_fault(const struct exception_table_entry *fixup,
422 struct pt_regs *regs, int trapnr,
423 unsigned long error_code,
424 unsigned long fault_addr)
426 pr_emerg("MSR access error: WRMSR to 0x%x (tried to write 0x%08x%08x) at rIP: 0x%lx (%pS)\n",
427 (unsigned int)regs->cx, (unsigned int)regs->dx, (unsigned int)regs->ax,
428 regs->ip, (void *)regs->ip);
430 show_stack_regs(regs);
432 panic("MCA architectural violation!\n");
440 static void mce_wrmsrl(u32 msr, u64 v)
444 if (__this_cpu_read(injectm.finished)) {
445 int offset = msr_to_offset(msr);
448 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
453 high = (u32)(v >> 32);
455 /* See comment in mce_rdmsrl() */
456 asm volatile("1: wrmsr\n"
458 _ASM_EXTABLE_HANDLE(1b, 2b, ex_handler_wrmsr_fault)
459 : : "c" (msr), "a"(low), "d" (high) : "memory");
463 * Collect all global (w.r.t. this processor) status about this machine
464 * check into our "mce" struct so that we can use it later to assess
465 * the severity of the problem as we read per-bank specific details.
467 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
471 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
474 * Get the address of the instruction at the time of
475 * the machine check error.
477 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
482 * When in VM86 mode make the cs look like ring 3
483 * always. This is a lie, but it's better than passing
484 * the additional vm86 bit around everywhere.
486 if (v8086_mode(regs))
489 /* Use accurate RIP reporting if available. */
491 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
495 int mce_available(struct cpuinfo_x86 *c)
497 if (mca_cfg.disabled)
499 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
502 static void mce_schedule_work(void)
504 if (!mce_gen_pool_empty())
505 schedule_work(&mce_work);
508 static void mce_irq_work_cb(struct irq_work *entry)
514 * Check if the address reported by the CPU is in a format we can parse.
515 * It would be possible to add code for most other cases, but all would
516 * be somewhat complicated (e.g. segment offset would require an instruction
517 * parser). So only support physical addresses up to page granuality for now.
519 int mce_usable_address(struct mce *m)
521 if (!(m->status & MCI_STATUS_ADDRV))
524 /* Checks after this one are Intel/Zhaoxin-specific: */
525 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL &&
526 boot_cpu_data.x86_vendor != X86_VENDOR_ZHAOXIN)
529 if (!(m->status & MCI_STATUS_MISCV))
532 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
535 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
540 EXPORT_SYMBOL_GPL(mce_usable_address);
542 bool mce_is_memory_error(struct mce *m)
544 switch (m->cpuvendor) {
546 case X86_VENDOR_HYGON:
547 return amd_mce_is_memory_error(m);
549 case X86_VENDOR_INTEL:
550 case X86_VENDOR_ZHAOXIN:
552 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
554 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
555 * indicating a memory error. Bit 8 is used for indicating a
556 * cache hierarchy error. The combination of bit 2 and bit 3
557 * is used for indicating a `generic' cache hierarchy error
558 * But we can't just blindly check the above bits, because if
559 * bit 11 is set, then it is a bus/interconnect error - and
560 * either way the above bits just gives more detail on what
561 * bus/interconnect error happened. Note that bit 12 can be
562 * ignored, as it's the "filter" bit.
564 return (m->status & 0xef80) == BIT(7) ||
565 (m->status & 0xef00) == BIT(8) ||
566 (m->status & 0xeffc) == 0xc;
572 EXPORT_SYMBOL_GPL(mce_is_memory_error);
574 static bool whole_page(struct mce *m)
576 if (!mca_cfg.ser || !(m->status & MCI_STATUS_MISCV))
579 return MCI_MISC_ADDR_LSB(m->misc) >= PAGE_SHIFT;
582 bool mce_is_correctable(struct mce *m)
584 if (m->cpuvendor == X86_VENDOR_AMD && m->status & MCI_STATUS_DEFERRED)
587 if (m->cpuvendor == X86_VENDOR_HYGON && m->status & MCI_STATUS_DEFERRED)
590 if (m->status & MCI_STATUS_UC)
595 EXPORT_SYMBOL_GPL(mce_is_correctable);
597 static int mce_early_notifier(struct notifier_block *nb, unsigned long val,
600 struct mce *m = (struct mce *)data;
605 /* Emit the trace record: */
608 set_bit(0, &mce_need_notify);
615 static struct notifier_block early_nb = {
616 .notifier_call = mce_early_notifier,
617 .priority = MCE_PRIO_EARLY,
620 static int uc_decode_notifier(struct notifier_block *nb, unsigned long val,
623 struct mce *mce = (struct mce *)data;
626 if (!mce || !mce_usable_address(mce))
629 if (mce->severity != MCE_AO_SEVERITY &&
630 mce->severity != MCE_DEFERRED_SEVERITY)
633 pfn = mce->addr >> PAGE_SHIFT;
634 if (!memory_failure(pfn, 0)) {
635 set_mce_nospec(pfn, whole_page(mce));
636 mce->kflags |= MCE_HANDLED_UC;
642 static struct notifier_block mce_uc_nb = {
643 .notifier_call = uc_decode_notifier,
644 .priority = MCE_PRIO_UC,
647 static int mce_default_notifier(struct notifier_block *nb, unsigned long val,
650 struct mce *m = (struct mce *)data;
655 if (mca_cfg.print_all || !m->kflags)
661 static struct notifier_block mce_default_nb = {
662 .notifier_call = mce_default_notifier,
663 /* lowest prio, we want it to run last. */
664 .priority = MCE_PRIO_LOWEST,
668 * Read ADDR and MISC registers.
670 static void mce_read_aux(struct mce *m, int i)
672 if (m->status & MCI_STATUS_MISCV)
673 m->misc = mce_rdmsrl(msr_ops.misc(i));
675 if (m->status & MCI_STATUS_ADDRV) {
676 m->addr = mce_rdmsrl(msr_ops.addr(i));
679 * Mask the reported address by the reported granularity.
681 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
682 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
688 * Extract [55:<lsb>] where lsb is the least significant
689 * *valid* bit of the address bits.
691 if (mce_flags.smca) {
692 u8 lsb = (m->addr >> 56) & 0x3f;
694 m->addr &= GENMASK_ULL(55, lsb);
698 if (mce_flags.smca) {
699 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
701 if (m->status & MCI_STATUS_SYNDV)
702 m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
706 DEFINE_PER_CPU(unsigned, mce_poll_count);
709 * Poll for corrected events or events that happened before reset.
710 * Those are just logged through /dev/mcelog.
712 * This is executed in standard interrupt context.
714 * Note: spec recommends to panic for fatal unsignalled
715 * errors here. However this would be quite problematic --
716 * we would need to reimplement the Monarch handling and
717 * it would mess up the exclusion between exception handler
718 * and poll handler -- * so we skip this for now.
719 * These cases should not happen anyways, or only when the CPU
720 * is already totally * confused. In this case it's likely it will
721 * not fully execute the machine check handler either.
723 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
725 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
726 bool error_seen = false;
730 this_cpu_inc(mce_poll_count);
732 mce_gather_info(&m, NULL);
734 if (flags & MCP_TIMESTAMP)
737 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
738 if (!mce_banks[i].ctl || !test_bit(i, *b))
746 m.status = mce_rdmsrl(msr_ops.status(i));
748 /* If this entry is not valid, ignore it */
749 if (!(m.status & MCI_STATUS_VAL))
753 * If we are logging everything (at CPU online) or this
754 * is a corrected error, then we must log it.
756 if ((flags & MCP_UC) || !(m.status & MCI_STATUS_UC))
760 * Newer Intel systems that support software error
761 * recovery need to make additional checks. Other
762 * CPUs should skip over uncorrected errors, but log
766 if (m.status & MCI_STATUS_UC)
771 /* Log "not enabled" (speculative) errors */
772 if (!(m.status & MCI_STATUS_EN))
776 * Log UCNA (SDM: 15.6.3 "UCR Error Classification")
777 * UC == 1 && PCC == 0 && S == 0
779 if (!(m.status & MCI_STATUS_PCC) && !(m.status & MCI_STATUS_S))
783 * Skip anything else. Presumption is that our read of this
784 * bank is racing with a machine check. Leave the log alone
785 * for do_machine_check() to deal with it.
792 if (flags & MCP_DONTLOG)
796 m.severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
798 * Don't get the IP here because it's unlikely to
799 * have anything to do with the actual error location.
802 if (mca_cfg.dont_log_ce && !mce_usable_address(&m))
809 * Clear state for this bank.
811 mce_wrmsrl(msr_ops.status(i), 0);
815 * Don't clear MCG_STATUS here because it's only defined for
823 EXPORT_SYMBOL_GPL(machine_check_poll);
826 * Do a quick check if any of the events requires a panic.
827 * This decides if we keep the events around or clear them.
829 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
830 struct pt_regs *regs)
835 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
836 m->status = mce_rdmsrl(msr_ops.status(i));
837 if (!(m->status & MCI_STATUS_VAL))
840 __set_bit(i, validp);
841 if (quirk_no_way_out)
842 quirk_no_way_out(i, m, regs);
845 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
855 * Variable to establish order between CPUs while scanning.
856 * Each CPU spins initially until executing is equal its number.
858 static atomic_t mce_executing;
861 * Defines order of CPUs on entry. First CPU becomes Monarch.
863 static atomic_t mce_callin;
866 * Check if a timeout waiting for other CPUs happened.
868 static int mce_timed_out(u64 *t, const char *msg)
871 * The others already did panic for some reason.
872 * Bail out like in a timeout.
873 * rmb() to tell the compiler that system_state
874 * might have been modified by someone else.
877 if (atomic_read(&mce_panicked))
879 if (!mca_cfg.monarch_timeout)
881 if ((s64)*t < SPINUNIT) {
882 if (mca_cfg.tolerant <= 1)
883 mce_panic(msg, NULL, NULL);
889 touch_nmi_watchdog();
894 * The Monarch's reign. The Monarch is the CPU who entered
895 * the machine check handler first. It waits for the others to
896 * raise the exception too and then grades them. When any
897 * error is fatal panic. Only then let the others continue.
899 * The other CPUs entering the MCE handler will be controlled by the
900 * Monarch. They are called Subjects.
902 * This way we prevent any potential data corruption in a unrecoverable case
903 * and also makes sure always all CPU's errors are examined.
905 * Also this detects the case of a machine check event coming from outer
906 * space (not detected by any CPUs) In this case some external agent wants
907 * us to shut down, so panic too.
909 * The other CPUs might still decide to panic if the handler happens
910 * in a unrecoverable place, but in this case the system is in a semi-stable
911 * state and won't corrupt anything by itself. It's ok to let the others
912 * continue for a bit first.
914 * All the spin loops have timeouts; when a timeout happens a CPU
915 * typically elects itself to be Monarch.
917 static void mce_reign(void)
920 struct mce *m = NULL;
921 int global_worst = 0;
926 * This CPU is the Monarch and the other CPUs have run
927 * through their handlers.
928 * Grade the severity of the errors of all the CPUs.
930 for_each_possible_cpu(cpu) {
931 int severity = mce_severity(&per_cpu(mces_seen, cpu),
934 if (severity > global_worst) {
936 global_worst = severity;
937 m = &per_cpu(mces_seen, cpu);
942 * Cannot recover? Panic here then.
943 * This dumps all the mces in the log buffer and stops the
946 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
947 mce_panic("Fatal machine check", m, msg);
950 * For UC somewhere we let the CPU who detects it handle it.
951 * Also must let continue the others, otherwise the handling
952 * CPU could deadlock on a lock.
956 * No machine check event found. Must be some external
957 * source or one CPU is hung. Panic.
959 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
960 mce_panic("Fatal machine check from unknown source", NULL, NULL);
963 * Now clear all the mces_seen so that they don't reappear on
966 for_each_possible_cpu(cpu)
967 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
970 static atomic_t global_nwo;
973 * Start of Monarch synchronization. This waits until all CPUs have
974 * entered the exception handler and then determines if any of them
975 * saw a fatal event that requires panic. Then it executes them
976 * in the entry order.
977 * TBD double check parallel CPU hotunplug
979 static int mce_start(int *no_way_out)
982 int cpus = num_online_cpus();
983 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
988 atomic_add(*no_way_out, &global_nwo);
990 * Rely on the implied barrier below, such that global_nwo
991 * is updated before mce_callin.
993 order = atomic_inc_return(&mce_callin);
998 while (atomic_read(&mce_callin) != cpus) {
999 if (mce_timed_out(&timeout,
1000 "Timeout: Not all CPUs entered broadcast exception handler")) {
1001 atomic_set(&global_nwo, 0);
1008 * mce_callin should be read before global_nwo
1014 * Monarch: Starts executing now, the others wait.
1016 atomic_set(&mce_executing, 1);
1019 * Subject: Now start the scanning loop one by one in
1020 * the original callin order.
1021 * This way when there are any shared banks it will be
1022 * only seen by one CPU before cleared, avoiding duplicates.
1024 while (atomic_read(&mce_executing) < order) {
1025 if (mce_timed_out(&timeout,
1026 "Timeout: Subject CPUs unable to finish machine check processing")) {
1027 atomic_set(&global_nwo, 0);
1035 * Cache the global no_way_out state.
1037 *no_way_out = atomic_read(&global_nwo);
1043 * Synchronize between CPUs after main scanning loop.
1044 * This invokes the bulk of the Monarch processing.
1046 static int mce_end(int order)
1049 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
1057 * Allow others to run.
1059 atomic_inc(&mce_executing);
1062 /* CHECKME: Can this race with a parallel hotplug? */
1063 int cpus = num_online_cpus();
1066 * Monarch: Wait for everyone to go through their scanning
1069 while (atomic_read(&mce_executing) <= cpus) {
1070 if (mce_timed_out(&timeout,
1071 "Timeout: Monarch CPU unable to finish machine check processing"))
1081 * Subject: Wait for Monarch to finish.
1083 while (atomic_read(&mce_executing) != 0) {
1084 if (mce_timed_out(&timeout,
1085 "Timeout: Monarch CPU did not finish machine check processing"))
1091 * Don't reset anything. That's done by the Monarch.
1097 * Reset all global state.
1100 atomic_set(&global_nwo, 0);
1101 atomic_set(&mce_callin, 0);
1105 * Let others run again.
1107 atomic_set(&mce_executing, 0);
1111 static void mce_clear_state(unsigned long *toclear)
1115 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1116 if (test_bit(i, toclear))
1117 mce_wrmsrl(msr_ops.status(i), 0);
1122 * Cases where we avoid rendezvous handler timeout:
1123 * 1) If this CPU is offline.
1125 * 2) If crashing_cpu was set, e.g. we're entering kdump and we need to
1126 * skip those CPUs which remain looping in the 1st kernel - see
1127 * crash_nmi_callback().
1129 * Note: there still is a small window between kexec-ing and the new,
1130 * kdump kernel establishing a new #MC handler where a broadcasted MCE
1131 * might not get handled properly.
1133 static noinstr bool mce_check_crashing_cpu(void)
1135 unsigned int cpu = smp_processor_id();
1137 if (arch_cpu_is_offline(cpu) ||
1138 (crashing_cpu != -1 && crashing_cpu != cpu)) {
1141 mcgstatus = __rdmsr(MSR_IA32_MCG_STATUS);
1143 if (boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN) {
1144 if (mcgstatus & MCG_STATUS_LMCES)
1148 if (mcgstatus & MCG_STATUS_RIPV) {
1149 __wrmsr(MSR_IA32_MCG_STATUS, 0, 0);
1156 static void __mc_scan_banks(struct mce *m, struct mce *final,
1157 unsigned long *toclear, unsigned long *valid_banks,
1158 int no_way_out, int *worst)
1160 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1161 struct mca_config *cfg = &mca_cfg;
1164 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1165 __clear_bit(i, toclear);
1166 if (!test_bit(i, valid_banks))
1169 if (!mce_banks[i].ctl)
1176 m->status = mce_rdmsrl(msr_ops.status(i));
1177 if (!(m->status & MCI_STATUS_VAL))
1181 * Corrected or non-signaled errors are handled by
1182 * machine_check_poll(). Leave them alone, unless this panics.
1184 if (!(m->status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1188 /* Set taint even when machine check was not enabled. */
1189 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1191 severity = mce_severity(m, cfg->tolerant, NULL, true);
1194 * When machine check was for corrected/deferred handler don't
1195 * touch, unless we're panicking.
1197 if ((severity == MCE_KEEP_SEVERITY ||
1198 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1201 __set_bit(i, toclear);
1203 /* Machine check event was not enabled. Clear, but ignore. */
1204 if (severity == MCE_NO_SEVERITY)
1209 /* assuming valid severity level != 0 */
1210 m->severity = severity;
1214 if (severity > *worst) {
1220 /* mce_clear_state will clear *final, save locally for use later */
1224 static void kill_me_now(struct callback_head *ch)
1229 static void kill_me_maybe(struct callback_head *cb)
1231 struct task_struct *p = container_of(cb, struct task_struct, mce_kill_me);
1232 int flags = MF_ACTION_REQUIRED;
1234 pr_err("Uncorrected hardware memory error in user-access at %llx", p->mce_addr);
1237 flags |= MF_MUST_KILL;
1239 if (!memory_failure(p->mce_addr >> PAGE_SHIFT, flags)) {
1240 set_mce_nospec(p->mce_addr >> PAGE_SHIFT, p->mce_whole_page);
1245 pr_err("Memory error not recovered");
1250 * The actual machine check handler. This only handles real
1251 * exceptions when something got corrupted coming in through int 18.
1253 * This is executed in NMI context not subject to normal locking rules. This
1254 * implies that most kernel services cannot be safely used. Don't even
1255 * think about putting a printk in there!
1257 * On Intel systems this is entered on all CPUs in parallel through
1258 * MCE broadcast. However some CPUs might be broken beyond repair,
1259 * so be always careful when synchronizing with others.
1261 * Tracing and kprobes are disabled: if we interrupted a kernel context
1262 * with IF=1, we need to minimize stack usage. There are also recursion
1263 * issues: if the machine check was due to a failure of the memory
1264 * backing the user stack, tracing that reads the user stack will cause
1265 * potentially infinite recursion.
1267 noinstr void do_machine_check(struct pt_regs *regs)
1269 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1270 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1271 struct mca_config *cfg = &mca_cfg;
1272 struct mce m, *final;
1277 * Establish sequential order between the CPUs entering the machine
1283 * If no_way_out gets set, there is no safe way to recover from this
1284 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1289 * If kill_it gets set, there might be a way to recover from this
1295 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1300 this_cpu_inc(mce_exception_count);
1302 mce_gather_info(&m, regs);
1305 final = this_cpu_ptr(&mces_seen);
1308 memset(valid_banks, 0, sizeof(valid_banks));
1309 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1314 * When no restart IP might need to kill or panic.
1315 * Assume the worst for now, but if we find the
1316 * severity is MCE_AR_SEVERITY we have other options.
1318 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1322 * Check if this MCE is signaled to only this logical processor,
1323 * on Intel, Zhaoxin only.
1325 if (m.cpuvendor == X86_VENDOR_INTEL ||
1326 m.cpuvendor == X86_VENDOR_ZHAOXIN)
1327 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1330 * Local machine check may already know that we have to panic.
1331 * Broadcast machine check begins rendezvous in mce_start()
1332 * Go through all banks in exclusion of the other CPUs. This way we
1333 * don't report duplicated events on shared banks because the first one
1334 * to see it will clear it.
1338 mce_panic("Fatal local machine check", &m, msg);
1340 order = mce_start(&no_way_out);
1343 __mc_scan_banks(&m, final, toclear, valid_banks, no_way_out, &worst);
1346 mce_clear_state(toclear);
1349 * Do most of the synchronization with other CPUs.
1350 * When there's any problem use only local no_way_out state.
1353 if (mce_end(order) < 0)
1354 no_way_out = worst >= MCE_PANIC_SEVERITY;
1357 * If there was a fatal machine check we should have
1358 * already called mce_panic earlier in this function.
1359 * Since we re-read the banks, we might have found
1360 * something new. Check again to see if we found a
1361 * fatal error. We call "mce_severity()" again to
1362 * make sure we have the right "msg".
1364 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3) {
1365 mce_severity(&m, cfg->tolerant, &msg, true);
1366 mce_panic("Local fatal machine check!", &m, msg);
1371 * If tolerant is at an insane level we drop requests to kill
1372 * processes and continue even when there is no way out.
1374 if (cfg->tolerant == 3)
1376 else if (no_way_out)
1377 mce_panic("Fatal machine check on current CPU", &m, msg);
1380 irq_work_queue(&mce_irq_work);
1382 if (worst != MCE_AR_SEVERITY && !kill_it)
1385 /* Fault was in user mode and we need to take some action */
1386 if ((m.cs & 3) == 3) {
1387 /* If this triggers there is no way to recover. Die hard. */
1388 BUG_ON(!on_thread_stack() || !user_mode(regs));
1390 current->mce_addr = m.addr;
1391 current->mce_ripv = !!(m.mcgstatus & MCG_STATUS_RIPV);
1392 current->mce_whole_page = whole_page(&m);
1393 current->mce_kill_me.func = kill_me_maybe;
1395 current->mce_kill_me.func = kill_me_now;
1396 task_work_add(current, ¤t->mce_kill_me, true);
1399 * Handle an MCE which has happened in kernel space but from
1400 * which the kernel can recover: ex_has_fault_handler() has
1401 * already verified that the rIP at which the error happened is
1402 * a rIP from which the kernel can recover (by jumping to
1403 * recovery code specified in _ASM_EXTABLE_FAULT()) and the
1404 * corresponding exception handler which would do that is the
1407 if (m.kflags & MCE_IN_KERNEL_RECOV) {
1408 if (!fixup_exception(regs, X86_TRAP_MC, 0, 0))
1409 mce_panic("Failed kernel mode recovery", &m, msg);
1413 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1415 EXPORT_SYMBOL_GPL(do_machine_check);
1417 #ifndef CONFIG_MEMORY_FAILURE
1418 int memory_failure(unsigned long pfn, int flags)
1420 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1421 BUG_ON(flags & MF_ACTION_REQUIRED);
1422 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1423 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1431 * Periodic polling timer for "silent" machine check errors. If the
1432 * poller finds an MCE, poll 2x faster. When the poller finds no more
1433 * errors, poll 2x slower (up to check_interval seconds).
1435 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1437 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1438 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1440 static unsigned long mce_adjust_timer_default(unsigned long interval)
1445 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1447 static void __start_timer(struct timer_list *t, unsigned long interval)
1449 unsigned long when = jiffies + interval;
1450 unsigned long flags;
1452 local_irq_save(flags);
1454 if (!timer_pending(t) || time_before(when, t->expires))
1455 mod_timer(t, round_jiffies(when));
1457 local_irq_restore(flags);
1460 static void mce_timer_fn(struct timer_list *t)
1462 struct timer_list *cpu_t = this_cpu_ptr(&mce_timer);
1465 WARN_ON(cpu_t != t);
1467 iv = __this_cpu_read(mce_next_interval);
1469 if (mce_available(this_cpu_ptr(&cpu_info))) {
1470 machine_check_poll(0, this_cpu_ptr(&mce_poll_banks));
1472 if (mce_intel_cmci_poll()) {
1473 iv = mce_adjust_timer(iv);
1479 * Alert userspace if needed. If we logged an MCE, reduce the polling
1480 * interval, otherwise increase the polling interval.
1482 if (mce_notify_irq())
1483 iv = max(iv / 2, (unsigned long) HZ/100);
1485 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1488 __this_cpu_write(mce_next_interval, iv);
1489 __start_timer(t, iv);
1493 * Ensure that the timer is firing in @interval from now.
1495 void mce_timer_kick(unsigned long interval)
1497 struct timer_list *t = this_cpu_ptr(&mce_timer);
1498 unsigned long iv = __this_cpu_read(mce_next_interval);
1500 __start_timer(t, interval);
1503 __this_cpu_write(mce_next_interval, interval);
1506 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1507 static void mce_timer_delete_all(void)
1511 for_each_online_cpu(cpu)
1512 del_timer_sync(&per_cpu(mce_timer, cpu));
1516 * Notify the user(s) about new machine check events.
1517 * Can be called from interrupt context, but not from machine check/NMI
1520 int mce_notify_irq(void)
1522 /* Not more than two messages every minute */
1523 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1525 if (test_and_clear_bit(0, &mce_need_notify)) {
1528 if (__ratelimit(&ratelimit))
1529 pr_info(HW_ERR "Machine check events logged\n");
1535 EXPORT_SYMBOL_GPL(mce_notify_irq);
1537 static void __mcheck_cpu_mce_banks_init(void)
1539 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1540 u8 n_banks = this_cpu_read(mce_num_banks);
1543 for (i = 0; i < n_banks; i++) {
1544 struct mce_bank *b = &mce_banks[i];
1547 * Init them all, __mcheck_cpu_apply_quirks() is going to apply
1548 * the required vendor quirks before
1549 * __mcheck_cpu_init_clear_banks() does the final bank setup.
1557 * Initialize Machine Checks for a CPU.
1559 static void __mcheck_cpu_cap_init(void)
1564 rdmsrl(MSR_IA32_MCG_CAP, cap);
1566 b = cap & MCG_BANKCNT_MASK;
1568 if (b > MAX_NR_BANKS) {
1569 pr_warn("CPU%d: Using only %u machine check banks out of %u\n",
1570 smp_processor_id(), MAX_NR_BANKS, b);
1574 this_cpu_write(mce_num_banks, b);
1576 __mcheck_cpu_mce_banks_init();
1578 /* Use accurate RIP reporting if available. */
1579 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1580 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1582 if (cap & MCG_SER_P)
1586 static void __mcheck_cpu_init_generic(void)
1588 enum mcp_flags m_fl = 0;
1589 mce_banks_t all_banks;
1592 if (!mca_cfg.bootlog)
1596 * Log the machine checks left over from the previous reset.
1598 bitmap_fill(all_banks, MAX_NR_BANKS);
1599 machine_check_poll(MCP_UC | m_fl, &all_banks);
1601 cr4_set_bits(X86_CR4_MCE);
1603 rdmsrl(MSR_IA32_MCG_CAP, cap);
1604 if (cap & MCG_CTL_P)
1605 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1608 static void __mcheck_cpu_init_clear_banks(void)
1610 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1613 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1614 struct mce_bank *b = &mce_banks[i];
1618 wrmsrl(msr_ops.ctl(i), b->ctl);
1619 wrmsrl(msr_ops.status(i), 0);
1624 * Do a final check to see if there are any unused/RAZ banks.
1626 * This must be done after the banks have been initialized and any quirks have
1629 * Do not call this from any user-initiated flows, e.g. CPU hotplug or sysfs.
1630 * Otherwise, a user who disables a bank will not be able to re-enable it
1631 * without a system reboot.
1633 static void __mcheck_cpu_check_banks(void)
1635 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1639 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1640 struct mce_bank *b = &mce_banks[i];
1645 rdmsrl(msr_ops.ctl(i), msrval);
1651 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1652 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1653 * Vol 3B Table 15-20). But this confuses both the code that determines
1654 * whether the machine check occurred in kernel or user mode, and also
1655 * the severity assessment code. Pretend that EIPV was set, and take the
1656 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1658 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1662 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1664 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1665 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1666 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1668 (MCI_STATUS_UC|MCI_STATUS_EN|
1669 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1670 MCI_STATUS_AR|MCACOD_INSTR))
1673 m->mcgstatus |= MCG_STATUS_EIPV;
1678 /* Add per CPU specific workarounds here */
1679 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1681 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1682 struct mca_config *cfg = &mca_cfg;
1684 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1685 pr_info("unknown CPU type - not enabling MCE support\n");
1689 /* This should be disabled by the BIOS, but isn't always */
1690 if (c->x86_vendor == X86_VENDOR_AMD) {
1691 if (c->x86 == 15 && this_cpu_read(mce_num_banks) > 4) {
1693 * disable GART TBL walk error reporting, which
1694 * trips off incorrectly with the IOMMU & 3ware
1697 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1699 if (c->x86 < 0x11 && cfg->bootlog < 0) {
1701 * Lots of broken BIOS around that don't clear them
1702 * by default and leave crap in there. Don't log:
1707 * Various K7s with broken bank 0 around. Always disable
1710 if (c->x86 == 6 && this_cpu_read(mce_num_banks) > 0)
1711 mce_banks[0].ctl = 0;
1714 * overflow_recov is supported for F15h Models 00h-0fh
1715 * even though we don't have a CPUID bit for it.
1717 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1718 mce_flags.overflow_recov = 1;
1722 if (c->x86_vendor == X86_VENDOR_INTEL) {
1724 * SDM documents that on family 6 bank 0 should not be written
1725 * because it aliases to another special BIOS controlled
1727 * But it's not aliased anymore on model 0x1a+
1728 * Don't ignore bank 0 completely because there could be a
1729 * valid event later, merely don't write CTL0.
1732 if (c->x86 == 6 && c->x86_model < 0x1A && this_cpu_read(mce_num_banks) > 0)
1733 mce_banks[0].init = 0;
1736 * All newer Intel systems support MCE broadcasting. Enable
1737 * synchronization with a one second timeout.
1739 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1740 cfg->monarch_timeout < 0)
1741 cfg->monarch_timeout = USEC_PER_SEC;
1744 * There are also broken BIOSes on some Pentium M and
1747 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1750 if (c->x86 == 6 && c->x86_model == 45)
1751 quirk_no_way_out = quirk_sandybridge_ifu;
1754 if (c->x86_vendor == X86_VENDOR_ZHAOXIN) {
1756 * All newer Zhaoxin CPUs support MCE broadcasting. Enable
1757 * synchronization with a one second timeout.
1759 if (c->x86 > 6 || (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1760 if (cfg->monarch_timeout < 0)
1761 cfg->monarch_timeout = USEC_PER_SEC;
1765 if (cfg->monarch_timeout < 0)
1766 cfg->monarch_timeout = 0;
1767 if (cfg->bootlog != 0)
1768 cfg->panic_timeout = 30;
1773 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1778 switch (c->x86_vendor) {
1779 case X86_VENDOR_INTEL:
1780 intel_p5_mcheck_init(c);
1783 case X86_VENDOR_CENTAUR:
1784 winchip_mcheck_init(c);
1795 * Init basic CPU features needed for early decoding of MCEs.
1797 static void __mcheck_cpu_init_early(struct cpuinfo_x86 *c)
1799 if (c->x86_vendor == X86_VENDOR_AMD || c->x86_vendor == X86_VENDOR_HYGON) {
1800 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1801 mce_flags.succor = !!cpu_has(c, X86_FEATURE_SUCCOR);
1802 mce_flags.smca = !!cpu_has(c, X86_FEATURE_SMCA);
1803 mce_flags.amd_threshold = 1;
1805 if (mce_flags.smca) {
1806 msr_ops.ctl = smca_ctl_reg;
1807 msr_ops.status = smca_status_reg;
1808 msr_ops.addr = smca_addr_reg;
1809 msr_ops.misc = smca_misc_reg;
1814 static void mce_centaur_feature_init(struct cpuinfo_x86 *c)
1816 struct mca_config *cfg = &mca_cfg;
1819 * All newer Centaur CPUs support MCE broadcasting. Enable
1820 * synchronization with a one second timeout.
1822 if ((c->x86 == 6 && c->x86_model == 0xf && c->x86_stepping >= 0xe) ||
1824 if (cfg->monarch_timeout < 0)
1825 cfg->monarch_timeout = USEC_PER_SEC;
1829 static void mce_zhaoxin_feature_init(struct cpuinfo_x86 *c)
1831 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1834 * These CPUs have MCA bank 8 which reports only one error type called
1835 * SVAD (System View Address Decoder). The reporting of that error is
1836 * controlled by IA32_MC8.CTL.0.
1838 * If enabled, prefetching on these CPUs will cause SVAD MCE when
1839 * virtual machines start and result in a system panic. Always disable
1840 * bank 8 SVAD error by default.
1842 if ((c->x86 == 7 && c->x86_model == 0x1b) ||
1843 (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1844 if (this_cpu_read(mce_num_banks) > 8)
1845 mce_banks[8].ctl = 0;
1850 mce_adjust_timer = cmci_intel_adjust_timer;
1853 static void mce_zhaoxin_feature_clear(struct cpuinfo_x86 *c)
1858 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1860 switch (c->x86_vendor) {
1861 case X86_VENDOR_INTEL:
1862 mce_intel_feature_init(c);
1863 mce_adjust_timer = cmci_intel_adjust_timer;
1866 case X86_VENDOR_AMD: {
1867 mce_amd_feature_init(c);
1871 case X86_VENDOR_HYGON:
1872 mce_hygon_feature_init(c);
1875 case X86_VENDOR_CENTAUR:
1876 mce_centaur_feature_init(c);
1879 case X86_VENDOR_ZHAOXIN:
1880 mce_zhaoxin_feature_init(c);
1888 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1890 switch (c->x86_vendor) {
1891 case X86_VENDOR_INTEL:
1892 mce_intel_feature_clear(c);
1895 case X86_VENDOR_ZHAOXIN:
1896 mce_zhaoxin_feature_clear(c);
1904 static void mce_start_timer(struct timer_list *t)
1906 unsigned long iv = check_interval * HZ;
1908 if (mca_cfg.ignore_ce || !iv)
1911 this_cpu_write(mce_next_interval, iv);
1912 __start_timer(t, iv);
1915 static void __mcheck_cpu_setup_timer(void)
1917 struct timer_list *t = this_cpu_ptr(&mce_timer);
1919 timer_setup(t, mce_timer_fn, TIMER_PINNED);
1922 static void __mcheck_cpu_init_timer(void)
1924 struct timer_list *t = this_cpu_ptr(&mce_timer);
1926 timer_setup(t, mce_timer_fn, TIMER_PINNED);
1930 bool filter_mce(struct mce *m)
1932 if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
1933 return amd_filter_mce(m);
1934 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
1935 return intel_filter_mce(m);
1940 /* Handle unconfigured int18 (should never happen) */
1941 static noinstr void unexpected_machine_check(struct pt_regs *regs)
1943 instrumentation_begin();
1944 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1945 smp_processor_id());
1946 instrumentation_end();
1949 /* Call the installed machine check handler for this CPU setup. */
1950 void (*machine_check_vector)(struct pt_regs *) = unexpected_machine_check;
1952 static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)
1954 WARN_ON_ONCE(user_mode(regs));
1957 * Only required when from kernel mode. See
1958 * mce_check_crashing_cpu() for details.
1960 if (machine_check_vector == do_machine_check &&
1961 mce_check_crashing_cpu())
1966 * The call targets are marked noinstr, but objtool can't figure
1967 * that out because it's an indirect call. Annotate it.
1969 instrumentation_begin();
1970 trace_hardirqs_off_finish();
1971 machine_check_vector(regs);
1972 if (regs->flags & X86_EFLAGS_IF)
1973 trace_hardirqs_on_prepare();
1974 instrumentation_end();
1978 static __always_inline void exc_machine_check_user(struct pt_regs *regs)
1980 irqentry_enter_from_user_mode(regs);
1981 instrumentation_begin();
1982 machine_check_vector(regs);
1983 instrumentation_end();
1984 irqentry_exit_to_user_mode(regs);
1987 #ifdef CONFIG_X86_64
1988 /* MCE hit kernel mode */
1989 DEFINE_IDTENTRY_MCE(exc_machine_check)
1993 dr7 = local_db_save();
1994 exc_machine_check_kernel(regs);
1995 local_db_restore(dr7);
1998 /* The user mode variant. */
1999 DEFINE_IDTENTRY_MCE_USER(exc_machine_check)
2003 dr7 = local_db_save();
2004 exc_machine_check_user(regs);
2005 local_db_restore(dr7);
2008 /* 32bit unified entry point */
2009 DEFINE_IDTENTRY_RAW(exc_machine_check)
2013 dr7 = local_db_save();
2014 if (user_mode(regs))
2015 exc_machine_check_user(regs);
2017 exc_machine_check_kernel(regs);
2018 local_db_restore(dr7);
2023 * Called for each booted CPU to set up machine checks.
2024 * Must be called with preempt off:
2026 void mcheck_cpu_init(struct cpuinfo_x86 *c)
2028 if (mca_cfg.disabled)
2031 if (__mcheck_cpu_ancient_init(c))
2034 if (!mce_available(c))
2037 __mcheck_cpu_cap_init();
2039 if (__mcheck_cpu_apply_quirks(c) < 0) {
2040 mca_cfg.disabled = 1;
2044 if (mce_gen_pool_init()) {
2045 mca_cfg.disabled = 1;
2046 pr_emerg("Couldn't allocate MCE records pool!\n");
2050 machine_check_vector = do_machine_check;
2052 __mcheck_cpu_init_early(c);
2053 __mcheck_cpu_init_generic();
2054 __mcheck_cpu_init_vendor(c);
2055 __mcheck_cpu_init_clear_banks();
2056 __mcheck_cpu_check_banks();
2057 __mcheck_cpu_setup_timer();
2061 * Called for each booted CPU to clear some machine checks opt-ins
2063 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
2065 if (mca_cfg.disabled)
2068 if (!mce_available(c))
2072 * Possibly to clear general settings generic to x86
2073 * __mcheck_cpu_clear_generic(c);
2075 __mcheck_cpu_clear_vendor(c);
2079 static void __mce_disable_bank(void *arg)
2081 int bank = *((int *)arg);
2082 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2083 cmci_disable_bank(bank);
2086 void mce_disable_bank(int bank)
2088 if (bank >= this_cpu_read(mce_num_banks)) {
2090 "Ignoring request to disable invalid MCA bank %d.\n",
2094 set_bit(bank, mce_banks_ce_disabled);
2095 on_each_cpu(__mce_disable_bank, &bank, 1);
2099 * mce=off Disables machine check
2100 * mce=no_cmci Disables CMCI
2101 * mce=no_lmce Disables LMCE
2102 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2103 * mce=print_all Print all machine check logs to console
2104 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2105 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2106 * monarchtimeout is how long to wait for other CPUs on machine
2107 * check, or 0 to not wait
2108 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD Fam10h
2110 * mce=nobootlog Don't log MCEs from before booting.
2111 * mce=bios_cmci_threshold Don't program the CMCI threshold
2112 * mce=recovery force enable memcpy_mcsafe()
2114 static int __init mcheck_enable(char *str)
2116 struct mca_config *cfg = &mca_cfg;
2124 if (!strcmp(str, "off"))
2126 else if (!strcmp(str, "no_cmci"))
2127 cfg->cmci_disabled = true;
2128 else if (!strcmp(str, "no_lmce"))
2129 cfg->lmce_disabled = 1;
2130 else if (!strcmp(str, "dont_log_ce"))
2131 cfg->dont_log_ce = true;
2132 else if (!strcmp(str, "print_all"))
2133 cfg->print_all = true;
2134 else if (!strcmp(str, "ignore_ce"))
2135 cfg->ignore_ce = true;
2136 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2137 cfg->bootlog = (str[0] == 'b');
2138 else if (!strcmp(str, "bios_cmci_threshold"))
2139 cfg->bios_cmci_threshold = 1;
2140 else if (!strcmp(str, "recovery"))
2142 else if (isdigit(str[0])) {
2143 if (get_option(&str, &cfg->tolerant) == 2)
2144 get_option(&str, &(cfg->monarch_timeout));
2146 pr_info("mce argument %s ignored. Please use /sys\n", str);
2151 __setup("mce", mcheck_enable);
2153 int __init mcheck_init(void)
2155 mcheck_intel_therm_init();
2156 mce_register_decode_chain(&early_nb);
2157 mce_register_decode_chain(&mce_uc_nb);
2158 mce_register_decode_chain(&mce_default_nb);
2159 mcheck_vendor_init_severity();
2161 INIT_WORK(&mce_work, mce_gen_pool_process);
2162 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2168 * mce_syscore: PM support
2172 * Disable machine checks on suspend and shutdown. We can't really handle
2175 static void mce_disable_error_reporting(void)
2177 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2180 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2181 struct mce_bank *b = &mce_banks[i];
2184 wrmsrl(msr_ops.ctl(i), 0);
2189 static void vendor_disable_error_reporting(void)
2192 * Don't clear on Intel or AMD or Hygon or Zhaoxin CPUs. Some of these
2193 * MSRs are socket-wide. Disabling them for just a single offlined CPU
2194 * is bad, since it will inhibit reporting for all shared resources on
2195 * the socket like the last level cache (LLC), the integrated memory
2196 * controller (iMC), etc.
2198 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL ||
2199 boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ||
2200 boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
2201 boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN)
2204 mce_disable_error_reporting();
2207 static int mce_syscore_suspend(void)
2209 vendor_disable_error_reporting();
2213 static void mce_syscore_shutdown(void)
2215 vendor_disable_error_reporting();
2219 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2220 * Only one CPU is active at this time, the others get re-added later using
2223 static void mce_syscore_resume(void)
2225 __mcheck_cpu_init_generic();
2226 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2227 __mcheck_cpu_init_clear_banks();
2230 static struct syscore_ops mce_syscore_ops = {
2231 .suspend = mce_syscore_suspend,
2232 .shutdown = mce_syscore_shutdown,
2233 .resume = mce_syscore_resume,
2237 * mce_device: Sysfs support
2240 static void mce_cpu_restart(void *data)
2242 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2244 __mcheck_cpu_init_generic();
2245 __mcheck_cpu_init_clear_banks();
2246 __mcheck_cpu_init_timer();
2249 /* Reinit MCEs after user configuration changes */
2250 static void mce_restart(void)
2252 mce_timer_delete_all();
2253 on_each_cpu(mce_cpu_restart, NULL, 1);
2256 /* Toggle features for corrected errors */
2257 static void mce_disable_cmci(void *data)
2259 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2264 static void mce_enable_ce(void *all)
2266 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2271 __mcheck_cpu_init_timer();
2274 static struct bus_type mce_subsys = {
2275 .name = "machinecheck",
2276 .dev_name = "machinecheck",
2279 DEFINE_PER_CPU(struct device *, mce_device);
2281 static inline struct mce_bank_dev *attr_to_bank(struct device_attribute *attr)
2283 return container_of(attr, struct mce_bank_dev, attr);
2286 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2289 u8 bank = attr_to_bank(attr)->bank;
2292 if (bank >= per_cpu(mce_num_banks, s->id))
2295 b = &per_cpu(mce_banks_array, s->id)[bank];
2300 return sprintf(buf, "%llx\n", b->ctl);
2303 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2304 const char *buf, size_t size)
2306 u8 bank = attr_to_bank(attr)->bank;
2310 if (kstrtou64(buf, 0, &new) < 0)
2313 if (bank >= per_cpu(mce_num_banks, s->id))
2316 b = &per_cpu(mce_banks_array, s->id)[bank];
2327 static ssize_t set_ignore_ce(struct device *s,
2328 struct device_attribute *attr,
2329 const char *buf, size_t size)
2333 if (kstrtou64(buf, 0, &new) < 0)
2336 mutex_lock(&mce_sysfs_mutex);
2337 if (mca_cfg.ignore_ce ^ !!new) {
2339 /* disable ce features */
2340 mce_timer_delete_all();
2341 on_each_cpu(mce_disable_cmci, NULL, 1);
2342 mca_cfg.ignore_ce = true;
2344 /* enable ce features */
2345 mca_cfg.ignore_ce = false;
2346 on_each_cpu(mce_enable_ce, (void *)1, 1);
2349 mutex_unlock(&mce_sysfs_mutex);
2354 static ssize_t set_cmci_disabled(struct device *s,
2355 struct device_attribute *attr,
2356 const char *buf, size_t size)
2360 if (kstrtou64(buf, 0, &new) < 0)
2363 mutex_lock(&mce_sysfs_mutex);
2364 if (mca_cfg.cmci_disabled ^ !!new) {
2367 on_each_cpu(mce_disable_cmci, NULL, 1);
2368 mca_cfg.cmci_disabled = true;
2371 mca_cfg.cmci_disabled = false;
2372 on_each_cpu(mce_enable_ce, NULL, 1);
2375 mutex_unlock(&mce_sysfs_mutex);
2380 static ssize_t store_int_with_restart(struct device *s,
2381 struct device_attribute *attr,
2382 const char *buf, size_t size)
2384 unsigned long old_check_interval = check_interval;
2385 ssize_t ret = device_store_ulong(s, attr, buf, size);
2387 if (check_interval == old_check_interval)
2390 mutex_lock(&mce_sysfs_mutex);
2392 mutex_unlock(&mce_sysfs_mutex);
2397 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2398 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2399 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2400 static DEVICE_BOOL_ATTR(print_all, 0644, mca_cfg.print_all);
2402 static struct dev_ext_attribute dev_attr_check_interval = {
2403 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2407 static struct dev_ext_attribute dev_attr_ignore_ce = {
2408 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2412 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2413 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2414 &mca_cfg.cmci_disabled
2417 static struct device_attribute *mce_device_attrs[] = {
2418 &dev_attr_tolerant.attr,
2419 &dev_attr_check_interval.attr,
2420 #ifdef CONFIG_X86_MCELOG_LEGACY
2423 &dev_attr_monarch_timeout.attr,
2424 &dev_attr_dont_log_ce.attr,
2425 &dev_attr_print_all.attr,
2426 &dev_attr_ignore_ce.attr,
2427 &dev_attr_cmci_disabled.attr,
2431 static cpumask_var_t mce_device_initialized;
2433 static void mce_device_release(struct device *dev)
2438 /* Per CPU device init. All of the CPUs still share the same bank device: */
2439 static int mce_device_create(unsigned int cpu)
2445 if (!mce_available(&boot_cpu_data))
2448 dev = per_cpu(mce_device, cpu);
2452 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2456 dev->bus = &mce_subsys;
2457 dev->release = &mce_device_release;
2459 err = device_register(dev);
2465 for (i = 0; mce_device_attrs[i]; i++) {
2466 err = device_create_file(dev, mce_device_attrs[i]);
2470 for (j = 0; j < per_cpu(mce_num_banks, cpu); j++) {
2471 err = device_create_file(dev, &mce_bank_devs[j].attr);
2475 cpumask_set_cpu(cpu, mce_device_initialized);
2476 per_cpu(mce_device, cpu) = dev;
2481 device_remove_file(dev, &mce_bank_devs[j].attr);
2484 device_remove_file(dev, mce_device_attrs[i]);
2486 device_unregister(dev);
2491 static void mce_device_remove(unsigned int cpu)
2493 struct device *dev = per_cpu(mce_device, cpu);
2496 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2499 for (i = 0; mce_device_attrs[i]; i++)
2500 device_remove_file(dev, mce_device_attrs[i]);
2502 for (i = 0; i < per_cpu(mce_num_banks, cpu); i++)
2503 device_remove_file(dev, &mce_bank_devs[i].attr);
2505 device_unregister(dev);
2506 cpumask_clear_cpu(cpu, mce_device_initialized);
2507 per_cpu(mce_device, cpu) = NULL;
2510 /* Make sure there are no machine checks on offlined CPUs. */
2511 static void mce_disable_cpu(void)
2513 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2516 if (!cpuhp_tasks_frozen)
2519 vendor_disable_error_reporting();
2522 static void mce_reenable_cpu(void)
2524 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2527 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2530 if (!cpuhp_tasks_frozen)
2532 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2533 struct mce_bank *b = &mce_banks[i];
2536 wrmsrl(msr_ops.ctl(i), b->ctl);
2540 static int mce_cpu_dead(unsigned int cpu)
2542 mce_intel_hcpu_update(cpu);
2544 /* intentionally ignoring frozen here */
2545 if (!cpuhp_tasks_frozen)
2550 static int mce_cpu_online(unsigned int cpu)
2552 struct timer_list *t = this_cpu_ptr(&mce_timer);
2555 mce_device_create(cpu);
2557 ret = mce_threshold_create_device(cpu);
2559 mce_device_remove(cpu);
2567 static int mce_cpu_pre_down(unsigned int cpu)
2569 struct timer_list *t = this_cpu_ptr(&mce_timer);
2573 mce_threshold_remove_device(cpu);
2574 mce_device_remove(cpu);
2578 static __init void mce_init_banks(void)
2582 for (i = 0; i < MAX_NR_BANKS; i++) {
2583 struct mce_bank_dev *b = &mce_bank_devs[i];
2584 struct device_attribute *a = &b->attr;
2588 sysfs_attr_init(&a->attr);
2589 a->attr.name = b->attrname;
2590 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2592 a->attr.mode = 0644;
2593 a->show = show_bank;
2594 a->store = set_bank;
2599 * When running on XEN, this initcall is ordered against the XEN mcelog
2602 * device_initcall(xen_late_init_mcelog);
2603 * device_initcall_sync(mcheck_init_device);
2605 static __init int mcheck_init_device(void)
2610 * Check if we have a spare virtual bit. This will only become
2611 * a problem if/when we move beyond 5-level page tables.
2613 MAYBE_BUILD_BUG_ON(__VIRTUAL_MASK_SHIFT >= 63);
2615 if (!mce_available(&boot_cpu_data)) {
2620 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2627 err = subsys_system_register(&mce_subsys, NULL);
2631 err = cpuhp_setup_state(CPUHP_X86_MCE_DEAD, "x86/mce:dead", NULL,
2637 * Invokes mce_cpu_online() on all CPUs which are online when
2638 * the state is installed.
2640 err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/mce:online",
2641 mce_cpu_online, mce_cpu_pre_down);
2643 goto err_out_online;
2645 register_syscore_ops(&mce_syscore_ops);
2650 cpuhp_remove_state(CPUHP_X86_MCE_DEAD);
2653 free_cpumask_var(mce_device_initialized);
2656 pr_err("Unable to init MCE device (rc: %d)\n", err);
2660 device_initcall_sync(mcheck_init_device);
2663 * Old style boot options parsing. Only for compatibility.
2665 static int __init mcheck_disable(char *str)
2667 mca_cfg.disabled = 1;
2670 __setup("nomce", mcheck_disable);
2672 #ifdef CONFIG_DEBUG_FS
2673 struct dentry *mce_get_debugfs_dir(void)
2675 static struct dentry *dmce;
2678 dmce = debugfs_create_dir("mce", NULL);
2683 static void mce_reset(void)
2686 atomic_set(&mce_fake_panicked, 0);
2687 atomic_set(&mce_executing, 0);
2688 atomic_set(&mce_callin, 0);
2689 atomic_set(&global_nwo, 0);
2692 static int fake_panic_get(void *data, u64 *val)
2698 static int fake_panic_set(void *data, u64 val)
2705 DEFINE_DEBUGFS_ATTRIBUTE(fake_panic_fops, fake_panic_get, fake_panic_set,
2708 static void __init mcheck_debugfs_init(void)
2710 struct dentry *dmce;
2712 dmce = mce_get_debugfs_dir();
2713 debugfs_create_file_unsafe("fake_panic", 0444, dmce, NULL,
2717 static void __init mcheck_debugfs_init(void) { }
2720 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2721 EXPORT_SYMBOL_GPL(mcsafe_key);
2723 static int __init mcheck_late_init(void)
2725 if (mca_cfg.recovery)
2726 static_branch_inc(&mcsafe_key);
2728 mcheck_debugfs_init();
2731 * Flush out everything that has been logged during early boot, now that
2732 * everything has been initialized (workqueues, decoders, ...).
2734 mce_schedule_work();
2738 late_initcall(mcheck_late_init);