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/jiffies.h>
45 #include <linux/swork.h>
46 #include <linux/jump_label.h>
48 #include <asm/processor.h>
49 #include <asm/traps.h>
50 #include <asm/tlbflush.h>
54 #include "mce-internal.h"
56 static DEFINE_MUTEX(mce_chrdev_read_mutex);
58 #define mce_log_get_idx_check(p) \
60 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
61 !lockdep_is_held(&mce_chrdev_read_mutex), \
62 "suspicious mce_log_get_idx_check() usage"); \
63 smp_load_acquire(&(p)); \
66 #define CREATE_TRACE_POINTS
67 #include <trace/events/mce.h>
69 #define SPINUNIT 100 /* 100ns */
71 DEFINE_PER_CPU(unsigned, mce_exception_count);
73 struct mce_bank *mce_banks __read_mostly;
74 struct mce_vendor_flags mce_flags __read_mostly;
76 struct mca_config mca_cfg __read_mostly = {
80 * 0: always panic on uncorrected errors, log corrected errors
81 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
82 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
83 * 3: never panic or SIGBUS, log all errors (for testing only)
89 /* User mode helper program triggered by machine check event */
90 static unsigned long mce_need_notify;
91 static char mce_helper[128];
92 static char *mce_helper_argv[2] = { mce_helper, NULL };
94 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
96 static DEFINE_PER_CPU(struct mce, mces_seen);
97 static int cpu_missing;
100 * MCA banks polled by the period polling timer for corrected events.
101 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
103 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
104 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
108 * MCA banks controlled through firmware first for corrected errors.
109 * This is a global list of banks for which we won't enable CMCI and we
110 * won't poll. Firmware controls these banks and is responsible for
111 * reporting corrected errors through GHES. Uncorrected/recoverable
112 * errors are still notified through a machine check.
114 mce_banks_t mce_banks_ce_disabled;
116 static struct work_struct mce_work;
117 static struct irq_work mce_irq_work;
119 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
122 * CPU/chipset specific EDAC code can register a notifier call here to print
123 * MCE errors in a human-readable form.
125 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
127 /* Do initial initialization of a struct mce */
128 void mce_setup(struct mce *m)
130 memset(m, 0, sizeof(struct mce));
131 m->cpu = m->extcpu = smp_processor_id();
133 /* We hope get_seconds stays lockless */
134 m->time = get_seconds();
135 m->cpuvendor = boot_cpu_data.x86_vendor;
136 m->cpuid = cpuid_eax(1);
137 m->socketid = cpu_data(m->extcpu).phys_proc_id;
138 m->apicid = cpu_data(m->extcpu).initial_apicid;
139 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
142 DEFINE_PER_CPU(struct mce, injectm);
143 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
146 * Lockless MCE logging infrastructure.
147 * This avoids deadlocks on printk locks without having to break locks. Also
148 * separate MCEs from kernel messages to avoid bogus bug reports.
151 static struct mce_log mcelog = {
152 .signature = MCE_LOG_SIGNATURE,
154 .recordlen = sizeof(struct mce),
157 void mce_log(struct mce *mce)
159 unsigned next, entry;
161 /* Emit the trace record: */
162 trace_mce_record(mce);
164 if (!mce_gen_pool_add(mce))
165 irq_work_queue(&mce_irq_work);
169 entry = mce_log_get_idx_check(mcelog.next);
173 * When the buffer fills up discard new entries.
174 * Assume that the earlier errors are the more
177 if (entry >= MCE_LOG_LEN) {
178 set_bit(MCE_OVERFLOW,
179 (unsigned long *)&mcelog.flags);
182 /* Old left over entry. Skip: */
183 if (mcelog.entry[entry].finished) {
191 if (cmpxchg(&mcelog.next, entry, next) == entry)
194 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
196 mcelog.entry[entry].finished = 1;
199 set_bit(0, &mce_need_notify);
202 void mce_inject_log(struct mce *m)
204 mutex_lock(&mce_chrdev_read_mutex);
206 mutex_unlock(&mce_chrdev_read_mutex);
208 EXPORT_SYMBOL_GPL(mce_inject_log);
210 static struct notifier_block mce_srao_nb;
212 void mce_register_decode_chain(struct notifier_block *nb)
214 /* Ensure SRAO notifier has the highest priority in the decode chain. */
215 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
218 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
220 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
222 void mce_unregister_decode_chain(struct notifier_block *nb)
224 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
226 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
228 static inline u32 ctl_reg(int bank)
230 return MSR_IA32_MCx_CTL(bank);
233 static inline u32 status_reg(int bank)
235 return MSR_IA32_MCx_STATUS(bank);
238 static inline u32 addr_reg(int bank)
240 return MSR_IA32_MCx_ADDR(bank);
243 static inline u32 misc_reg(int bank)
245 return MSR_IA32_MCx_MISC(bank);
248 static inline u32 smca_ctl_reg(int bank)
250 return MSR_AMD64_SMCA_MCx_CTL(bank);
253 static inline u32 smca_status_reg(int bank)
255 return MSR_AMD64_SMCA_MCx_STATUS(bank);
258 static inline u32 smca_addr_reg(int bank)
260 return MSR_AMD64_SMCA_MCx_ADDR(bank);
263 static inline u32 smca_misc_reg(int bank)
265 return MSR_AMD64_SMCA_MCx_MISC(bank);
268 struct mca_msr_regs msr_ops = {
270 .status = status_reg,
275 static void print_mce(struct mce *m)
279 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
280 m->extcpu, m->mcgstatus, m->bank, m->status);
283 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
284 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
287 if (m->cs == __KERNEL_CS)
288 print_symbol("{%s}", m->ip);
292 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
294 pr_cont("ADDR %llx ", m->addr);
296 pr_cont("MISC %llx ", m->misc);
298 if (mce_flags.smca) {
300 pr_cont("SYND %llx ", m->synd);
302 pr_cont("IPID %llx ", m->ipid);
307 * Note this output is parsed by external tools and old fields
308 * should not be changed.
310 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
311 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
312 cpu_data(m->extcpu).microcode);
315 * Print out human-readable details about the MCE error,
316 * (if the CPU has an implementation for that)
318 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
319 if (ret == NOTIFY_STOP)
322 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
325 #define PANIC_TIMEOUT 5 /* 5 seconds */
327 static atomic_t mce_panicked;
329 static int fake_panic;
330 static atomic_t mce_fake_panicked;
332 /* Panic in progress. Enable interrupts and wait for final IPI */
333 static void wait_for_panic(void)
335 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
339 while (timeout-- > 0)
341 if (panic_timeout == 0)
342 panic_timeout = mca_cfg.panic_timeout;
343 panic("Panicing machine check CPU died");
346 static void mce_panic(const char *msg, struct mce *final, char *exp)
349 struct llist_node *pending;
350 struct mce_evt_llist *l;
354 * Make sure only one CPU runs in machine check panic
356 if (atomic_inc_return(&mce_panicked) > 1)
363 /* Don't log too much for fake panic */
364 if (atomic_inc_return(&mce_fake_panicked) > 1)
367 pending = mce_gen_pool_prepare_records();
368 /* First print corrected ones that are still unlogged */
369 llist_for_each_entry(l, pending, llnode) {
370 struct mce *m = &l->mce;
371 if (!(m->status & MCI_STATUS_UC)) {
374 apei_err = apei_write_mce(m);
377 /* Now print uncorrected but with the final one last */
378 llist_for_each_entry(l, pending, llnode) {
379 struct mce *m = &l->mce;
380 if (!(m->status & MCI_STATUS_UC))
382 if (!final || mce_cmp(m, final)) {
385 apei_err = apei_write_mce(m);
391 apei_err = apei_write_mce(final);
394 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
396 pr_emerg(HW_ERR "Machine check: %s\n", exp);
398 if (panic_timeout == 0)
399 panic_timeout = mca_cfg.panic_timeout;
402 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
405 /* Support code for software error injection */
407 static int msr_to_offset(u32 msr)
409 unsigned bank = __this_cpu_read(injectm.bank);
411 if (msr == mca_cfg.rip_msr)
412 return offsetof(struct mce, ip);
413 if (msr == msr_ops.status(bank))
414 return offsetof(struct mce, status);
415 if (msr == msr_ops.addr(bank))
416 return offsetof(struct mce, addr);
417 if (msr == msr_ops.misc(bank))
418 return offsetof(struct mce, misc);
419 if (msr == MSR_IA32_MCG_STATUS)
420 return offsetof(struct mce, mcgstatus);
424 /* MSR access wrappers used for error injection */
425 static u64 mce_rdmsrl(u32 msr)
429 if (__this_cpu_read(injectm.finished)) {
430 int offset = msr_to_offset(msr);
434 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
437 if (rdmsrl_safe(msr, &v)) {
438 WARN_ONCE(1, "mce: Unable to read MSR 0x%x!\n", msr);
440 * Return zero in case the access faulted. This should
441 * not happen normally but can happen if the CPU does
442 * something weird, or if the code is buggy.
450 static void mce_wrmsrl(u32 msr, u64 v)
452 if (__this_cpu_read(injectm.finished)) {
453 int offset = msr_to_offset(msr);
456 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
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() && keventd_up())
505 schedule_work(&mce_work);
508 static void mce_irq_work_cb(struct irq_work *entry)
514 static void mce_report_event(struct pt_regs *regs)
516 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
519 * Triggering the work queue here is just an insurance
520 * policy in case the syscall exit notify handler
521 * doesn't run soon enough or ends up running on the
522 * wrong CPU (can happen when audit sleeps)
528 irq_work_queue(&mce_irq_work);
532 * Check if the address reported by the CPU is in a format we can parse.
533 * It would be possible to add code for most other cases, but all would
534 * be somewhat complicated (e.g. segment offset would require an instruction
535 * parser). So only support physical addresses up to page granuality for now.
537 static int mce_usable_address(struct mce *m)
539 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
542 /* Checks after this one are Intel-specific: */
543 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
546 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
548 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
553 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
556 struct mce *mce = (struct mce *)data;
562 if (mce_usable_address(mce) && (mce->severity == MCE_AO_SEVERITY)) {
563 pfn = mce->addr >> PAGE_SHIFT;
564 memory_failure(pfn, MCE_VECTOR, 0);
569 static struct notifier_block mce_srao_nb = {
570 .notifier_call = srao_decode_notifier,
575 * Read ADDR and MISC registers.
577 static void mce_read_aux(struct mce *m, int i)
579 if (m->status & MCI_STATUS_MISCV)
580 m->misc = mce_rdmsrl(msr_ops.misc(i));
582 if (m->status & MCI_STATUS_ADDRV) {
583 m->addr = mce_rdmsrl(msr_ops.addr(i));
586 * Mask the reported address by the reported granularity.
588 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
589 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
595 * Extract [55:<lsb>] where lsb is the least significant
596 * *valid* bit of the address bits.
598 if (mce_flags.smca) {
599 u8 lsb = (m->addr >> 56) & 0x3f;
601 m->addr &= GENMASK_ULL(55, lsb);
605 if (mce_flags.smca) {
606 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
608 if (m->status & MCI_STATUS_SYNDV)
609 m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
613 static bool memory_error(struct mce *m)
615 struct cpuinfo_x86 *c = &boot_cpu_data;
617 if (c->x86_vendor == X86_VENDOR_AMD) {
618 /* ErrCodeExt[20:16] */
619 u8 xec = (m->status >> 16) & 0x1f;
621 return (xec == 0x0 || xec == 0x8);
622 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
624 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
626 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
627 * indicating a memory error. Bit 8 is used for indicating a
628 * cache hierarchy error. The combination of bit 2 and bit 3
629 * is used for indicating a `generic' cache hierarchy error
630 * But we can't just blindly check the above bits, because if
631 * bit 11 is set, then it is a bus/interconnect error - and
632 * either way the above bits just gives more detail on what
633 * bus/interconnect error happened. Note that bit 12 can be
634 * ignored, as it's the "filter" bit.
636 return (m->status & 0xef80) == BIT(7) ||
637 (m->status & 0xef00) == BIT(8) ||
638 (m->status & 0xeffc) == 0xc;
644 DEFINE_PER_CPU(unsigned, mce_poll_count);
647 * Poll for corrected events or events that happened before reset.
648 * Those are just logged through /dev/mcelog.
650 * This is executed in standard interrupt context.
652 * Note: spec recommends to panic for fatal unsignalled
653 * errors here. However this would be quite problematic --
654 * we would need to reimplement the Monarch handling and
655 * it would mess up the exclusion between exception handler
656 * and poll hander -- * so we skip this for now.
657 * These cases should not happen anyways, or only when the CPU
658 * is already totally * confused. In this case it's likely it will
659 * not fully execute the machine check handler either.
661 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
663 bool error_seen = false;
668 this_cpu_inc(mce_poll_count);
670 mce_gather_info(&m, NULL);
672 for (i = 0; i < mca_cfg.banks; i++) {
673 if (!mce_banks[i].ctl || !test_bit(i, *b))
682 m.status = mce_rdmsrl(msr_ops.status(i));
683 if (!(m.status & MCI_STATUS_VAL))
688 * Uncorrected or signalled events are handled by the exception
689 * handler when it is enabled, so don't process those here.
691 * TBD do the same check for MCI_STATUS_EN here?
693 if (!(flags & MCP_UC) &&
694 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
701 if (!(flags & MCP_TIMESTAMP))
704 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
706 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m))
707 if (m.status & MCI_STATUS_ADDRV)
708 m.severity = severity;
711 * Don't get the IP here because it's unlikely to
712 * have anything to do with the actual error location.
714 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
716 else if (mce_usable_address(&m)) {
718 * Although we skipped logging this, we still want
719 * to take action. Add to the pool so the registered
720 * notifiers will see it.
722 if (!mce_gen_pool_add(&m))
727 * Clear state for this bank.
729 mce_wrmsrl(msr_ops.status(i), 0);
733 * Don't clear MCG_STATUS here because it's only defined for
741 EXPORT_SYMBOL_GPL(machine_check_poll);
744 * Do a quick check if any of the events requires a panic.
745 * This decides if we keep the events around or clear them.
747 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
748 struct pt_regs *regs)
753 for (i = 0; i < mca_cfg.banks; i++) {
754 m->status = mce_rdmsrl(msr_ops.status(i));
755 if (m->status & MCI_STATUS_VAL) {
756 __set_bit(i, validp);
757 if (quirk_no_way_out)
758 quirk_no_way_out(i, m, regs);
761 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
770 * Variable to establish order between CPUs while scanning.
771 * Each CPU spins initially until executing is equal its number.
773 static atomic_t mce_executing;
776 * Defines order of CPUs on entry. First CPU becomes Monarch.
778 static atomic_t mce_callin;
781 * Check if a timeout waiting for other CPUs happened.
783 static int mce_timed_out(u64 *t, const char *msg)
786 * The others already did panic for some reason.
787 * Bail out like in a timeout.
788 * rmb() to tell the compiler that system_state
789 * might have been modified by someone else.
792 if (atomic_read(&mce_panicked))
794 if (!mca_cfg.monarch_timeout)
796 if ((s64)*t < SPINUNIT) {
797 if (mca_cfg.tolerant <= 1)
798 mce_panic(msg, NULL, NULL);
804 touch_nmi_watchdog();
809 * The Monarch's reign. The Monarch is the CPU who entered
810 * the machine check handler first. It waits for the others to
811 * raise the exception too and then grades them. When any
812 * error is fatal panic. Only then let the others continue.
814 * The other CPUs entering the MCE handler will be controlled by the
815 * Monarch. They are called Subjects.
817 * This way we prevent any potential data corruption in a unrecoverable case
818 * and also makes sure always all CPU's errors are examined.
820 * Also this detects the case of a machine check event coming from outer
821 * space (not detected by any CPUs) In this case some external agent wants
822 * us to shut down, so panic too.
824 * The other CPUs might still decide to panic if the handler happens
825 * in a unrecoverable place, but in this case the system is in a semi-stable
826 * state and won't corrupt anything by itself. It's ok to let the others
827 * continue for a bit first.
829 * All the spin loops have timeouts; when a timeout happens a CPU
830 * typically elects itself to be Monarch.
832 static void mce_reign(void)
835 struct mce *m = NULL;
836 int global_worst = 0;
841 * This CPU is the Monarch and the other CPUs have run
842 * through their handlers.
843 * Grade the severity of the errors of all the CPUs.
845 for_each_possible_cpu(cpu) {
846 int severity = mce_severity(&per_cpu(mces_seen, cpu),
849 if (severity > global_worst) {
851 global_worst = severity;
852 m = &per_cpu(mces_seen, cpu);
857 * Cannot recover? Panic here then.
858 * This dumps all the mces in the log buffer and stops the
861 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
862 mce_panic("Fatal machine check", m, msg);
865 * For UC somewhere we let the CPU who detects it handle it.
866 * Also must let continue the others, otherwise the handling
867 * CPU could deadlock on a lock.
871 * No machine check event found. Must be some external
872 * source or one CPU is hung. Panic.
874 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
875 mce_panic("Fatal machine check from unknown source", NULL, NULL);
878 * Now clear all the mces_seen so that they don't reappear on
881 for_each_possible_cpu(cpu)
882 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
885 static atomic_t global_nwo;
888 * Start of Monarch synchronization. This waits until all CPUs have
889 * entered the exception handler and then determines if any of them
890 * saw a fatal event that requires panic. Then it executes them
891 * in the entry order.
892 * TBD double check parallel CPU hotunplug
894 static int mce_start(int *no_way_out)
897 int cpus = num_online_cpus();
898 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
903 atomic_add(*no_way_out, &global_nwo);
905 * Rely on the implied barrier below, such that global_nwo
906 * is updated before mce_callin.
908 order = atomic_inc_return(&mce_callin);
913 while (atomic_read(&mce_callin) != cpus) {
914 if (mce_timed_out(&timeout,
915 "Timeout: Not all CPUs entered broadcast exception handler")) {
916 atomic_set(&global_nwo, 0);
923 * mce_callin should be read before global_nwo
929 * Monarch: Starts executing now, the others wait.
931 atomic_set(&mce_executing, 1);
934 * Subject: Now start the scanning loop one by one in
935 * the original callin order.
936 * This way when there are any shared banks it will be
937 * only seen by one CPU before cleared, avoiding duplicates.
939 while (atomic_read(&mce_executing) < order) {
940 if (mce_timed_out(&timeout,
941 "Timeout: Subject CPUs unable to finish machine check processing")) {
942 atomic_set(&global_nwo, 0);
950 * Cache the global no_way_out state.
952 *no_way_out = atomic_read(&global_nwo);
958 * Synchronize between CPUs after main scanning loop.
959 * This invokes the bulk of the Monarch processing.
961 static int mce_end(int order)
964 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
972 * Allow others to run.
974 atomic_inc(&mce_executing);
977 /* CHECKME: Can this race with a parallel hotplug? */
978 int cpus = num_online_cpus();
981 * Monarch: Wait for everyone to go through their scanning
984 while (atomic_read(&mce_executing) <= cpus) {
985 if (mce_timed_out(&timeout,
986 "Timeout: Monarch CPU unable to finish machine check processing"))
996 * Subject: Wait for Monarch to finish.
998 while (atomic_read(&mce_executing) != 0) {
999 if (mce_timed_out(&timeout,
1000 "Timeout: Monarch CPU did not finish machine check processing"))
1006 * Don't reset anything. That's done by the Monarch.
1012 * Reset all global state.
1015 atomic_set(&global_nwo, 0);
1016 atomic_set(&mce_callin, 0);
1020 * Let others run again.
1022 atomic_set(&mce_executing, 0);
1026 static void mce_clear_state(unsigned long *toclear)
1030 for (i = 0; i < mca_cfg.banks; i++) {
1031 if (test_bit(i, toclear))
1032 mce_wrmsrl(msr_ops.status(i), 0);
1036 static int do_memory_failure(struct mce *m)
1038 int flags = MF_ACTION_REQUIRED;
1041 pr_err("Uncorrected hardware memory error in user-access at %llx", m->addr);
1042 if (!(m->mcgstatus & MCG_STATUS_RIPV))
1043 flags |= MF_MUST_KILL;
1044 ret = memory_failure(m->addr >> PAGE_SHIFT, MCE_VECTOR, flags);
1046 pr_err("Memory error not recovered");
1051 * The actual machine check handler. This only handles real
1052 * exceptions when something got corrupted coming in through int 18.
1054 * This is executed in NMI context not subject to normal locking rules. This
1055 * implies that most kernel services cannot be safely used. Don't even
1056 * think about putting a printk in there!
1058 * On Intel systems this is entered on all CPUs in parallel through
1059 * MCE broadcast. However some CPUs might be broken beyond repair,
1060 * so be always careful when synchronizing with others.
1062 void do_machine_check(struct pt_regs *regs, long error_code)
1064 struct mca_config *cfg = &mca_cfg;
1065 struct mce m, *final;
1071 * Establish sequential order between the CPUs entering the machine
1076 * If no_way_out gets set, there is no safe way to recover from this
1077 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1081 * If kill_it gets set, there might be a way to recover from this
1085 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1086 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1087 char *msg = "Unknown";
1090 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1095 /* If this CPU is offline, just bail out. */
1096 if (cpu_is_offline(smp_processor_id())) {
1099 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1100 if (mcgstatus & MCG_STATUS_RIPV) {
1101 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1108 this_cpu_inc(mce_exception_count);
1113 mce_gather_info(&m, regs);
1115 final = this_cpu_ptr(&mces_seen);
1118 memset(valid_banks, 0, sizeof(valid_banks));
1119 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1124 * When no restart IP might need to kill or panic.
1125 * Assume the worst for now, but if we find the
1126 * severity is MCE_AR_SEVERITY we have other options.
1128 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1132 * Check if this MCE is signaled to only this logical processor,
1135 if (m.cpuvendor == X86_VENDOR_INTEL)
1136 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1139 * Go through all banks in exclusion of the other CPUs. This way we
1140 * don't report duplicated events on shared banks because the first one
1141 * to see it will clear it. If this is a Local MCE, then no need to
1142 * perform rendezvous.
1145 order = mce_start(&no_way_out);
1147 for (i = 0; i < cfg->banks; i++) {
1148 __clear_bit(i, toclear);
1149 if (!test_bit(i, valid_banks))
1151 if (!mce_banks[i].ctl)
1158 m.status = mce_rdmsrl(msr_ops.status(i));
1159 if ((m.status & MCI_STATUS_VAL) == 0)
1163 * Non uncorrected or non signaled errors are handled by
1164 * machine_check_poll. Leave them alone, unless this panics.
1166 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1171 * Set taint even when machine check was not enabled.
1173 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1175 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1178 * When machine check was for corrected/deferred handler don't
1179 * touch, unless we're panicing.
1181 if ((severity == MCE_KEEP_SEVERITY ||
1182 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1184 __set_bit(i, toclear);
1185 if (severity == MCE_NO_SEVERITY) {
1187 * Machine check event was not enabled. Clear, but
1193 mce_read_aux(&m, i);
1195 /* assuming valid severity level != 0 */
1196 m.severity = severity;
1200 if (severity > worst) {
1206 /* mce_clear_state will clear *final, save locally for use later */
1210 mce_clear_state(toclear);
1213 * Do most of the synchronization with other CPUs.
1214 * When there's any problem use only local no_way_out state.
1217 if (mce_end(order) < 0)
1218 no_way_out = worst >= MCE_PANIC_SEVERITY;
1221 * Local MCE skipped calling mce_reign()
1222 * If we found a fatal error, we need to panic here.
1224 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1225 mce_panic("Machine check from unknown source",
1230 * If tolerant is at an insane level we drop requests to kill
1231 * processes and continue even when there is no way out.
1233 if (cfg->tolerant == 3)
1235 else if (no_way_out)
1236 mce_panic("Fatal machine check on current CPU", &m, msg);
1239 mce_report_event(regs);
1240 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1244 if (worst != MCE_AR_SEVERITY && !kill_it)
1247 /* Fault was in user mode and we need to take some action */
1248 if ((m.cs & 3) == 3) {
1249 ist_begin_non_atomic(regs);
1252 if (kill_it || do_memory_failure(&m))
1253 force_sig(SIGBUS, current);
1254 local_irq_disable();
1255 ist_end_non_atomic();
1257 if (!fixup_exception(regs, X86_TRAP_MC))
1258 mce_panic("Failed kernel mode recovery", &m, NULL);
1264 EXPORT_SYMBOL_GPL(do_machine_check);
1266 #ifndef CONFIG_MEMORY_FAILURE
1267 int memory_failure(unsigned long pfn, int vector, int flags)
1269 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1270 BUG_ON(flags & MF_ACTION_REQUIRED);
1271 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1272 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1280 * Action optional processing happens here (picking up
1281 * from the list of faulting pages that do_machine_check()
1282 * placed into the genpool).
1284 static void mce_process_work(struct work_struct *dummy)
1286 mce_gen_pool_process();
1289 #ifdef CONFIG_X86_MCE_INTEL
1291 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1292 * @cpu: The CPU on which the event occurred.
1293 * @status: Event status information
1295 * This function should be called by the thermal interrupt after the
1296 * event has been processed and the decision was made to log the event
1299 * The status parameter will be saved to the 'status' field of 'struct mce'
1300 * and historically has been the register value of the
1301 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1303 void mce_log_therm_throt_event(__u64 status)
1308 m.bank = MCE_THERMAL_BANK;
1312 #endif /* CONFIG_X86_MCE_INTEL */
1315 * Periodic polling timer for "silent" machine check errors. If the
1316 * poller finds an MCE, poll 2x faster. When the poller finds no more
1317 * errors, poll 2x slower (up to check_interval seconds).
1319 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1321 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1322 static DEFINE_PER_CPU(struct hrtimer, mce_timer);
1324 static unsigned long mce_adjust_timer_default(unsigned long interval)
1329 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1331 static enum hrtimer_restart __restart_timer(struct hrtimer *timer, unsigned long interval)
1334 return HRTIMER_NORESTART;
1335 hrtimer_forward_now(timer, ns_to_ktime(jiffies_to_nsecs(interval)));
1336 return HRTIMER_RESTART;
1339 static enum hrtimer_restart mce_timer_fn(struct hrtimer *timer)
1343 iv = __this_cpu_read(mce_next_interval);
1345 if (mce_available(this_cpu_ptr(&cpu_info))) {
1346 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1348 if (mce_intel_cmci_poll()) {
1349 iv = mce_adjust_timer(iv);
1355 * Alert userspace if needed. If we logged an MCE, reduce the polling
1356 * interval, otherwise increase the polling interval.
1358 if (mce_notify_irq())
1359 iv = max(iv / 2, (unsigned long) HZ/100);
1361 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1364 __this_cpu_write(mce_next_interval, iv);
1365 return __restart_timer(timer, iv);
1369 * Ensure that the timer is firing in @interval from now.
1371 void mce_timer_kick(unsigned long interval)
1373 struct hrtimer *t = this_cpu_ptr(&mce_timer);
1374 unsigned long iv = __this_cpu_read(mce_next_interval);
1376 __restart_timer(t, interval);
1379 __this_cpu_write(mce_next_interval, interval);
1382 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1383 static void mce_timer_delete_all(void)
1387 for_each_online_cpu(cpu)
1388 hrtimer_cancel(&per_cpu(mce_timer, cpu));
1391 static void mce_do_trigger(struct work_struct *work)
1393 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1396 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1398 static void __mce_notify_work(struct swork_event *event)
1400 /* Not more than two messages every minute */
1401 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1403 /* wake processes polling /dev/mcelog */
1404 wake_up_interruptible(&mce_chrdev_wait);
1407 * There is no risk of missing notifications because
1408 * work_pending is always cleared before the function is
1411 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1412 schedule_work(&mce_trigger_work);
1414 if (__ratelimit(&ratelimit))
1415 pr_info(HW_ERR "Machine check events logged\n");
1418 #ifdef CONFIG_PREEMPT_RT_FULL
1419 static bool notify_work_ready __read_mostly;
1420 static struct swork_event notify_work;
1422 static int mce_notify_work_init(void)
1430 INIT_SWORK(¬ify_work, __mce_notify_work);
1431 notify_work_ready = true;
1435 static void mce_notify_work(void)
1437 if (notify_work_ready)
1438 swork_queue(¬ify_work);
1441 static void mce_notify_work(void)
1443 __mce_notify_work(NULL);
1445 static inline int mce_notify_work_init(void) { return 0; }
1449 * Notify the user(s) about new machine check events.
1450 * Can be called from interrupt context, but not from machine check/NMI
1453 int mce_notify_irq(void)
1455 if (test_and_clear_bit(0, &mce_need_notify)) {
1461 EXPORT_SYMBOL_GPL(mce_notify_irq);
1463 static int __mcheck_cpu_mce_banks_init(void)
1466 u8 num_banks = mca_cfg.banks;
1468 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1472 for (i = 0; i < num_banks; i++) {
1473 struct mce_bank *b = &mce_banks[i];
1482 * Initialize Machine Checks for a CPU.
1484 static int __mcheck_cpu_cap_init(void)
1489 rdmsrl(MSR_IA32_MCG_CAP, cap);
1491 b = cap & MCG_BANKCNT_MASK;
1493 pr_info("CPU supports %d MCE banks\n", b);
1495 if (b > MAX_NR_BANKS) {
1496 pr_warn("Using only %u machine check banks out of %u\n",
1501 /* Don't support asymmetric configurations today */
1502 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1506 int err = __mcheck_cpu_mce_banks_init();
1512 /* Use accurate RIP reporting if available. */
1513 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1514 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1516 if (cap & MCG_SER_P)
1522 static void __mcheck_cpu_init_generic(void)
1524 enum mcp_flags m_fl = 0;
1525 mce_banks_t all_banks;
1528 if (!mca_cfg.bootlog)
1532 * Log the machine checks left over from the previous reset.
1534 bitmap_fill(all_banks, MAX_NR_BANKS);
1535 machine_check_poll(MCP_UC | m_fl, &all_banks);
1537 cr4_set_bits(X86_CR4_MCE);
1539 rdmsrl(MSR_IA32_MCG_CAP, cap);
1540 if (cap & MCG_CTL_P)
1541 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1544 static void __mcheck_cpu_init_clear_banks(void)
1548 for (i = 0; i < mca_cfg.banks; i++) {
1549 struct mce_bank *b = &mce_banks[i];
1553 wrmsrl(msr_ops.ctl(i), b->ctl);
1554 wrmsrl(msr_ops.status(i), 0);
1559 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1560 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1561 * Vol 3B Table 15-20). But this confuses both the code that determines
1562 * whether the machine check occurred in kernel or user mode, and also
1563 * the severity assessment code. Pretend that EIPV was set, and take the
1564 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1566 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1570 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1572 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1573 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1574 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1576 (MCI_STATUS_UC|MCI_STATUS_EN|
1577 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1578 MCI_STATUS_AR|MCACOD_INSTR))
1581 m->mcgstatus |= MCG_STATUS_EIPV;
1586 /* Add per CPU specific workarounds here */
1587 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1589 struct mca_config *cfg = &mca_cfg;
1591 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1592 pr_info("unknown CPU type - not enabling MCE support\n");
1596 /* This should be disabled by the BIOS, but isn't always */
1597 if (c->x86_vendor == X86_VENDOR_AMD) {
1598 if (c->x86 == 15 && cfg->banks > 4) {
1600 * disable GART TBL walk error reporting, which
1601 * trips off incorrectly with the IOMMU & 3ware
1604 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1606 if (c->x86 < 17 && cfg->bootlog < 0) {
1608 * Lots of broken BIOS around that don't clear them
1609 * by default and leave crap in there. Don't log:
1614 * Various K7s with broken bank 0 around. Always disable
1617 if (c->x86 == 6 && cfg->banks > 0)
1618 mce_banks[0].ctl = 0;
1621 * overflow_recov is supported for F15h Models 00h-0fh
1622 * even though we don't have a CPUID bit for it.
1624 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1625 mce_flags.overflow_recov = 1;
1628 * Turn off MC4_MISC thresholding banks on those models since
1629 * they're not supported there.
1631 if (c->x86 == 0x15 &&
1632 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1637 0x00000413, /* MC4_MISC0 */
1638 0xc0000408, /* MC4_MISC1 */
1641 rdmsrl(MSR_K7_HWCR, hwcr);
1643 /* McStatusWrEn has to be set */
1644 need_toggle = !(hwcr & BIT(18));
1647 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1649 /* Clear CntP bit safely */
1650 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1651 msr_clear_bit(msrs[i], 62);
1653 /* restore old settings */
1655 wrmsrl(MSR_K7_HWCR, hwcr);
1659 if (c->x86_vendor == X86_VENDOR_INTEL) {
1661 * SDM documents that on family 6 bank 0 should not be written
1662 * because it aliases to another special BIOS controlled
1664 * But it's not aliased anymore on model 0x1a+
1665 * Don't ignore bank 0 completely because there could be a
1666 * valid event later, merely don't write CTL0.
1669 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1670 mce_banks[0].init = 0;
1673 * All newer Intel systems support MCE broadcasting. Enable
1674 * synchronization with a one second timeout.
1676 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1677 cfg->monarch_timeout < 0)
1678 cfg->monarch_timeout = USEC_PER_SEC;
1681 * There are also broken BIOSes on some Pentium M and
1684 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1687 if (c->x86 == 6 && c->x86_model == 45)
1688 quirk_no_way_out = quirk_sandybridge_ifu;
1690 if (cfg->monarch_timeout < 0)
1691 cfg->monarch_timeout = 0;
1692 if (cfg->bootlog != 0)
1693 cfg->panic_timeout = 30;
1698 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1703 switch (c->x86_vendor) {
1704 case X86_VENDOR_INTEL:
1705 intel_p5_mcheck_init(c);
1708 case X86_VENDOR_CENTAUR:
1709 winchip_mcheck_init(c);
1719 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1721 switch (c->x86_vendor) {
1722 case X86_VENDOR_INTEL:
1723 mce_intel_feature_init(c);
1724 mce_adjust_timer = cmci_intel_adjust_timer;
1727 case X86_VENDOR_AMD: {
1728 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1729 mce_flags.succor = !!cpu_has(c, X86_FEATURE_SUCCOR);
1730 mce_flags.smca = !!cpu_has(c, X86_FEATURE_SMCA);
1733 * Install proper ops for Scalable MCA enabled processors
1735 if (mce_flags.smca) {
1736 msr_ops.ctl = smca_ctl_reg;
1737 msr_ops.status = smca_status_reg;
1738 msr_ops.addr = smca_addr_reg;
1739 msr_ops.misc = smca_misc_reg;
1741 mce_amd_feature_init(c);
1751 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1753 switch (c->x86_vendor) {
1754 case X86_VENDOR_INTEL:
1755 mce_intel_feature_clear(c);
1762 static void mce_start_timer(unsigned int cpu, struct hrtimer *t)
1764 unsigned long iv = check_interval * HZ;
1766 if (mca_cfg.ignore_ce || !iv)
1769 per_cpu(mce_next_interval, cpu) = iv;
1771 hrtimer_start_range_ns(t, ns_to_ktime(jiffies_to_usecs(iv) * 1000ULL),
1772 0, HRTIMER_MODE_REL_PINNED);
1775 static void __mcheck_cpu_init_timer(void)
1777 struct hrtimer *t = this_cpu_ptr(&mce_timer);
1778 unsigned int cpu = smp_processor_id();
1780 hrtimer_init(t, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1781 t->function = mce_timer_fn;
1782 mce_start_timer(cpu, t);
1785 /* Handle unconfigured int18 (should never happen) */
1786 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1788 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1789 smp_processor_id());
1792 /* Call the installed machine check handler for this CPU setup. */
1793 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1794 unexpected_machine_check;
1797 * Called for each booted CPU to set up machine checks.
1798 * Must be called with preempt off:
1800 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1802 if (mca_cfg.disabled)
1805 if (__mcheck_cpu_ancient_init(c))
1808 if (!mce_available(c))
1811 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1812 mca_cfg.disabled = true;
1816 if (mce_gen_pool_init()) {
1817 mca_cfg.disabled = true;
1818 pr_emerg("Couldn't allocate MCE records pool!\n");
1822 machine_check_vector = do_machine_check;
1824 __mcheck_cpu_init_generic();
1825 __mcheck_cpu_init_vendor(c);
1826 __mcheck_cpu_init_clear_banks();
1827 __mcheck_cpu_init_timer();
1831 * Called for each booted CPU to clear some machine checks opt-ins
1833 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1835 if (mca_cfg.disabled)
1838 if (!mce_available(c))
1842 * Possibly to clear general settings generic to x86
1843 * __mcheck_cpu_clear_generic(c);
1845 __mcheck_cpu_clear_vendor(c);
1850 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1853 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1854 static int mce_chrdev_open_count; /* #times opened */
1855 static int mce_chrdev_open_exclu; /* already open exclusive? */
1857 static int mce_chrdev_open(struct inode *inode, struct file *file)
1859 spin_lock(&mce_chrdev_state_lock);
1861 if (mce_chrdev_open_exclu ||
1862 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1863 spin_unlock(&mce_chrdev_state_lock);
1868 if (file->f_flags & O_EXCL)
1869 mce_chrdev_open_exclu = 1;
1870 mce_chrdev_open_count++;
1872 spin_unlock(&mce_chrdev_state_lock);
1874 return nonseekable_open(inode, file);
1877 static int mce_chrdev_release(struct inode *inode, struct file *file)
1879 spin_lock(&mce_chrdev_state_lock);
1881 mce_chrdev_open_count--;
1882 mce_chrdev_open_exclu = 0;
1884 spin_unlock(&mce_chrdev_state_lock);
1889 static void collect_tscs(void *data)
1891 unsigned long *cpu_tsc = (unsigned long *)data;
1893 cpu_tsc[smp_processor_id()] = rdtsc();
1896 static int mce_apei_read_done;
1898 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1899 static int __mce_read_apei(char __user **ubuf, size_t usize)
1905 if (usize < sizeof(struct mce))
1908 rc = apei_read_mce(&m, &record_id);
1909 /* Error or no more MCE record */
1911 mce_apei_read_done = 1;
1913 * When ERST is disabled, mce_chrdev_read() should return
1914 * "no record" instead of "no device."
1921 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1924 * In fact, we should have cleared the record after that has
1925 * been flushed to the disk or sent to network in
1926 * /sbin/mcelog, but we have no interface to support that now,
1927 * so just clear it to avoid duplication.
1929 rc = apei_clear_mce(record_id);
1931 mce_apei_read_done = 1;
1934 *ubuf += sizeof(struct mce);
1939 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1940 size_t usize, loff_t *off)
1942 char __user *buf = ubuf;
1943 unsigned long *cpu_tsc;
1944 unsigned prev, next;
1947 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1951 mutex_lock(&mce_chrdev_read_mutex);
1953 if (!mce_apei_read_done) {
1954 err = __mce_read_apei(&buf, usize);
1955 if (err || buf != ubuf)
1959 next = mce_log_get_idx_check(mcelog.next);
1961 /* Only supports full reads right now */
1963 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1969 for (i = prev; i < next; i++) {
1970 unsigned long start = jiffies;
1971 struct mce *m = &mcelog.entry[i];
1973 while (!m->finished) {
1974 if (time_after_eq(jiffies, start + 2)) {
1975 memset(m, 0, sizeof(*m));
1981 err |= copy_to_user(buf, m, sizeof(*m));
1987 memset(mcelog.entry + prev, 0,
1988 (next - prev) * sizeof(struct mce));
1990 next = cmpxchg(&mcelog.next, prev, 0);
1991 } while (next != prev);
1993 synchronize_sched();
1996 * Collect entries that were still getting written before the
1999 on_each_cpu(collect_tscs, cpu_tsc, 1);
2001 for (i = next; i < MCE_LOG_LEN; i++) {
2002 struct mce *m = &mcelog.entry[i];
2004 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
2005 err |= copy_to_user(buf, m, sizeof(*m));
2008 memset(m, 0, sizeof(*m));
2016 mutex_unlock(&mce_chrdev_read_mutex);
2019 return err ? err : buf - ubuf;
2022 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
2024 poll_wait(file, &mce_chrdev_wait, wait);
2025 if (READ_ONCE(mcelog.next))
2026 return POLLIN | POLLRDNORM;
2027 if (!mce_apei_read_done && apei_check_mce())
2028 return POLLIN | POLLRDNORM;
2032 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
2035 int __user *p = (int __user *)arg;
2037 if (!capable(CAP_SYS_ADMIN))
2041 case MCE_GET_RECORD_LEN:
2042 return put_user(sizeof(struct mce), p);
2043 case MCE_GET_LOG_LEN:
2044 return put_user(MCE_LOG_LEN, p);
2045 case MCE_GETCLEAR_FLAGS: {
2049 flags = mcelog.flags;
2050 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
2052 return put_user(flags, p);
2059 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
2060 size_t usize, loff_t *off);
2062 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
2063 const char __user *ubuf,
2064 size_t usize, loff_t *off))
2068 EXPORT_SYMBOL_GPL(register_mce_write_callback);
2070 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
2071 size_t usize, loff_t *off)
2074 return mce_write(filp, ubuf, usize, off);
2079 static const struct file_operations mce_chrdev_ops = {
2080 .open = mce_chrdev_open,
2081 .release = mce_chrdev_release,
2082 .read = mce_chrdev_read,
2083 .write = mce_chrdev_write,
2084 .poll = mce_chrdev_poll,
2085 .unlocked_ioctl = mce_chrdev_ioctl,
2086 .llseek = no_llseek,
2089 static struct miscdevice mce_chrdev_device = {
2095 static void __mce_disable_bank(void *arg)
2097 int bank = *((int *)arg);
2098 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2099 cmci_disable_bank(bank);
2102 void mce_disable_bank(int bank)
2104 if (bank >= mca_cfg.banks) {
2106 "Ignoring request to disable invalid MCA bank %d.\n",
2110 set_bit(bank, mce_banks_ce_disabled);
2111 on_each_cpu(__mce_disable_bank, &bank, 1);
2115 * mce=off Disables machine check
2116 * mce=no_cmci Disables CMCI
2117 * mce=no_lmce Disables LMCE
2118 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2119 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2120 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2121 * monarchtimeout is how long to wait for other CPUs on machine
2122 * check, or 0 to not wait
2123 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2124 * mce=nobootlog Don't log MCEs from before booting.
2125 * mce=bios_cmci_threshold Don't program the CMCI threshold
2126 * mce=recovery force enable memcpy_mcsafe()
2128 static int __init mcheck_enable(char *str)
2130 struct mca_config *cfg = &mca_cfg;
2138 if (!strcmp(str, "off"))
2139 cfg->disabled = true;
2140 else if (!strcmp(str, "no_cmci"))
2141 cfg->cmci_disabled = true;
2142 else if (!strcmp(str, "no_lmce"))
2143 cfg->lmce_disabled = true;
2144 else if (!strcmp(str, "dont_log_ce"))
2145 cfg->dont_log_ce = true;
2146 else if (!strcmp(str, "ignore_ce"))
2147 cfg->ignore_ce = true;
2148 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2149 cfg->bootlog = (str[0] == 'b');
2150 else if (!strcmp(str, "bios_cmci_threshold"))
2151 cfg->bios_cmci_threshold = true;
2152 else if (!strcmp(str, "recovery"))
2153 cfg->recovery = true;
2154 else if (isdigit(str[0])) {
2155 if (get_option(&str, &cfg->tolerant) == 2)
2156 get_option(&str, &(cfg->monarch_timeout));
2158 pr_info("mce argument %s ignored. Please use /sys\n", str);
2163 __setup("mce", mcheck_enable);
2165 int __init mcheck_init(void)
2167 mcheck_intel_therm_init();
2168 mce_register_decode_chain(&mce_srao_nb);
2169 mcheck_vendor_init_severity();
2171 INIT_WORK(&mce_work, mce_process_work);
2172 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2178 * mce_syscore: PM support
2182 * Disable machine checks on suspend and shutdown. We can't really handle
2185 static void mce_disable_error_reporting(void)
2189 for (i = 0; i < mca_cfg.banks; i++) {
2190 struct mce_bank *b = &mce_banks[i];
2193 wrmsrl(msr_ops.ctl(i), 0);
2198 static void vendor_disable_error_reporting(void)
2201 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2202 * Disabling them for just a single offlined CPU is bad, since it will
2203 * inhibit reporting for all shared resources on the socket like the
2204 * last level cache (LLC), the integrated memory controller (iMC), etc.
2206 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2209 mce_disable_error_reporting();
2212 static int mce_syscore_suspend(void)
2214 vendor_disable_error_reporting();
2218 static void mce_syscore_shutdown(void)
2220 vendor_disable_error_reporting();
2224 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2225 * Only one CPU is active at this time, the others get re-added later using
2228 static void mce_syscore_resume(void)
2230 __mcheck_cpu_init_generic();
2231 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2232 __mcheck_cpu_init_clear_banks();
2235 static struct syscore_ops mce_syscore_ops = {
2236 .suspend = mce_syscore_suspend,
2237 .shutdown = mce_syscore_shutdown,
2238 .resume = mce_syscore_resume,
2242 * mce_device: Sysfs support
2245 static void mce_cpu_restart(void *data)
2247 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2249 __mcheck_cpu_init_generic();
2250 __mcheck_cpu_init_clear_banks();
2251 __mcheck_cpu_init_timer();
2254 /* Reinit MCEs after user configuration changes */
2255 static void mce_restart(void)
2257 mce_timer_delete_all();
2258 on_each_cpu(mce_cpu_restart, NULL, 1);
2261 /* Toggle features for corrected errors */
2262 static void mce_disable_cmci(void *data)
2264 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2269 static void mce_enable_ce(void *all)
2271 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2276 __mcheck_cpu_init_timer();
2279 static struct bus_type mce_subsys = {
2280 .name = "machinecheck",
2281 .dev_name = "machinecheck",
2284 DEFINE_PER_CPU(struct device *, mce_device);
2286 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2288 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2290 return container_of(attr, struct mce_bank, attr);
2293 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2296 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2299 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2300 const char *buf, size_t size)
2304 if (kstrtou64(buf, 0, &new) < 0)
2307 attr_to_bank(attr)->ctl = new;
2314 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2316 strcpy(buf, mce_helper);
2318 return strlen(mce_helper) + 1;
2321 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2322 const char *buf, size_t siz)
2326 strncpy(mce_helper, buf, sizeof(mce_helper));
2327 mce_helper[sizeof(mce_helper)-1] = 0;
2328 p = strchr(mce_helper, '\n');
2333 return strlen(mce_helper) + !!p;
2336 static ssize_t set_ignore_ce(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.ignore_ce ^ !!new) {
2347 /* disable ce features */
2348 mce_timer_delete_all();
2349 on_each_cpu(mce_disable_cmci, NULL, 1);
2350 mca_cfg.ignore_ce = true;
2352 /* enable ce features */
2353 mca_cfg.ignore_ce = false;
2354 on_each_cpu(mce_enable_ce, (void *)1, 1);
2360 static ssize_t set_cmci_disabled(struct device *s,
2361 struct device_attribute *attr,
2362 const char *buf, size_t size)
2366 if (kstrtou64(buf, 0, &new) < 0)
2369 if (mca_cfg.cmci_disabled ^ !!new) {
2372 on_each_cpu(mce_disable_cmci, NULL, 1);
2373 mca_cfg.cmci_disabled = true;
2376 mca_cfg.cmci_disabled = false;
2377 on_each_cpu(mce_enable_ce, NULL, 1);
2383 static ssize_t store_int_with_restart(struct device *s,
2384 struct device_attribute *attr,
2385 const char *buf, size_t size)
2387 ssize_t ret = device_store_int(s, attr, buf, size);
2392 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2393 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2394 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2395 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2397 static struct dev_ext_attribute dev_attr_check_interval = {
2398 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2402 static struct dev_ext_attribute dev_attr_ignore_ce = {
2403 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2407 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2408 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2409 &mca_cfg.cmci_disabled
2412 static struct device_attribute *mce_device_attrs[] = {
2413 &dev_attr_tolerant.attr,
2414 &dev_attr_check_interval.attr,
2416 &dev_attr_monarch_timeout.attr,
2417 &dev_attr_dont_log_ce.attr,
2418 &dev_attr_ignore_ce.attr,
2419 &dev_attr_cmci_disabled.attr,
2423 static cpumask_var_t mce_device_initialized;
2425 static void mce_device_release(struct device *dev)
2430 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2431 static int mce_device_create(unsigned int cpu)
2437 if (!mce_available(&boot_cpu_data))
2440 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2444 dev->bus = &mce_subsys;
2445 dev->release = &mce_device_release;
2447 err = device_register(dev);
2453 for (i = 0; mce_device_attrs[i]; i++) {
2454 err = device_create_file(dev, mce_device_attrs[i]);
2458 for (j = 0; j < mca_cfg.banks; j++) {
2459 err = device_create_file(dev, &mce_banks[j].attr);
2463 cpumask_set_cpu(cpu, mce_device_initialized);
2464 per_cpu(mce_device, cpu) = dev;
2469 device_remove_file(dev, &mce_banks[j].attr);
2472 device_remove_file(dev, mce_device_attrs[i]);
2474 device_unregister(dev);
2479 static void mce_device_remove(unsigned int cpu)
2481 struct device *dev = per_cpu(mce_device, cpu);
2484 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2487 for (i = 0; mce_device_attrs[i]; i++)
2488 device_remove_file(dev, mce_device_attrs[i]);
2490 for (i = 0; i < mca_cfg.banks; i++)
2491 device_remove_file(dev, &mce_banks[i].attr);
2493 device_unregister(dev);
2494 cpumask_clear_cpu(cpu, mce_device_initialized);
2495 per_cpu(mce_device, cpu) = NULL;
2498 /* Make sure there are no machine checks on offlined CPUs. */
2499 static void mce_disable_cpu(void *h)
2501 unsigned long action = *(unsigned long *)h;
2503 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2506 hrtimer_cancel(this_cpu_ptr(&mce_timer));
2508 if (!(action & CPU_TASKS_FROZEN))
2511 vendor_disable_error_reporting();
2514 static void mce_reenable_cpu(void *h)
2516 unsigned long action = *(unsigned long *)h;
2519 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2522 if (!(action & CPU_TASKS_FROZEN))
2524 for (i = 0; i < mca_cfg.banks; i++) {
2525 struct mce_bank *b = &mce_banks[i];
2528 wrmsrl(msr_ops.ctl(i), b->ctl);
2530 __mcheck_cpu_init_timer();
2533 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2535 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2537 unsigned int cpu = (unsigned long)hcpu;
2539 switch (action & ~CPU_TASKS_FROZEN) {
2541 mce_device_create(cpu);
2542 if (threshold_cpu_callback)
2543 threshold_cpu_callback(action, cpu);
2546 if (threshold_cpu_callback)
2547 threshold_cpu_callback(action, cpu);
2548 mce_device_remove(cpu);
2549 mce_intel_hcpu_update(cpu);
2551 /* intentionally ignoring frozen here */
2552 if (!(action & CPU_TASKS_FROZEN))
2555 case CPU_DOWN_PREPARE:
2556 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2558 case CPU_DOWN_FAILED:
2559 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2566 static struct notifier_block mce_cpu_notifier = {
2567 .notifier_call = mce_cpu_callback,
2570 static __init void mce_init_banks(void)
2574 for (i = 0; i < mca_cfg.banks; i++) {
2575 struct mce_bank *b = &mce_banks[i];
2576 struct device_attribute *a = &b->attr;
2578 sysfs_attr_init(&a->attr);
2579 a->attr.name = b->attrname;
2580 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2582 a->attr.mode = 0644;
2583 a->show = show_bank;
2584 a->store = set_bank;
2588 static __init int mcheck_init_device(void)
2593 if (!mce_available(&boot_cpu_data)) {
2598 err = mce_notify_work_init();
2602 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2609 err = subsys_system_register(&mce_subsys, NULL);
2613 cpu_notifier_register_begin();
2614 for_each_online_cpu(i) {
2615 err = mce_device_create(i);
2618 * Register notifier anyway (and do not unreg it) so
2619 * that we don't leave undeleted timers, see notifier
2622 __register_hotcpu_notifier(&mce_cpu_notifier);
2623 cpu_notifier_register_done();
2624 goto err_device_create;
2628 __register_hotcpu_notifier(&mce_cpu_notifier);
2629 cpu_notifier_register_done();
2631 register_syscore_ops(&mce_syscore_ops);
2633 /* register character device /dev/mcelog */
2634 err = misc_register(&mce_chrdev_device);
2641 unregister_syscore_ops(&mce_syscore_ops);
2645 * We didn't keep track of which devices were created above, but
2646 * even if we had, the set of online cpus might have changed.
2647 * Play safe and remove for every possible cpu, since
2648 * mce_device_remove() will do the right thing.
2650 for_each_possible_cpu(i)
2651 mce_device_remove(i);
2654 free_cpumask_var(mce_device_initialized);
2657 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2661 device_initcall_sync(mcheck_init_device);
2664 * Old style boot options parsing. Only for compatibility.
2666 static int __init mcheck_disable(char *str)
2668 mca_cfg.disabled = true;
2671 __setup("nomce", mcheck_disable);
2673 #ifdef CONFIG_DEBUG_FS
2674 struct dentry *mce_get_debugfs_dir(void)
2676 static struct dentry *dmce;
2679 dmce = debugfs_create_dir("mce", NULL);
2684 static void mce_reset(void)
2687 atomic_set(&mce_fake_panicked, 0);
2688 atomic_set(&mce_executing, 0);
2689 atomic_set(&mce_callin, 0);
2690 atomic_set(&global_nwo, 0);
2693 static int fake_panic_get(void *data, u64 *val)
2699 static int fake_panic_set(void *data, u64 val)
2706 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2707 fake_panic_set, "%llu\n");
2709 static int __init mcheck_debugfs_init(void)
2711 struct dentry *dmce, *ffake_panic;
2713 dmce = mce_get_debugfs_dir();
2716 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2724 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2727 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2728 EXPORT_SYMBOL_GPL(mcsafe_key);
2730 static int __init mcheck_late_init(void)
2732 if (mca_cfg.recovery)
2733 static_branch_inc(&mcsafe_key);
2735 mcheck_debugfs_init();
2738 * Flush out everything that has been logged during early boot, now that
2739 * everything has been initialized (workqueues, decoders, ...).
2741 mce_schedule_work();
2745 late_initcall(mcheck_late_init);