2 * Machine check handler.
4 * K8 parts Copyright 2002,2003 Andi Kleen, SuSE Labs.
5 * Rest from unknown author(s).
6 * 2004 Andi Kleen. Rewrote most of it.
7 * Copyright 2008 Intel Corporation
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/thread_info.h>
14 #include <linux/capability.h>
15 #include <linux/miscdevice.h>
16 #include <linux/ratelimit.h>
17 #include <linux/kallsyms.h>
18 #include <linux/rcupdate.h>
19 #include <linux/kobject.h>
20 #include <linux/uaccess.h>
21 #include <linux/kdebug.h>
22 #include <linux/kernel.h>
23 #include <linux/percpu.h>
24 #include <linux/string.h>
25 #include <linux/device.h>
26 #include <linux/syscore_ops.h>
27 #include <linux/delay.h>
28 #include <linux/ctype.h>
29 #include <linux/sched.h>
30 #include <linux/sysfs.h>
31 #include <linux/types.h>
32 #include <linux/slab.h>
33 #include <linux/init.h>
34 #include <linux/kmod.h>
35 #include <linux/poll.h>
36 #include <linux/nmi.h>
37 #include <linux/cpu.h>
38 #include <linux/smp.h>
41 #include <linux/debugfs.h>
42 #include <linux/irq_work.h>
43 #include <linux/export.h>
45 #include <asm/processor.h>
46 #include <asm/traps.h>
47 #include <asm/tlbflush.h>
51 #include "mce-internal.h"
53 static DEFINE_MUTEX(mce_chrdev_read_mutex);
55 #define mce_log_get_idx_check(p) \
57 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
58 !lockdep_is_held(&mce_chrdev_read_mutex), \
59 "suspicious mce_log_get_idx_check() usage"); \
60 smp_load_acquire(&(p)); \
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/mce.h>
66 #define SPINUNIT 100 /* 100ns */
68 DEFINE_PER_CPU(unsigned, mce_exception_count);
70 struct mce_bank *mce_banks __read_mostly;
71 struct mce_vendor_flags mce_flags __read_mostly;
73 struct mca_config mca_cfg __read_mostly = {
77 * 0: always panic on uncorrected errors, log corrected errors
78 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
79 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
80 * 3: never panic or SIGBUS, log all errors (for testing only)
86 /* User mode helper program triggered by machine check event */
87 static unsigned long mce_need_notify;
88 static char mce_helper[128];
89 static char *mce_helper_argv[2] = { mce_helper, NULL };
91 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
93 static DEFINE_PER_CPU(struct mce, mces_seen);
94 static int cpu_missing;
97 * MCA banks polled by the period polling timer for corrected events.
98 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
100 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
101 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
105 * MCA banks controlled through firmware first for corrected errors.
106 * This is a global list of banks for which we won't enable CMCI and we
107 * won't poll. Firmware controls these banks and is responsible for
108 * reporting corrected errors through GHES. Uncorrected/recoverable
109 * errors are still notified through a machine check.
111 mce_banks_t mce_banks_ce_disabled;
113 static struct work_struct mce_work;
114 static struct irq_work mce_irq_work;
116 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
119 * CPU/chipset specific EDAC code can register a notifier call here to print
120 * MCE errors in a human-readable form.
122 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
124 /* Do initial initialization of a struct mce */
125 void mce_setup(struct mce *m)
127 memset(m, 0, sizeof(struct mce));
128 m->cpu = m->extcpu = smp_processor_id();
130 /* We hope get_seconds stays lockless */
131 m->time = get_seconds();
132 m->cpuvendor = boot_cpu_data.x86_vendor;
133 m->cpuid = cpuid_eax(1);
134 m->socketid = cpu_data(m->extcpu).phys_proc_id;
135 m->apicid = cpu_data(m->extcpu).initial_apicid;
136 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
139 DEFINE_PER_CPU(struct mce, injectm);
140 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
143 * Lockless MCE logging infrastructure.
144 * This avoids deadlocks on printk locks without having to break locks. Also
145 * separate MCEs from kernel messages to avoid bogus bug reports.
148 static struct mce_log mcelog = {
149 .signature = MCE_LOG_SIGNATURE,
151 .recordlen = sizeof(struct mce),
154 void mce_log(struct mce *mce)
156 unsigned next, entry;
158 /* Emit the trace record: */
159 trace_mce_record(mce);
161 if (!mce_gen_pool_add(mce))
162 irq_work_queue(&mce_irq_work);
167 entry = mce_log_get_idx_check(mcelog.next);
171 * When the buffer fills up discard new entries.
172 * Assume that the earlier errors are the more
175 if (entry >= MCE_LOG_LEN) {
176 set_bit(MCE_OVERFLOW,
177 (unsigned long *)&mcelog.flags);
180 /* Old left over entry. Skip: */
181 if (mcelog.entry[entry].finished) {
189 if (cmpxchg(&mcelog.next, entry, next) == entry)
192 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
194 mcelog.entry[entry].finished = 1;
198 set_bit(0, &mce_need_notify);
201 void mce_inject_log(struct mce *m)
203 mutex_lock(&mce_chrdev_read_mutex);
205 mutex_unlock(&mce_chrdev_read_mutex);
207 EXPORT_SYMBOL_GPL(mce_inject_log);
209 static struct notifier_block mce_srao_nb;
211 void mce_register_decode_chain(struct notifier_block *nb)
213 /* Ensure SRAO notifier has the highest priority in the decode chain. */
214 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
217 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
219 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
221 void mce_unregister_decode_chain(struct notifier_block *nb)
223 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
225 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
227 static void print_mce(struct mce *m)
231 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
232 m->extcpu, m->mcgstatus, m->bank, m->status);
235 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
236 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
239 if (m->cs == __KERNEL_CS)
240 print_symbol("{%s}", m->ip);
244 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
246 pr_cont("ADDR %llx ", m->addr);
248 pr_cont("MISC %llx ", m->misc);
252 * Note this output is parsed by external tools and old fields
253 * should not be changed.
255 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
256 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
257 cpu_data(m->extcpu).microcode);
260 * Print out human-readable details about the MCE error,
261 * (if the CPU has an implementation for that)
263 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
264 if (ret == NOTIFY_STOP)
267 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
270 #define PANIC_TIMEOUT 5 /* 5 seconds */
272 static atomic_t mce_panicked;
274 static int fake_panic;
275 static atomic_t mce_fake_panicked;
277 /* Panic in progress. Enable interrupts and wait for final IPI */
278 static void wait_for_panic(void)
280 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
284 while (timeout-- > 0)
286 if (panic_timeout == 0)
287 panic_timeout = mca_cfg.panic_timeout;
288 panic("Panicing machine check CPU died");
291 static void mce_panic(const char *msg, struct mce *final, char *exp)
297 * Make sure only one CPU runs in machine check panic
299 if (atomic_inc_return(&mce_panicked) > 1)
306 /* Don't log too much for fake panic */
307 if (atomic_inc_return(&mce_fake_panicked) > 1)
310 /* First print corrected ones that are still unlogged */
311 for (i = 0; i < MCE_LOG_LEN; i++) {
312 struct mce *m = &mcelog.entry[i];
313 if (!(m->status & MCI_STATUS_VAL))
315 if (!(m->status & MCI_STATUS_UC)) {
318 apei_err = apei_write_mce(m);
321 /* Now print uncorrected but with the final one last */
322 for (i = 0; i < MCE_LOG_LEN; i++) {
323 struct mce *m = &mcelog.entry[i];
324 if (!(m->status & MCI_STATUS_VAL))
326 if (!(m->status & MCI_STATUS_UC))
328 if (!final || memcmp(m, final, sizeof(struct mce))) {
331 apei_err = apei_write_mce(m);
337 apei_err = apei_write_mce(final);
340 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
342 pr_emerg(HW_ERR "Machine check: %s\n", exp);
344 if (panic_timeout == 0)
345 panic_timeout = mca_cfg.panic_timeout;
348 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
351 /* Support code for software error injection */
353 static int msr_to_offset(u32 msr)
355 unsigned bank = __this_cpu_read(injectm.bank);
357 if (msr == mca_cfg.rip_msr)
358 return offsetof(struct mce, ip);
359 if (msr == MSR_IA32_MCx_STATUS(bank))
360 return offsetof(struct mce, status);
361 if (msr == MSR_IA32_MCx_ADDR(bank))
362 return offsetof(struct mce, addr);
363 if (msr == MSR_IA32_MCx_MISC(bank))
364 return offsetof(struct mce, misc);
365 if (msr == MSR_IA32_MCG_STATUS)
366 return offsetof(struct mce, mcgstatus);
370 /* MSR access wrappers used for error injection */
371 static u64 mce_rdmsrl(u32 msr)
375 if (__this_cpu_read(injectm.finished)) {
376 int offset = msr_to_offset(msr);
380 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
383 if (rdmsrl_safe(msr, &v)) {
384 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
386 * Return zero in case the access faulted. This should
387 * not happen normally but can happen if the CPU does
388 * something weird, or if the code is buggy.
396 static void mce_wrmsrl(u32 msr, u64 v)
398 if (__this_cpu_read(injectm.finished)) {
399 int offset = msr_to_offset(msr);
402 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
409 * Collect all global (w.r.t. this processor) status about this machine
410 * check into our "mce" struct so that we can use it later to assess
411 * the severity of the problem as we read per-bank specific details.
413 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
417 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
420 * Get the address of the instruction at the time of
421 * the machine check error.
423 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
428 * When in VM86 mode make the cs look like ring 3
429 * always. This is a lie, but it's better than passing
430 * the additional vm86 bit around everywhere.
432 if (v8086_mode(regs))
435 /* Use accurate RIP reporting if available. */
437 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
441 int mce_available(struct cpuinfo_x86 *c)
443 if (mca_cfg.disabled)
445 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
448 static void mce_schedule_work(void)
450 if (!mce_gen_pool_empty() && keventd_up())
451 schedule_work(&mce_work);
454 static void mce_irq_work_cb(struct irq_work *entry)
460 static void mce_report_event(struct pt_regs *regs)
462 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
465 * Triggering the work queue here is just an insurance
466 * policy in case the syscall exit notify handler
467 * doesn't run soon enough or ends up running on the
468 * wrong CPU (can happen when audit sleeps)
474 irq_work_queue(&mce_irq_work);
478 * Check if the address reported by the CPU is in a format we can parse.
479 * It would be possible to add code for most other cases, but all would
480 * be somewhat complicated (e.g. segment offset would require an instruction
481 * parser). So only support physical addresses up to page granuality for now.
483 static int mce_usable_address(struct mce *m)
485 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
488 /* Checks after this one are Intel-specific: */
489 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
492 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
494 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
499 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
502 struct mce *mce = (struct mce *)data;
508 if (mce_usable_address(mce) && (mce->severity == MCE_AO_SEVERITY)) {
509 pfn = mce->addr >> PAGE_SHIFT;
510 memory_failure(pfn, MCE_VECTOR, 0);
515 static struct notifier_block mce_srao_nb = {
516 .notifier_call = srao_decode_notifier,
521 * Read ADDR and MISC registers.
523 static void mce_read_aux(struct mce *m, int i)
525 if (m->status & MCI_STATUS_MISCV)
526 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
527 if (m->status & MCI_STATUS_ADDRV) {
528 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
531 * Mask the reported address by the reported granularity.
533 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
534 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
541 static bool memory_error(struct mce *m)
543 struct cpuinfo_x86 *c = &boot_cpu_data;
545 if (c->x86_vendor == X86_VENDOR_AMD) {
546 /* ErrCodeExt[20:16] */
547 u8 xec = (m->status >> 16) & 0x1f;
549 return (xec == 0x0 || xec == 0x8);
550 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
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 DEFINE_PER_CPU(unsigned, mce_poll_count);
575 * Poll for corrected events or events that happened before reset.
576 * Those are just logged through /dev/mcelog.
578 * This is executed in standard interrupt context.
580 * Note: spec recommends to panic for fatal unsignalled
581 * errors here. However this would be quite problematic --
582 * we would need to reimplement the Monarch handling and
583 * it would mess up the exclusion between exception handler
584 * and poll hander -- * so we skip this for now.
585 * These cases should not happen anyways, or only when the CPU
586 * is already totally * confused. In this case it's likely it will
587 * not fully execute the machine check handler either.
589 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
591 bool error_seen = false;
596 this_cpu_inc(mce_poll_count);
598 mce_gather_info(&m, NULL);
600 for (i = 0; i < mca_cfg.banks; i++) {
601 if (!mce_banks[i].ctl || !test_bit(i, *b))
610 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
611 if (!(m.status & MCI_STATUS_VAL))
616 * Uncorrected or signalled events are handled by the exception
617 * handler when it is enabled, so don't process those here.
619 * TBD do the same check for MCI_STATUS_EN here?
621 if (!(flags & MCP_UC) &&
622 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
629 if (!(flags & MCP_TIMESTAMP))
632 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
634 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m))
635 if (m.status & MCI_STATUS_ADDRV)
636 m.severity = severity;
639 * Don't get the IP here because it's unlikely to
640 * have anything to do with the actual error location.
642 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
644 else if (mce_usable_address(&m)) {
646 * Although we skipped logging this, we still want
647 * to take action. Add to the pool so the registered
648 * notifiers will see it.
650 if (!mce_gen_pool_add(&m))
655 * Clear state for this bank.
657 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
661 * Don't clear MCG_STATUS here because it's only defined for
669 EXPORT_SYMBOL_GPL(machine_check_poll);
672 * Do a quick check if any of the events requires a panic.
673 * This decides if we keep the events around or clear them.
675 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
676 struct pt_regs *regs)
681 for (i = 0; i < mca_cfg.banks; i++) {
682 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
683 if (m->status & MCI_STATUS_VAL) {
684 __set_bit(i, validp);
685 if (quirk_no_way_out)
686 quirk_no_way_out(i, m, regs);
689 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
698 * Variable to establish order between CPUs while scanning.
699 * Each CPU spins initially until executing is equal its number.
701 static atomic_t mce_executing;
704 * Defines order of CPUs on entry. First CPU becomes Monarch.
706 static atomic_t mce_callin;
709 * Check if a timeout waiting for other CPUs happened.
711 static int mce_timed_out(u64 *t, const char *msg)
714 * The others already did panic for some reason.
715 * Bail out like in a timeout.
716 * rmb() to tell the compiler that system_state
717 * might have been modified by someone else.
720 if (atomic_read(&mce_panicked))
722 if (!mca_cfg.monarch_timeout)
724 if ((s64)*t < SPINUNIT) {
725 if (mca_cfg.tolerant <= 1)
726 mce_panic(msg, NULL, NULL);
732 touch_nmi_watchdog();
737 * The Monarch's reign. The Monarch is the CPU who entered
738 * the machine check handler first. It waits for the others to
739 * raise the exception too and then grades them. When any
740 * error is fatal panic. Only then let the others continue.
742 * The other CPUs entering the MCE handler will be controlled by the
743 * Monarch. They are called Subjects.
745 * This way we prevent any potential data corruption in a unrecoverable case
746 * and also makes sure always all CPU's errors are examined.
748 * Also this detects the case of a machine check event coming from outer
749 * space (not detected by any CPUs) In this case some external agent wants
750 * us to shut down, so panic too.
752 * The other CPUs might still decide to panic if the handler happens
753 * in a unrecoverable place, but in this case the system is in a semi-stable
754 * state and won't corrupt anything by itself. It's ok to let the others
755 * continue for a bit first.
757 * All the spin loops have timeouts; when a timeout happens a CPU
758 * typically elects itself to be Monarch.
760 static void mce_reign(void)
763 struct mce *m = NULL;
764 int global_worst = 0;
769 * This CPU is the Monarch and the other CPUs have run
770 * through their handlers.
771 * Grade the severity of the errors of all the CPUs.
773 for_each_possible_cpu(cpu) {
774 int severity = mce_severity(&per_cpu(mces_seen, cpu),
777 if (severity > global_worst) {
779 global_worst = severity;
780 m = &per_cpu(mces_seen, cpu);
785 * Cannot recover? Panic here then.
786 * This dumps all the mces in the log buffer and stops the
789 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
790 mce_panic("Fatal machine check", m, msg);
793 * For UC somewhere we let the CPU who detects it handle it.
794 * Also must let continue the others, otherwise the handling
795 * CPU could deadlock on a lock.
799 * No machine check event found. Must be some external
800 * source or one CPU is hung. Panic.
802 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
803 mce_panic("Fatal machine check from unknown source", NULL, NULL);
806 * Now clear all the mces_seen so that they don't reappear on
809 for_each_possible_cpu(cpu)
810 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
813 static atomic_t global_nwo;
816 * Start of Monarch synchronization. This waits until all CPUs have
817 * entered the exception handler and then determines if any of them
818 * saw a fatal event that requires panic. Then it executes them
819 * in the entry order.
820 * TBD double check parallel CPU hotunplug
822 static int mce_start(int *no_way_out)
825 int cpus = num_online_cpus();
826 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
831 atomic_add(*no_way_out, &global_nwo);
833 * global_nwo should be updated before mce_callin
836 order = atomic_inc_return(&mce_callin);
841 while (atomic_read(&mce_callin) != cpus) {
842 if (mce_timed_out(&timeout,
843 "Timeout: Not all CPUs entered broadcast exception handler")) {
844 atomic_set(&global_nwo, 0);
851 * mce_callin should be read before global_nwo
857 * Monarch: Starts executing now, the others wait.
859 atomic_set(&mce_executing, 1);
862 * Subject: Now start the scanning loop one by one in
863 * the original callin order.
864 * This way when there are any shared banks it will be
865 * only seen by one CPU before cleared, avoiding duplicates.
867 while (atomic_read(&mce_executing) < order) {
868 if (mce_timed_out(&timeout,
869 "Timeout: Subject CPUs unable to finish machine check processing")) {
870 atomic_set(&global_nwo, 0);
878 * Cache the global no_way_out state.
880 *no_way_out = atomic_read(&global_nwo);
886 * Synchronize between CPUs after main scanning loop.
887 * This invokes the bulk of the Monarch processing.
889 static int mce_end(int order)
892 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
900 * Allow others to run.
902 atomic_inc(&mce_executing);
905 /* CHECKME: Can this race with a parallel hotplug? */
906 int cpus = num_online_cpus();
909 * Monarch: Wait for everyone to go through their scanning
912 while (atomic_read(&mce_executing) <= cpus) {
913 if (mce_timed_out(&timeout,
914 "Timeout: Monarch CPU unable to finish machine check processing"))
924 * Subject: Wait for Monarch to finish.
926 while (atomic_read(&mce_executing) != 0) {
927 if (mce_timed_out(&timeout,
928 "Timeout: Monarch CPU did not finish machine check processing"))
934 * Don't reset anything. That's done by the Monarch.
940 * Reset all global state.
943 atomic_set(&global_nwo, 0);
944 atomic_set(&mce_callin, 0);
948 * Let others run again.
950 atomic_set(&mce_executing, 0);
954 static void mce_clear_state(unsigned long *toclear)
958 for (i = 0; i < mca_cfg.banks; i++) {
959 if (test_bit(i, toclear))
960 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
965 * The actual machine check handler. This only handles real
966 * exceptions when something got corrupted coming in through int 18.
968 * This is executed in NMI context not subject to normal locking rules. This
969 * implies that most kernel services cannot be safely used. Don't even
970 * think about putting a printk in there!
972 * On Intel systems this is entered on all CPUs in parallel through
973 * MCE broadcast. However some CPUs might be broken beyond repair,
974 * so be always careful when synchronizing with others.
976 void do_machine_check(struct pt_regs *regs, long error_code)
978 struct mca_config *cfg = &mca_cfg;
979 struct mce m, *final;
984 * Establish sequential order between the CPUs entering the machine
989 * If no_way_out gets set, there is no safe way to recover from this
990 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
994 * If kill_it gets set, there might be a way to recover from this
998 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
999 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1000 char *msg = "Unknown";
1001 u64 recover_paddr = ~0ull;
1002 int flags = MF_ACTION_REQUIRED;
1005 /* If this CPU is offline, just bail out. */
1006 if (cpu_is_offline(smp_processor_id())) {
1009 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1010 if (mcgstatus & MCG_STATUS_RIPV) {
1011 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1018 this_cpu_inc(mce_exception_count);
1023 mce_gather_info(&m, regs);
1025 final = this_cpu_ptr(&mces_seen);
1028 memset(valid_banks, 0, sizeof(valid_banks));
1029 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1034 * When no restart IP might need to kill or panic.
1035 * Assume the worst for now, but if we find the
1036 * severity is MCE_AR_SEVERITY we have other options.
1038 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1042 * Check if this MCE is signaled to only this logical processor
1044 if (m.mcgstatus & MCG_STATUS_LMCES)
1048 * Go through all the banks in exclusion of the other CPUs.
1049 * This way we don't report duplicated events on shared banks
1050 * because the first one to see it will clear it.
1051 * If this is a Local MCE, then no need to perform rendezvous.
1053 order = mce_start(&no_way_out);
1056 for (i = 0; i < cfg->banks; i++) {
1057 __clear_bit(i, toclear);
1058 if (!test_bit(i, valid_banks))
1060 if (!mce_banks[i].ctl)
1067 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1068 if ((m.status & MCI_STATUS_VAL) == 0)
1072 * Non uncorrected or non signaled errors are handled by
1073 * machine_check_poll. Leave them alone, unless this panics.
1075 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1080 * Set taint even when machine check was not enabled.
1082 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1084 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1087 * When machine check was for corrected/deferred handler don't
1088 * touch, unless we're panicing.
1090 if ((severity == MCE_KEEP_SEVERITY ||
1091 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1093 __set_bit(i, toclear);
1094 if (severity == MCE_NO_SEVERITY) {
1096 * Machine check event was not enabled. Clear, but
1102 mce_read_aux(&m, i);
1104 /* assuming valid severity level != 0 */
1105 m.severity = severity;
1109 if (severity > worst) {
1115 /* mce_clear_state will clear *final, save locally for use later */
1119 mce_clear_state(toclear);
1122 * Do most of the synchronization with other CPUs.
1123 * When there's any problem use only local no_way_out state.
1126 if (mce_end(order) < 0)
1127 no_way_out = worst >= MCE_PANIC_SEVERITY;
1130 * Local MCE skipped calling mce_reign()
1131 * If we found a fatal error, we need to panic here.
1133 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1134 mce_panic("Machine check from unknown source",
1139 * At insane "tolerant" levels we take no action. Otherwise
1140 * we only die if we have no other choice. For less serious
1141 * issues we try to recover, or limit damage to the current
1144 if (cfg->tolerant < 3) {
1146 mce_panic("Fatal machine check on current CPU", &m, msg);
1147 if (worst == MCE_AR_SEVERITY) {
1148 recover_paddr = m.addr;
1149 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1150 flags |= MF_MUST_KILL;
1151 } else if (kill_it) {
1152 force_sig(SIGBUS, current);
1157 mce_report_event(regs);
1158 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1162 if (recover_paddr == ~0ull)
1165 pr_err("Uncorrected hardware memory error in user-access at %llx",
1168 * We must call memory_failure() here even if the current process is
1169 * doomed. We still need to mark the page as poisoned and alert any
1170 * other users of the page.
1172 ist_begin_non_atomic(regs);
1174 if (memory_failure(recover_paddr >> PAGE_SHIFT, MCE_VECTOR, flags) < 0) {
1175 pr_err("Memory error not recovered");
1176 force_sig(SIGBUS, current);
1178 local_irq_disable();
1179 ist_end_non_atomic();
1183 EXPORT_SYMBOL_GPL(do_machine_check);
1185 #ifndef CONFIG_MEMORY_FAILURE
1186 int memory_failure(unsigned long pfn, int vector, int flags)
1188 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1189 BUG_ON(flags & MF_ACTION_REQUIRED);
1190 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1191 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1199 * Action optional processing happens here (picking up
1200 * from the list of faulting pages that do_machine_check()
1201 * placed into the genpool).
1203 static void mce_process_work(struct work_struct *dummy)
1205 mce_gen_pool_process();
1208 #ifdef CONFIG_X86_MCE_INTEL
1210 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1211 * @cpu: The CPU on which the event occurred.
1212 * @status: Event status information
1214 * This function should be called by the thermal interrupt after the
1215 * event has been processed and the decision was made to log the event
1218 * The status parameter will be saved to the 'status' field of 'struct mce'
1219 * and historically has been the register value of the
1220 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1222 void mce_log_therm_throt_event(__u64 status)
1227 m.bank = MCE_THERMAL_BANK;
1231 #endif /* CONFIG_X86_MCE_INTEL */
1234 * Periodic polling timer for "silent" machine check errors. If the
1235 * poller finds an MCE, poll 2x faster. When the poller finds no more
1236 * errors, poll 2x slower (up to check_interval seconds).
1238 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1240 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1241 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1243 static unsigned long mce_adjust_timer_default(unsigned long interval)
1248 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1250 static void __restart_timer(struct timer_list *t, unsigned long interval)
1252 unsigned long when = jiffies + interval;
1253 unsigned long flags;
1255 local_irq_save(flags);
1257 if (timer_pending(t)) {
1258 if (time_before(when, t->expires))
1259 mod_timer_pinned(t, when);
1261 t->expires = round_jiffies(when);
1262 add_timer_on(t, smp_processor_id());
1265 local_irq_restore(flags);
1268 static void mce_timer_fn(unsigned long data)
1270 struct timer_list *t = this_cpu_ptr(&mce_timer);
1271 int cpu = smp_processor_id();
1274 WARN_ON(cpu != data);
1276 iv = __this_cpu_read(mce_next_interval);
1278 if (mce_available(this_cpu_ptr(&cpu_info))) {
1279 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1281 if (mce_intel_cmci_poll()) {
1282 iv = mce_adjust_timer(iv);
1288 * Alert userspace if needed. If we logged an MCE, reduce the polling
1289 * interval, otherwise increase the polling interval.
1291 if (mce_notify_irq())
1292 iv = max(iv / 2, (unsigned long) HZ/100);
1294 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1297 __this_cpu_write(mce_next_interval, iv);
1298 __restart_timer(t, iv);
1302 * Ensure that the timer is firing in @interval from now.
1304 void mce_timer_kick(unsigned long interval)
1306 struct timer_list *t = this_cpu_ptr(&mce_timer);
1307 unsigned long iv = __this_cpu_read(mce_next_interval);
1309 __restart_timer(t, interval);
1312 __this_cpu_write(mce_next_interval, interval);
1315 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1316 static void mce_timer_delete_all(void)
1320 for_each_online_cpu(cpu)
1321 del_timer_sync(&per_cpu(mce_timer, cpu));
1324 static void mce_do_trigger(struct work_struct *work)
1326 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1329 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1332 * Notify the user(s) about new machine check events.
1333 * Can be called from interrupt context, but not from machine check/NMI
1336 int mce_notify_irq(void)
1338 /* Not more than two messages every minute */
1339 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1341 if (test_and_clear_bit(0, &mce_need_notify)) {
1342 /* wake processes polling /dev/mcelog */
1343 wake_up_interruptible(&mce_chrdev_wait);
1346 schedule_work(&mce_trigger_work);
1348 if (__ratelimit(&ratelimit))
1349 pr_info(HW_ERR "Machine check events logged\n");
1355 EXPORT_SYMBOL_GPL(mce_notify_irq);
1357 static int __mcheck_cpu_mce_banks_init(void)
1360 u8 num_banks = mca_cfg.banks;
1362 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1366 for (i = 0; i < num_banks; i++) {
1367 struct mce_bank *b = &mce_banks[i];
1376 * Initialize Machine Checks for a CPU.
1378 static int __mcheck_cpu_cap_init(void)
1383 rdmsrl(MSR_IA32_MCG_CAP, cap);
1385 b = cap & MCG_BANKCNT_MASK;
1387 pr_info("CPU supports %d MCE banks\n", b);
1389 if (b > MAX_NR_BANKS) {
1390 pr_warn("Using only %u machine check banks out of %u\n",
1395 /* Don't support asymmetric configurations today */
1396 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1400 int err = __mcheck_cpu_mce_banks_init();
1406 /* Use accurate RIP reporting if available. */
1407 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1408 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1410 if (cap & MCG_SER_P)
1416 static void __mcheck_cpu_init_generic(void)
1418 enum mcp_flags m_fl = 0;
1419 mce_banks_t all_banks;
1423 if (!mca_cfg.bootlog)
1427 * Log the machine checks left over from the previous reset.
1429 bitmap_fill(all_banks, MAX_NR_BANKS);
1430 machine_check_poll(MCP_UC | m_fl, &all_banks);
1432 cr4_set_bits(X86_CR4_MCE);
1434 rdmsrl(MSR_IA32_MCG_CAP, cap);
1435 if (cap & MCG_CTL_P)
1436 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1438 for (i = 0; i < mca_cfg.banks; i++) {
1439 struct mce_bank *b = &mce_banks[i];
1443 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1444 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1449 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1450 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1451 * Vol 3B Table 15-20). But this confuses both the code that determines
1452 * whether the machine check occurred in kernel or user mode, and also
1453 * the severity assessment code. Pretend that EIPV was set, and take the
1454 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1456 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1460 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1462 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1463 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1464 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1466 (MCI_STATUS_UC|MCI_STATUS_EN|
1467 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1468 MCI_STATUS_AR|MCACOD_INSTR))
1471 m->mcgstatus |= MCG_STATUS_EIPV;
1476 /* Add per CPU specific workarounds here */
1477 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1479 struct mca_config *cfg = &mca_cfg;
1481 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1482 pr_info("unknown CPU type - not enabling MCE support\n");
1486 /* This should be disabled by the BIOS, but isn't always */
1487 if (c->x86_vendor == X86_VENDOR_AMD) {
1488 if (c->x86 == 15 && cfg->banks > 4) {
1490 * disable GART TBL walk error reporting, which
1491 * trips off incorrectly with the IOMMU & 3ware
1494 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1496 if (c->x86 <= 17 && cfg->bootlog < 0) {
1498 * Lots of broken BIOS around that don't clear them
1499 * by default and leave crap in there. Don't log:
1504 * Various K7s with broken bank 0 around. Always disable
1507 if (c->x86 == 6 && cfg->banks > 0)
1508 mce_banks[0].ctl = 0;
1511 * overflow_recov is supported for F15h Models 00h-0fh
1512 * even though we don't have a CPUID bit for it.
1514 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1515 mce_flags.overflow_recov = 1;
1518 * Turn off MC4_MISC thresholding banks on those models since
1519 * they're not supported there.
1521 if (c->x86 == 0x15 &&
1522 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1527 0x00000413, /* MC4_MISC0 */
1528 0xc0000408, /* MC4_MISC1 */
1531 rdmsrl(MSR_K7_HWCR, hwcr);
1533 /* McStatusWrEn has to be set */
1534 need_toggle = !(hwcr & BIT(18));
1537 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1539 /* Clear CntP bit safely */
1540 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1541 msr_clear_bit(msrs[i], 62);
1543 /* restore old settings */
1545 wrmsrl(MSR_K7_HWCR, hwcr);
1549 if (c->x86_vendor == X86_VENDOR_INTEL) {
1551 * SDM documents that on family 6 bank 0 should not be written
1552 * because it aliases to another special BIOS controlled
1554 * But it's not aliased anymore on model 0x1a+
1555 * Don't ignore bank 0 completely because there could be a
1556 * valid event later, merely don't write CTL0.
1559 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1560 mce_banks[0].init = 0;
1563 * All newer Intel systems support MCE broadcasting. Enable
1564 * synchronization with a one second timeout.
1566 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1567 cfg->monarch_timeout < 0)
1568 cfg->monarch_timeout = USEC_PER_SEC;
1571 * There are also broken BIOSes on some Pentium M and
1574 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1577 if (c->x86 == 6 && c->x86_model == 45)
1578 quirk_no_way_out = quirk_sandybridge_ifu;
1580 if (cfg->monarch_timeout < 0)
1581 cfg->monarch_timeout = 0;
1582 if (cfg->bootlog != 0)
1583 cfg->panic_timeout = 30;
1588 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1593 switch (c->x86_vendor) {
1594 case X86_VENDOR_INTEL:
1595 intel_p5_mcheck_init(c);
1598 case X86_VENDOR_CENTAUR:
1599 winchip_mcheck_init(c);
1609 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1611 switch (c->x86_vendor) {
1612 case X86_VENDOR_INTEL:
1613 mce_intel_feature_init(c);
1614 mce_adjust_timer = cmci_intel_adjust_timer;
1617 case X86_VENDOR_AMD: {
1618 u32 ebx = cpuid_ebx(0x80000007);
1620 mce_amd_feature_init(c);
1621 mce_flags.overflow_recov = !!(ebx & BIT(0));
1622 mce_flags.succor = !!(ebx & BIT(1));
1623 mce_flags.smca = !!(ebx & BIT(3));
1633 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1635 switch (c->x86_vendor) {
1636 case X86_VENDOR_INTEL:
1637 mce_intel_feature_clear(c);
1644 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1646 unsigned long iv = check_interval * HZ;
1648 if (mca_cfg.ignore_ce || !iv)
1651 per_cpu(mce_next_interval, cpu) = iv;
1653 t->expires = round_jiffies(jiffies + iv);
1654 add_timer_on(t, cpu);
1657 static void __mcheck_cpu_init_timer(void)
1659 struct timer_list *t = this_cpu_ptr(&mce_timer);
1660 unsigned int cpu = smp_processor_id();
1662 setup_timer(t, mce_timer_fn, cpu);
1663 mce_start_timer(cpu, t);
1666 /* Handle unconfigured int18 (should never happen) */
1667 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1669 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1670 smp_processor_id());
1673 /* Call the installed machine check handler for this CPU setup. */
1674 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1675 unexpected_machine_check;
1678 * Called for each booted CPU to set up machine checks.
1679 * Must be called with preempt off:
1681 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1683 if (mca_cfg.disabled)
1686 if (__mcheck_cpu_ancient_init(c))
1689 if (!mce_available(c))
1692 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1693 mca_cfg.disabled = true;
1697 if (mce_gen_pool_init()) {
1698 mca_cfg.disabled = true;
1699 pr_emerg("Couldn't allocate MCE records pool!\n");
1703 machine_check_vector = do_machine_check;
1705 __mcheck_cpu_init_generic();
1706 __mcheck_cpu_init_vendor(c);
1707 __mcheck_cpu_init_timer();
1711 * Called for each booted CPU to clear some machine checks opt-ins
1713 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1715 if (mca_cfg.disabled)
1718 if (!mce_available(c))
1722 * Possibly to clear general settings generic to x86
1723 * __mcheck_cpu_clear_generic(c);
1725 __mcheck_cpu_clear_vendor(c);
1730 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1733 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1734 static int mce_chrdev_open_count; /* #times opened */
1735 static int mce_chrdev_open_exclu; /* already open exclusive? */
1737 static int mce_chrdev_open(struct inode *inode, struct file *file)
1739 spin_lock(&mce_chrdev_state_lock);
1741 if (mce_chrdev_open_exclu ||
1742 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1743 spin_unlock(&mce_chrdev_state_lock);
1748 if (file->f_flags & O_EXCL)
1749 mce_chrdev_open_exclu = 1;
1750 mce_chrdev_open_count++;
1752 spin_unlock(&mce_chrdev_state_lock);
1754 return nonseekable_open(inode, file);
1757 static int mce_chrdev_release(struct inode *inode, struct file *file)
1759 spin_lock(&mce_chrdev_state_lock);
1761 mce_chrdev_open_count--;
1762 mce_chrdev_open_exclu = 0;
1764 spin_unlock(&mce_chrdev_state_lock);
1769 static void collect_tscs(void *data)
1771 unsigned long *cpu_tsc = (unsigned long *)data;
1773 cpu_tsc[smp_processor_id()] = rdtsc();
1776 static int mce_apei_read_done;
1778 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1779 static int __mce_read_apei(char __user **ubuf, size_t usize)
1785 if (usize < sizeof(struct mce))
1788 rc = apei_read_mce(&m, &record_id);
1789 /* Error or no more MCE record */
1791 mce_apei_read_done = 1;
1793 * When ERST is disabled, mce_chrdev_read() should return
1794 * "no record" instead of "no device."
1801 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1804 * In fact, we should have cleared the record after that has
1805 * been flushed to the disk or sent to network in
1806 * /sbin/mcelog, but we have no interface to support that now,
1807 * so just clear it to avoid duplication.
1809 rc = apei_clear_mce(record_id);
1811 mce_apei_read_done = 1;
1814 *ubuf += sizeof(struct mce);
1819 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1820 size_t usize, loff_t *off)
1822 char __user *buf = ubuf;
1823 unsigned long *cpu_tsc;
1824 unsigned prev, next;
1827 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1831 mutex_lock(&mce_chrdev_read_mutex);
1833 if (!mce_apei_read_done) {
1834 err = __mce_read_apei(&buf, usize);
1835 if (err || buf != ubuf)
1839 next = mce_log_get_idx_check(mcelog.next);
1841 /* Only supports full reads right now */
1843 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1849 for (i = prev; i < next; i++) {
1850 unsigned long start = jiffies;
1851 struct mce *m = &mcelog.entry[i];
1853 while (!m->finished) {
1854 if (time_after_eq(jiffies, start + 2)) {
1855 memset(m, 0, sizeof(*m));
1861 err |= copy_to_user(buf, m, sizeof(*m));
1867 memset(mcelog.entry + prev, 0,
1868 (next - prev) * sizeof(struct mce));
1870 next = cmpxchg(&mcelog.next, prev, 0);
1871 } while (next != prev);
1873 synchronize_sched();
1876 * Collect entries that were still getting written before the
1879 on_each_cpu(collect_tscs, cpu_tsc, 1);
1881 for (i = next; i < MCE_LOG_LEN; i++) {
1882 struct mce *m = &mcelog.entry[i];
1884 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1885 err |= copy_to_user(buf, m, sizeof(*m));
1888 memset(m, 0, sizeof(*m));
1896 mutex_unlock(&mce_chrdev_read_mutex);
1899 return err ? err : buf - ubuf;
1902 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1904 poll_wait(file, &mce_chrdev_wait, wait);
1905 if (READ_ONCE(mcelog.next))
1906 return POLLIN | POLLRDNORM;
1907 if (!mce_apei_read_done && apei_check_mce())
1908 return POLLIN | POLLRDNORM;
1912 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1915 int __user *p = (int __user *)arg;
1917 if (!capable(CAP_SYS_ADMIN))
1921 case MCE_GET_RECORD_LEN:
1922 return put_user(sizeof(struct mce), p);
1923 case MCE_GET_LOG_LEN:
1924 return put_user(MCE_LOG_LEN, p);
1925 case MCE_GETCLEAR_FLAGS: {
1929 flags = mcelog.flags;
1930 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1932 return put_user(flags, p);
1939 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1940 size_t usize, loff_t *off);
1942 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1943 const char __user *ubuf,
1944 size_t usize, loff_t *off))
1948 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1950 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1951 size_t usize, loff_t *off)
1954 return mce_write(filp, ubuf, usize, off);
1959 static const struct file_operations mce_chrdev_ops = {
1960 .open = mce_chrdev_open,
1961 .release = mce_chrdev_release,
1962 .read = mce_chrdev_read,
1963 .write = mce_chrdev_write,
1964 .poll = mce_chrdev_poll,
1965 .unlocked_ioctl = mce_chrdev_ioctl,
1966 .llseek = no_llseek,
1969 static struct miscdevice mce_chrdev_device = {
1975 static void __mce_disable_bank(void *arg)
1977 int bank = *((int *)arg);
1978 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1979 cmci_disable_bank(bank);
1982 void mce_disable_bank(int bank)
1984 if (bank >= mca_cfg.banks) {
1986 "Ignoring request to disable invalid MCA bank %d.\n",
1990 set_bit(bank, mce_banks_ce_disabled);
1991 on_each_cpu(__mce_disable_bank, &bank, 1);
1995 * mce=off Disables machine check
1996 * mce=no_cmci Disables CMCI
1997 * mce=no_lmce Disables LMCE
1998 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1999 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2000 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2001 * monarchtimeout is how long to wait for other CPUs on machine
2002 * check, or 0 to not wait
2003 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2004 * mce=nobootlog Don't log MCEs from before booting.
2005 * mce=bios_cmci_threshold Don't program the CMCI threshold
2007 static int __init mcheck_enable(char *str)
2009 struct mca_config *cfg = &mca_cfg;
2017 if (!strcmp(str, "off"))
2018 cfg->disabled = true;
2019 else if (!strcmp(str, "no_cmci"))
2020 cfg->cmci_disabled = true;
2021 else if (!strcmp(str, "no_lmce"))
2022 cfg->lmce_disabled = true;
2023 else if (!strcmp(str, "dont_log_ce"))
2024 cfg->dont_log_ce = true;
2025 else if (!strcmp(str, "ignore_ce"))
2026 cfg->ignore_ce = true;
2027 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2028 cfg->bootlog = (str[0] == 'b');
2029 else if (!strcmp(str, "bios_cmci_threshold"))
2030 cfg->bios_cmci_threshold = true;
2031 else if (isdigit(str[0])) {
2032 if (get_option(&str, &cfg->tolerant) == 2)
2033 get_option(&str, &(cfg->monarch_timeout));
2035 pr_info("mce argument %s ignored. Please use /sys\n", str);
2040 __setup("mce", mcheck_enable);
2042 int __init mcheck_init(void)
2044 mcheck_intel_therm_init();
2045 mce_register_decode_chain(&mce_srao_nb);
2046 mcheck_vendor_init_severity();
2048 INIT_WORK(&mce_work, mce_process_work);
2049 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2055 * mce_syscore: PM support
2059 * Disable machine checks on suspend and shutdown. We can't really handle
2062 static void mce_disable_error_reporting(void)
2066 for (i = 0; i < mca_cfg.banks; i++) {
2067 struct mce_bank *b = &mce_banks[i];
2070 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2075 static void vendor_disable_error_reporting(void)
2078 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2079 * Disabling them for just a single offlined CPU is bad, since it will
2080 * inhibit reporting for all shared resources on the socket like the
2081 * last level cache (LLC), the integrated memory controller (iMC), etc.
2083 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2086 mce_disable_error_reporting();
2089 static int mce_syscore_suspend(void)
2091 vendor_disable_error_reporting();
2095 static void mce_syscore_shutdown(void)
2097 vendor_disable_error_reporting();
2101 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2102 * Only one CPU is active at this time, the others get re-added later using
2105 static void mce_syscore_resume(void)
2107 __mcheck_cpu_init_generic();
2108 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2111 static struct syscore_ops mce_syscore_ops = {
2112 .suspend = mce_syscore_suspend,
2113 .shutdown = mce_syscore_shutdown,
2114 .resume = mce_syscore_resume,
2118 * mce_device: Sysfs support
2121 static void mce_cpu_restart(void *data)
2123 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2125 __mcheck_cpu_init_generic();
2126 __mcheck_cpu_init_timer();
2129 /* Reinit MCEs after user configuration changes */
2130 static void mce_restart(void)
2132 mce_timer_delete_all();
2133 on_each_cpu(mce_cpu_restart, NULL, 1);
2136 /* Toggle features for corrected errors */
2137 static void mce_disable_cmci(void *data)
2139 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2144 static void mce_enable_ce(void *all)
2146 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2151 __mcheck_cpu_init_timer();
2154 static struct bus_type mce_subsys = {
2155 .name = "machinecheck",
2156 .dev_name = "machinecheck",
2159 DEFINE_PER_CPU(struct device *, mce_device);
2161 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2163 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2165 return container_of(attr, struct mce_bank, attr);
2168 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2171 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2174 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2175 const char *buf, size_t size)
2179 if (kstrtou64(buf, 0, &new) < 0)
2182 attr_to_bank(attr)->ctl = new;
2189 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2191 strcpy(buf, mce_helper);
2193 return strlen(mce_helper) + 1;
2196 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2197 const char *buf, size_t siz)
2201 strncpy(mce_helper, buf, sizeof(mce_helper));
2202 mce_helper[sizeof(mce_helper)-1] = 0;
2203 p = strchr(mce_helper, '\n');
2208 return strlen(mce_helper) + !!p;
2211 static ssize_t set_ignore_ce(struct device *s,
2212 struct device_attribute *attr,
2213 const char *buf, size_t size)
2217 if (kstrtou64(buf, 0, &new) < 0)
2220 if (mca_cfg.ignore_ce ^ !!new) {
2222 /* disable ce features */
2223 mce_timer_delete_all();
2224 on_each_cpu(mce_disable_cmci, NULL, 1);
2225 mca_cfg.ignore_ce = true;
2227 /* enable ce features */
2228 mca_cfg.ignore_ce = false;
2229 on_each_cpu(mce_enable_ce, (void *)1, 1);
2235 static ssize_t set_cmci_disabled(struct device *s,
2236 struct device_attribute *attr,
2237 const char *buf, size_t size)
2241 if (kstrtou64(buf, 0, &new) < 0)
2244 if (mca_cfg.cmci_disabled ^ !!new) {
2247 on_each_cpu(mce_disable_cmci, NULL, 1);
2248 mca_cfg.cmci_disabled = true;
2251 mca_cfg.cmci_disabled = false;
2252 on_each_cpu(mce_enable_ce, NULL, 1);
2258 static ssize_t store_int_with_restart(struct device *s,
2259 struct device_attribute *attr,
2260 const char *buf, size_t size)
2262 ssize_t ret = device_store_int(s, attr, buf, size);
2267 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2268 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2269 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2270 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2272 static struct dev_ext_attribute dev_attr_check_interval = {
2273 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2277 static struct dev_ext_attribute dev_attr_ignore_ce = {
2278 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2282 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2283 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2284 &mca_cfg.cmci_disabled
2287 static struct device_attribute *mce_device_attrs[] = {
2288 &dev_attr_tolerant.attr,
2289 &dev_attr_check_interval.attr,
2291 &dev_attr_monarch_timeout.attr,
2292 &dev_attr_dont_log_ce.attr,
2293 &dev_attr_ignore_ce.attr,
2294 &dev_attr_cmci_disabled.attr,
2298 static cpumask_var_t mce_device_initialized;
2300 static void mce_device_release(struct device *dev)
2305 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2306 static int mce_device_create(unsigned int cpu)
2312 if (!mce_available(&boot_cpu_data))
2315 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2319 dev->bus = &mce_subsys;
2320 dev->release = &mce_device_release;
2322 err = device_register(dev);
2328 for (i = 0; mce_device_attrs[i]; i++) {
2329 err = device_create_file(dev, mce_device_attrs[i]);
2333 for (j = 0; j < mca_cfg.banks; j++) {
2334 err = device_create_file(dev, &mce_banks[j].attr);
2338 cpumask_set_cpu(cpu, mce_device_initialized);
2339 per_cpu(mce_device, cpu) = dev;
2344 device_remove_file(dev, &mce_banks[j].attr);
2347 device_remove_file(dev, mce_device_attrs[i]);
2349 device_unregister(dev);
2354 static void mce_device_remove(unsigned int cpu)
2356 struct device *dev = per_cpu(mce_device, cpu);
2359 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2362 for (i = 0; mce_device_attrs[i]; i++)
2363 device_remove_file(dev, mce_device_attrs[i]);
2365 for (i = 0; i < mca_cfg.banks; i++)
2366 device_remove_file(dev, &mce_banks[i].attr);
2368 device_unregister(dev);
2369 cpumask_clear_cpu(cpu, mce_device_initialized);
2370 per_cpu(mce_device, cpu) = NULL;
2373 /* Make sure there are no machine checks on offlined CPUs. */
2374 static void mce_disable_cpu(void *h)
2376 unsigned long action = *(unsigned long *)h;
2378 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2381 if (!(action & CPU_TASKS_FROZEN))
2384 vendor_disable_error_reporting();
2387 static void mce_reenable_cpu(void *h)
2389 unsigned long action = *(unsigned long *)h;
2392 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2395 if (!(action & CPU_TASKS_FROZEN))
2397 for (i = 0; i < mca_cfg.banks; i++) {
2398 struct mce_bank *b = &mce_banks[i];
2401 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2405 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2407 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2409 unsigned int cpu = (unsigned long)hcpu;
2410 struct timer_list *t = &per_cpu(mce_timer, cpu);
2412 switch (action & ~CPU_TASKS_FROZEN) {
2414 mce_device_create(cpu);
2415 if (threshold_cpu_callback)
2416 threshold_cpu_callback(action, cpu);
2419 if (threshold_cpu_callback)
2420 threshold_cpu_callback(action, cpu);
2421 mce_device_remove(cpu);
2422 mce_intel_hcpu_update(cpu);
2424 /* intentionally ignoring frozen here */
2425 if (!(action & CPU_TASKS_FROZEN))
2428 case CPU_DOWN_PREPARE:
2429 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2432 case CPU_DOWN_FAILED:
2433 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2434 mce_start_timer(cpu, t);
2441 static struct notifier_block mce_cpu_notifier = {
2442 .notifier_call = mce_cpu_callback,
2445 static __init void mce_init_banks(void)
2449 for (i = 0; i < mca_cfg.banks; i++) {
2450 struct mce_bank *b = &mce_banks[i];
2451 struct device_attribute *a = &b->attr;
2453 sysfs_attr_init(&a->attr);
2454 a->attr.name = b->attrname;
2455 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2457 a->attr.mode = 0644;
2458 a->show = show_bank;
2459 a->store = set_bank;
2463 static __init int mcheck_init_device(void)
2468 if (!mce_available(&boot_cpu_data)) {
2473 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2480 err = subsys_system_register(&mce_subsys, NULL);
2484 cpu_notifier_register_begin();
2485 for_each_online_cpu(i) {
2486 err = mce_device_create(i);
2489 * Register notifier anyway (and do not unreg it) so
2490 * that we don't leave undeleted timers, see notifier
2493 __register_hotcpu_notifier(&mce_cpu_notifier);
2494 cpu_notifier_register_done();
2495 goto err_device_create;
2499 __register_hotcpu_notifier(&mce_cpu_notifier);
2500 cpu_notifier_register_done();
2502 register_syscore_ops(&mce_syscore_ops);
2504 /* register character device /dev/mcelog */
2505 err = misc_register(&mce_chrdev_device);
2512 unregister_syscore_ops(&mce_syscore_ops);
2516 * We didn't keep track of which devices were created above, but
2517 * even if we had, the set of online cpus might have changed.
2518 * Play safe and remove for every possible cpu, since
2519 * mce_device_remove() will do the right thing.
2521 for_each_possible_cpu(i)
2522 mce_device_remove(i);
2525 free_cpumask_var(mce_device_initialized);
2528 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2532 device_initcall_sync(mcheck_init_device);
2535 * Old style boot options parsing. Only for compatibility.
2537 static int __init mcheck_disable(char *str)
2539 mca_cfg.disabled = true;
2542 __setup("nomce", mcheck_disable);
2544 #ifdef CONFIG_DEBUG_FS
2545 struct dentry *mce_get_debugfs_dir(void)
2547 static struct dentry *dmce;
2550 dmce = debugfs_create_dir("mce", NULL);
2555 static void mce_reset(void)
2558 atomic_set(&mce_fake_panicked, 0);
2559 atomic_set(&mce_executing, 0);
2560 atomic_set(&mce_callin, 0);
2561 atomic_set(&global_nwo, 0);
2564 static int fake_panic_get(void *data, u64 *val)
2570 static int fake_panic_set(void *data, u64 val)
2577 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2578 fake_panic_set, "%llu\n");
2580 static int __init mcheck_debugfs_init(void)
2582 struct dentry *dmce, *ffake_panic;
2584 dmce = mce_get_debugfs_dir();
2587 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2595 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2598 static int __init mcheck_late_init(void)
2600 mcheck_debugfs_init();
2603 * Flush out everything that has been logged during early boot, now that
2604 * everything has been initialized (workqueues, decoders, ...).
2606 mce_schedule_work();
2610 late_initcall(mcheck_late_init);