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/work-simple.h>
47 #include <asm/processor.h>
48 #include <asm/traps.h>
49 #include <asm/tlbflush.h>
53 #include "mce-internal.h"
55 static DEFINE_MUTEX(mce_chrdev_read_mutex);
57 #define rcu_dereference_check_mce(p) \
58 rcu_dereference_index_check((p), \
59 rcu_read_lock_sched_held() || \
60 lockdep_is_held(&mce_chrdev_read_mutex))
62 #define CREATE_TRACE_POINTS
63 #include <trace/events/mce.h>
65 #define SPINUNIT 100 /* 100ns */
67 DEFINE_PER_CPU(unsigned, mce_exception_count);
69 struct mce_bank *mce_banks __read_mostly;
70 struct mce_vendor_flags mce_flags __read_mostly;
72 struct mca_config mca_cfg __read_mostly = {
76 * 0: always panic on uncorrected errors, log corrected errors
77 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
78 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
79 * 3: never panic or SIGBUS, log all errors (for testing only)
85 /* User mode helper program triggered by machine check event */
86 static unsigned long mce_need_notify;
87 static char mce_helper[128];
88 static char *mce_helper_argv[2] = { mce_helper, NULL };
90 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
92 static DEFINE_PER_CPU(struct mce, mces_seen);
93 static int cpu_missing;
96 * MCA banks polled by the period polling timer for corrected events.
97 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
99 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
100 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
104 * MCA banks controlled through firmware first for corrected errors.
105 * This is a global list of banks for which we won't enable CMCI and we
106 * won't poll. Firmware controls these banks and is responsible for
107 * reporting corrected errors through GHES. Uncorrected/recoverable
108 * errors are still notified through a machine check.
110 mce_banks_t mce_banks_ce_disabled;
112 static DEFINE_PER_CPU(struct work_struct, mce_work);
114 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
117 * CPU/chipset specific EDAC code can register a notifier call here to print
118 * MCE errors in a human-readable form.
120 static ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
122 /* Do initial initialization of a struct mce */
123 void mce_setup(struct mce *m)
125 memset(m, 0, sizeof(struct mce));
126 m->cpu = m->extcpu = smp_processor_id();
128 /* We hope get_seconds stays lockless */
129 m->time = get_seconds();
130 m->cpuvendor = boot_cpu_data.x86_vendor;
131 m->cpuid = cpuid_eax(1);
132 m->socketid = cpu_data(m->extcpu).phys_proc_id;
133 m->apicid = cpu_data(m->extcpu).initial_apicid;
134 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
137 DEFINE_PER_CPU(struct mce, injectm);
138 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
141 * Lockless MCE logging infrastructure.
142 * This avoids deadlocks on printk locks without having to break locks. Also
143 * separate MCEs from kernel messages to avoid bogus bug reports.
146 static struct mce_log mcelog = {
147 .signature = MCE_LOG_SIGNATURE,
149 .recordlen = sizeof(struct mce),
152 void mce_log(struct mce *mce)
154 unsigned next, entry;
156 /* Emit the trace record: */
157 trace_mce_record(mce);
159 atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, mce);
164 entry = rcu_dereference_check_mce(mcelog.next);
168 * When the buffer fills up discard new entries.
169 * Assume that the earlier errors are the more
172 if (entry >= MCE_LOG_LEN) {
173 set_bit(MCE_OVERFLOW,
174 (unsigned long *)&mcelog.flags);
177 /* Old left over entry. Skip: */
178 if (mcelog.entry[entry].finished) {
186 if (cmpxchg(&mcelog.next, entry, next) == entry)
189 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
191 mcelog.entry[entry].finished = 1;
195 set_bit(0, &mce_need_notify);
198 static void drain_mcelog_buffer(void)
200 unsigned int next, i, prev = 0;
202 next = ACCESS_ONCE(mcelog.next);
207 /* drain what was logged during boot */
208 for (i = prev; i < next; i++) {
209 unsigned long start = jiffies;
210 unsigned retries = 1;
212 m = &mcelog.entry[i];
214 while (!m->finished) {
215 if (time_after_eq(jiffies, start + 2*retries))
220 if (!m->finished && retries >= 4) {
221 pr_err("skipping error being logged currently!\n");
226 atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
229 memset(mcelog.entry + prev, 0, (next - prev) * sizeof(*m));
231 next = cmpxchg(&mcelog.next, prev, 0);
232 } while (next != prev);
236 void mce_register_decode_chain(struct notifier_block *nb)
238 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
239 drain_mcelog_buffer();
241 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
243 void mce_unregister_decode_chain(struct notifier_block *nb)
245 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
247 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
249 static void print_mce(struct mce *m)
253 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
254 m->extcpu, m->mcgstatus, m->bank, m->status);
257 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
258 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
261 if (m->cs == __KERNEL_CS)
262 print_symbol("{%s}", m->ip);
266 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
268 pr_cont("ADDR %llx ", m->addr);
270 pr_cont("MISC %llx ", m->misc);
274 * Note this output is parsed by external tools and old fields
275 * should not be changed.
277 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
278 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
279 cpu_data(m->extcpu).microcode);
282 * Print out human-readable details about the MCE error,
283 * (if the CPU has an implementation for that)
285 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
286 if (ret == NOTIFY_STOP)
289 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
292 #define PANIC_TIMEOUT 5 /* 5 seconds */
294 static atomic_t mce_panicked;
296 static int fake_panic;
297 static atomic_t mce_fake_panicked;
299 /* Panic in progress. Enable interrupts and wait for final IPI */
300 static void wait_for_panic(void)
302 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
306 while (timeout-- > 0)
308 if (panic_timeout == 0)
309 panic_timeout = mca_cfg.panic_timeout;
310 panic("Panicing machine check CPU died");
313 static void mce_panic(const char *msg, struct mce *final, char *exp)
319 * Make sure only one CPU runs in machine check panic
321 if (atomic_inc_return(&mce_panicked) > 1)
328 /* Don't log too much for fake panic */
329 if (atomic_inc_return(&mce_fake_panicked) > 1)
332 /* First print corrected ones that are still unlogged */
333 for (i = 0; i < MCE_LOG_LEN; i++) {
334 struct mce *m = &mcelog.entry[i];
335 if (!(m->status & MCI_STATUS_VAL))
337 if (!(m->status & MCI_STATUS_UC)) {
340 apei_err = apei_write_mce(m);
343 /* Now print uncorrected but with the final one last */
344 for (i = 0; i < MCE_LOG_LEN; i++) {
345 struct mce *m = &mcelog.entry[i];
346 if (!(m->status & MCI_STATUS_VAL))
348 if (!(m->status & MCI_STATUS_UC))
350 if (!final || memcmp(m, final, sizeof(struct mce))) {
353 apei_err = apei_write_mce(m);
359 apei_err = apei_write_mce(final);
362 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
364 pr_emerg(HW_ERR "Machine check: %s\n", exp);
366 if (panic_timeout == 0)
367 panic_timeout = mca_cfg.panic_timeout;
370 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
373 /* Support code for software error injection */
375 static int msr_to_offset(u32 msr)
377 unsigned bank = __this_cpu_read(injectm.bank);
379 if (msr == mca_cfg.rip_msr)
380 return offsetof(struct mce, ip);
381 if (msr == MSR_IA32_MCx_STATUS(bank))
382 return offsetof(struct mce, status);
383 if (msr == MSR_IA32_MCx_ADDR(bank))
384 return offsetof(struct mce, addr);
385 if (msr == MSR_IA32_MCx_MISC(bank))
386 return offsetof(struct mce, misc);
387 if (msr == MSR_IA32_MCG_STATUS)
388 return offsetof(struct mce, mcgstatus);
392 /* MSR access wrappers used for error injection */
393 static u64 mce_rdmsrl(u32 msr)
397 if (__this_cpu_read(injectm.finished)) {
398 int offset = msr_to_offset(msr);
402 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
405 if (rdmsrl_safe(msr, &v)) {
406 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
408 * Return zero in case the access faulted. This should
409 * not happen normally but can happen if the CPU does
410 * something weird, or if the code is buggy.
418 static void mce_wrmsrl(u32 msr, u64 v)
420 if (__this_cpu_read(injectm.finished)) {
421 int offset = msr_to_offset(msr);
424 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
431 * Collect all global (w.r.t. this processor) status about this machine
432 * check into our "mce" struct so that we can use it later to assess
433 * the severity of the problem as we read per-bank specific details.
435 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
439 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
442 * Get the address of the instruction at the time of
443 * the machine check error.
445 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
450 * When in VM86 mode make the cs look like ring 3
451 * always. This is a lie, but it's better than passing
452 * the additional vm86 bit around everywhere.
454 if (v8086_mode(regs))
457 /* Use accurate RIP reporting if available. */
459 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
464 * Simple lockless ring to communicate PFNs from the exception handler with the
465 * process context work function. This is vastly simplified because there's
466 * only a single reader and a single writer.
468 #define MCE_RING_SIZE 16 /* we use one entry less */
471 unsigned short start;
473 unsigned long ring[MCE_RING_SIZE];
475 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
477 /* Runs with CPU affinity in workqueue */
478 static int mce_ring_empty(void)
480 struct mce_ring *r = this_cpu_ptr(&mce_ring);
482 return r->start == r->end;
485 static int mce_ring_get(unsigned long *pfn)
492 r = this_cpu_ptr(&mce_ring);
493 if (r->start == r->end)
495 *pfn = r->ring[r->start];
496 r->start = (r->start + 1) % MCE_RING_SIZE;
503 /* Always runs in MCE context with preempt off */
504 static int mce_ring_add(unsigned long pfn)
506 struct mce_ring *r = this_cpu_ptr(&mce_ring);
509 next = (r->end + 1) % MCE_RING_SIZE;
510 if (next == r->start)
512 r->ring[r->end] = pfn;
518 int mce_available(struct cpuinfo_x86 *c)
520 if (mca_cfg.disabled)
522 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
525 static void mce_schedule_work(void)
527 if (!mce_ring_empty())
528 schedule_work(this_cpu_ptr(&mce_work));
531 static DEFINE_PER_CPU(struct irq_work, mce_irq_work);
533 static void mce_irq_work_cb(struct irq_work *entry)
539 static void mce_report_event(struct pt_regs *regs)
541 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
544 * Triggering the work queue here is just an insurance
545 * policy in case the syscall exit notify handler
546 * doesn't run soon enough or ends up running on the
547 * wrong CPU (can happen when audit sleeps)
553 irq_work_queue(this_cpu_ptr(&mce_irq_work));
557 * Read ADDR and MISC registers.
559 static void mce_read_aux(struct mce *m, int i)
561 if (m->status & MCI_STATUS_MISCV)
562 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
563 if (m->status & MCI_STATUS_ADDRV) {
564 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
567 * Mask the reported address by the reported granularity.
569 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
570 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
577 static bool memory_error(struct mce *m)
579 struct cpuinfo_x86 *c = &boot_cpu_data;
581 if (c->x86_vendor == X86_VENDOR_AMD) {
586 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
588 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
590 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
591 * indicating a memory error. Bit 8 is used for indicating a
592 * cache hierarchy error. The combination of bit 2 and bit 3
593 * is used for indicating a `generic' cache hierarchy error
594 * But we can't just blindly check the above bits, because if
595 * bit 11 is set, then it is a bus/interconnect error - and
596 * either way the above bits just gives more detail on what
597 * bus/interconnect error happened. Note that bit 12 can be
598 * ignored, as it's the "filter" bit.
600 return (m->status & 0xef80) == BIT(7) ||
601 (m->status & 0xef00) == BIT(8) ||
602 (m->status & 0xeffc) == 0xc;
608 DEFINE_PER_CPU(unsigned, mce_poll_count);
611 * Poll for corrected events or events that happened before reset.
612 * Those are just logged through /dev/mcelog.
614 * This is executed in standard interrupt context.
616 * Note: spec recommends to panic for fatal unsignalled
617 * errors here. However this would be quite problematic --
618 * we would need to reimplement the Monarch handling and
619 * it would mess up the exclusion between exception handler
620 * and poll hander -- * so we skip this for now.
621 * These cases should not happen anyways, or only when the CPU
622 * is already totally * confused. In this case it's likely it will
623 * not fully execute the machine check handler either.
625 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
627 bool error_logged = false;
632 this_cpu_inc(mce_poll_count);
634 mce_gather_info(&m, NULL);
636 for (i = 0; i < mca_cfg.banks; i++) {
637 if (!mce_banks[i].ctl || !test_bit(i, *b))
646 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
647 if (!(m.status & MCI_STATUS_VAL))
652 * Uncorrected or signalled events are handled by the exception
653 * handler when it is enabled, so don't process those here.
655 * TBD do the same check for MCI_STATUS_EN here?
657 if (!(flags & MCP_UC) &&
658 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
663 if (!(flags & MCP_TIMESTAMP))
666 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
669 * In the cases where we don't have a valid address after all,
670 * do not add it into the ring buffer.
672 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m)) {
673 if (m.status & MCI_STATUS_ADDRV) {
674 mce_ring_add(m.addr >> PAGE_SHIFT);
680 * Don't get the IP here because it's unlikely to
681 * have anything to do with the actual error location.
683 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce) {
689 * Clear state for this bank.
691 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
695 * Don't clear MCG_STATUS here because it's only defined for
703 EXPORT_SYMBOL_GPL(machine_check_poll);
706 * Do a quick check if any of the events requires a panic.
707 * This decides if we keep the events around or clear them.
709 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
710 struct pt_regs *regs)
715 for (i = 0; i < mca_cfg.banks; i++) {
716 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
717 if (m->status & MCI_STATUS_VAL) {
718 __set_bit(i, validp);
719 if (quirk_no_way_out)
720 quirk_no_way_out(i, m, regs);
723 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
732 * Variable to establish order between CPUs while scanning.
733 * Each CPU spins initially until executing is equal its number.
735 static atomic_t mce_executing;
738 * Defines order of CPUs on entry. First CPU becomes Monarch.
740 static atomic_t mce_callin;
743 * Check if a timeout waiting for other CPUs happened.
745 static int mce_timed_out(u64 *t, const char *msg)
748 * The others already did panic for some reason.
749 * Bail out like in a timeout.
750 * rmb() to tell the compiler that system_state
751 * might have been modified by someone else.
754 if (atomic_read(&mce_panicked))
756 if (!mca_cfg.monarch_timeout)
758 if ((s64)*t < SPINUNIT) {
759 if (mca_cfg.tolerant <= 1)
760 mce_panic(msg, NULL, NULL);
766 touch_nmi_watchdog();
771 * The Monarch's reign. The Monarch is the CPU who entered
772 * the machine check handler first. It waits for the others to
773 * raise the exception too and then grades them. When any
774 * error is fatal panic. Only then let the others continue.
776 * The other CPUs entering the MCE handler will be controlled by the
777 * Monarch. They are called Subjects.
779 * This way we prevent any potential data corruption in a unrecoverable case
780 * and also makes sure always all CPU's errors are examined.
782 * Also this detects the case of a machine check event coming from outer
783 * space (not detected by any CPUs) In this case some external agent wants
784 * us to shut down, so panic too.
786 * The other CPUs might still decide to panic if the handler happens
787 * in a unrecoverable place, but in this case the system is in a semi-stable
788 * state and won't corrupt anything by itself. It's ok to let the others
789 * continue for a bit first.
791 * All the spin loops have timeouts; when a timeout happens a CPU
792 * typically elects itself to be Monarch.
794 static void mce_reign(void)
797 struct mce *m = NULL;
798 int global_worst = 0;
803 * This CPU is the Monarch and the other CPUs have run
804 * through their handlers.
805 * Grade the severity of the errors of all the CPUs.
807 for_each_possible_cpu(cpu) {
808 int severity = mce_severity(&per_cpu(mces_seen, cpu),
811 if (severity > global_worst) {
813 global_worst = severity;
814 m = &per_cpu(mces_seen, cpu);
819 * Cannot recover? Panic here then.
820 * This dumps all the mces in the log buffer and stops the
823 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
824 mce_panic("Fatal machine check", m, msg);
827 * For UC somewhere we let the CPU who detects it handle it.
828 * Also must let continue the others, otherwise the handling
829 * CPU could deadlock on a lock.
833 * No machine check event found. Must be some external
834 * source or one CPU is hung. Panic.
836 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
837 mce_panic("Fatal machine check from unknown source", NULL, NULL);
840 * Now clear all the mces_seen so that they don't reappear on
843 for_each_possible_cpu(cpu)
844 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
847 static atomic_t global_nwo;
850 * Start of Monarch synchronization. This waits until all CPUs have
851 * entered the exception handler and then determines if any of them
852 * saw a fatal event that requires panic. Then it executes them
853 * in the entry order.
854 * TBD double check parallel CPU hotunplug
856 static int mce_start(int *no_way_out)
859 int cpus = num_online_cpus();
860 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
865 atomic_add(*no_way_out, &global_nwo);
867 * global_nwo should be updated before mce_callin
870 order = atomic_inc_return(&mce_callin);
875 while (atomic_read(&mce_callin) != cpus) {
876 if (mce_timed_out(&timeout,
877 "Timeout: Not all CPUs entered broadcast exception handler")) {
878 atomic_set(&global_nwo, 0);
885 * mce_callin should be read before global_nwo
891 * Monarch: Starts executing now, the others wait.
893 atomic_set(&mce_executing, 1);
896 * Subject: Now start the scanning loop one by one in
897 * the original callin order.
898 * This way when there are any shared banks it will be
899 * only seen by one CPU before cleared, avoiding duplicates.
901 while (atomic_read(&mce_executing) < order) {
902 if (mce_timed_out(&timeout,
903 "Timeout: Subject CPUs unable to finish machine check processing")) {
904 atomic_set(&global_nwo, 0);
912 * Cache the global no_way_out state.
914 *no_way_out = atomic_read(&global_nwo);
920 * Synchronize between CPUs after main scanning loop.
921 * This invokes the bulk of the Monarch processing.
923 static int mce_end(int order)
926 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
934 * Allow others to run.
936 atomic_inc(&mce_executing);
939 /* CHECKME: Can this race with a parallel hotplug? */
940 int cpus = num_online_cpus();
943 * Monarch: Wait for everyone to go through their scanning
946 while (atomic_read(&mce_executing) <= cpus) {
947 if (mce_timed_out(&timeout,
948 "Timeout: Monarch CPU unable to finish machine check processing"))
958 * Subject: Wait for Monarch to finish.
960 while (atomic_read(&mce_executing) != 0) {
961 if (mce_timed_out(&timeout,
962 "Timeout: Monarch CPU did not finish machine check processing"))
968 * Don't reset anything. That's done by the Monarch.
974 * Reset all global state.
977 atomic_set(&global_nwo, 0);
978 atomic_set(&mce_callin, 0);
982 * Let others run again.
984 atomic_set(&mce_executing, 0);
989 * Check if the address reported by the CPU is in a format we can parse.
990 * It would be possible to add code for most other cases, but all would
991 * be somewhat complicated (e.g. segment offset would require an instruction
992 * parser). So only support physical addresses up to page granuality for now.
994 static int mce_usable_address(struct mce *m)
996 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
998 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
1000 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
1005 static void mce_clear_state(unsigned long *toclear)
1009 for (i = 0; i < mca_cfg.banks; i++) {
1010 if (test_bit(i, toclear))
1011 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1016 * The actual machine check handler. This only handles real
1017 * exceptions when something got corrupted coming in through int 18.
1019 * This is executed in NMI context not subject to normal locking rules. This
1020 * implies that most kernel services cannot be safely used. Don't even
1021 * think about putting a printk in there!
1023 * On Intel systems this is entered on all CPUs in parallel through
1024 * MCE broadcast. However some CPUs might be broken beyond repair,
1025 * so be always careful when synchronizing with others.
1027 void do_machine_check(struct pt_regs *regs, long error_code)
1029 struct mca_config *cfg = &mca_cfg;
1030 struct mce m, *final;
1031 enum ctx_state prev_state;
1036 * Establish sequential order between the CPUs entering the machine
1041 * If no_way_out gets set, there is no safe way to recover from this
1042 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1046 * If kill_it gets set, there might be a way to recover from this
1050 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1051 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1052 char *msg = "Unknown";
1053 u64 recover_paddr = ~0ull;
1054 int flags = MF_ACTION_REQUIRED;
1056 prev_state = ist_enter(regs);
1058 this_cpu_inc(mce_exception_count);
1063 mce_gather_info(&m, regs);
1065 final = this_cpu_ptr(&mces_seen);
1068 memset(valid_banks, 0, sizeof(valid_banks));
1069 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1074 * When no restart IP might need to kill or panic.
1075 * Assume the worst for now, but if we find the
1076 * severity is MCE_AR_SEVERITY we have other options.
1078 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1082 * Go through all the banks in exclusion of the other CPUs.
1083 * This way we don't report duplicated events on shared banks
1084 * because the first one to see it will clear it.
1086 order = mce_start(&no_way_out);
1087 for (i = 0; i < cfg->banks; i++) {
1088 __clear_bit(i, toclear);
1089 if (!test_bit(i, valid_banks))
1091 if (!mce_banks[i].ctl)
1098 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1099 if ((m.status & MCI_STATUS_VAL) == 0)
1103 * Non uncorrected or non signaled errors are handled by
1104 * machine_check_poll. Leave them alone, unless this panics.
1106 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1111 * Set taint even when machine check was not enabled.
1113 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1115 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1118 * When machine check was for corrected/deferred handler don't
1119 * touch, unless we're panicing.
1121 if ((severity == MCE_KEEP_SEVERITY ||
1122 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1124 __set_bit(i, toclear);
1125 if (severity == MCE_NO_SEVERITY) {
1127 * Machine check event was not enabled. Clear, but
1133 mce_read_aux(&m, i);
1136 * Action optional error. Queue address for later processing.
1137 * When the ring overflows we just ignore the AO error.
1138 * RED-PEN add some logging mechanism when
1139 * usable_address or mce_add_ring fails.
1140 * RED-PEN don't ignore overflow for mca_cfg.tolerant == 0
1142 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1143 mce_ring_add(m.addr >> PAGE_SHIFT);
1147 if (severity > worst) {
1153 /* mce_clear_state will clear *final, save locally for use later */
1157 mce_clear_state(toclear);
1160 * Do most of the synchronization with other CPUs.
1161 * When there's any problem use only local no_way_out state.
1163 if (mce_end(order) < 0)
1164 no_way_out = worst >= MCE_PANIC_SEVERITY;
1167 * At insane "tolerant" levels we take no action. Otherwise
1168 * we only die if we have no other choice. For less serious
1169 * issues we try to recover, or limit damage to the current
1172 if (cfg->tolerant < 3) {
1174 mce_panic("Fatal machine check on current CPU", &m, msg);
1175 if (worst == MCE_AR_SEVERITY) {
1176 recover_paddr = m.addr;
1177 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1178 flags |= MF_MUST_KILL;
1179 } else if (kill_it) {
1180 force_sig(SIGBUS, current);
1185 mce_report_event(regs);
1186 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1190 if (recover_paddr == ~0ull)
1193 pr_err("Uncorrected hardware memory error in user-access at %llx",
1196 * We must call memory_failure() here even if the current process is
1197 * doomed. We still need to mark the page as poisoned and alert any
1198 * other users of the page.
1200 ist_begin_non_atomic(regs);
1202 if (memory_failure(recover_paddr >> PAGE_SHIFT, MCE_VECTOR, flags) < 0) {
1203 pr_err("Memory error not recovered");
1204 force_sig(SIGBUS, current);
1206 local_irq_disable();
1207 ist_end_non_atomic();
1209 ist_exit(regs, prev_state);
1211 EXPORT_SYMBOL_GPL(do_machine_check);
1213 #ifndef CONFIG_MEMORY_FAILURE
1214 int memory_failure(unsigned long pfn, int vector, int flags)
1216 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1217 BUG_ON(flags & MF_ACTION_REQUIRED);
1218 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1219 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1227 * Action optional processing happens here (picking up
1228 * from the list of faulting pages that do_machine_check()
1229 * placed into the "ring").
1231 static void mce_process_work(struct work_struct *dummy)
1235 while (mce_ring_get(&pfn))
1236 memory_failure(pfn, MCE_VECTOR, 0);
1239 #ifdef CONFIG_X86_MCE_INTEL
1241 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1242 * @cpu: The CPU on which the event occurred.
1243 * @status: Event status information
1245 * This function should be called by the thermal interrupt after the
1246 * event has been processed and the decision was made to log the event
1249 * The status parameter will be saved to the 'status' field of 'struct mce'
1250 * and historically has been the register value of the
1251 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1253 void mce_log_therm_throt_event(__u64 status)
1258 m.bank = MCE_THERMAL_BANK;
1262 #endif /* CONFIG_X86_MCE_INTEL */
1265 * Periodic polling timer for "silent" machine check errors. If the
1266 * poller finds an MCE, poll 2x faster. When the poller finds no more
1267 * errors, poll 2x slower (up to check_interval seconds).
1269 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1271 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1272 static DEFINE_PER_CPU(struct hrtimer, mce_timer);
1274 static unsigned long mce_adjust_timer_default(unsigned long interval)
1279 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1281 static enum hrtimer_restart __restart_timer(struct hrtimer *timer, unsigned long interval)
1284 return HRTIMER_NORESTART;
1285 hrtimer_forward_now(timer, ns_to_ktime(jiffies_to_nsecs(interval)));
1286 return HRTIMER_RESTART;
1289 static enum hrtimer_restart mce_timer_fn(struct hrtimer *timer)
1293 iv = __this_cpu_read(mce_next_interval);
1295 if (mce_available(this_cpu_ptr(&cpu_info))) {
1296 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1298 if (mce_intel_cmci_poll()) {
1299 iv = mce_adjust_timer(iv);
1305 * Alert userspace if needed. If we logged an MCE, reduce the polling
1306 * interval, otherwise increase the polling interval.
1308 if (mce_notify_irq())
1309 iv = max(iv / 2, (unsigned long) HZ/100);
1311 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1314 __this_cpu_write(mce_next_interval, iv);
1315 return __restart_timer(timer, iv);
1319 * Ensure that the timer is firing in @interval from now.
1321 void mce_timer_kick(unsigned long interval)
1323 struct hrtimer *t = this_cpu_ptr(&mce_timer);
1324 unsigned long iv = __this_cpu_read(mce_next_interval);
1326 __restart_timer(t, interval);
1329 __this_cpu_write(mce_next_interval, interval);
1332 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1333 static void mce_timer_delete_all(void)
1337 for_each_online_cpu(cpu)
1338 hrtimer_cancel(&per_cpu(mce_timer, cpu));
1341 static void mce_do_trigger(struct work_struct *work)
1343 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1346 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1348 static void __mce_notify_work(struct swork_event *event)
1350 /* Not more than two messages every minute */
1351 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1353 /* wake processes polling /dev/mcelog */
1354 wake_up_interruptible(&mce_chrdev_wait);
1357 * There is no risk of missing notifications because
1358 * work_pending is always cleared before the function is
1361 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1362 schedule_work(&mce_trigger_work);
1364 if (__ratelimit(&ratelimit))
1365 pr_info(HW_ERR "Machine check events logged\n");
1368 #ifdef CONFIG_PREEMPT_RT_FULL
1369 static bool notify_work_ready __read_mostly;
1370 static struct swork_event notify_work;
1372 static int mce_notify_work_init(void)
1380 INIT_SWORK(¬ify_work, __mce_notify_work);
1381 notify_work_ready = true;
1385 static void mce_notify_work(void)
1387 if (notify_work_ready)
1388 swork_queue(¬ify_work);
1391 static void mce_notify_work(void)
1393 __mce_notify_work(NULL);
1395 static inline int mce_notify_work_init(void) { return 0; }
1399 * Notify the user(s) about new machine check events.
1400 * Can be called from interrupt context, but not from machine check/NMI
1403 int mce_notify_irq(void)
1405 if (test_and_clear_bit(0, &mce_need_notify)) {
1411 EXPORT_SYMBOL_GPL(mce_notify_irq);
1413 static int __mcheck_cpu_mce_banks_init(void)
1416 u8 num_banks = mca_cfg.banks;
1418 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1422 for (i = 0; i < num_banks; i++) {
1423 struct mce_bank *b = &mce_banks[i];
1432 * Initialize Machine Checks for a CPU.
1434 static int __mcheck_cpu_cap_init(void)
1439 rdmsrl(MSR_IA32_MCG_CAP, cap);
1441 b = cap & MCG_BANKCNT_MASK;
1443 pr_info("CPU supports %d MCE banks\n", b);
1445 if (b > MAX_NR_BANKS) {
1446 pr_warn("Using only %u machine check banks out of %u\n",
1451 /* Don't support asymmetric configurations today */
1452 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1456 int err = __mcheck_cpu_mce_banks_init();
1462 /* Use accurate RIP reporting if available. */
1463 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1464 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1466 if (cap & MCG_SER_P)
1472 static void __mcheck_cpu_init_generic(void)
1474 enum mcp_flags m_fl = 0;
1475 mce_banks_t all_banks;
1479 if (!mca_cfg.bootlog)
1483 * Log the machine checks left over from the previous reset.
1485 bitmap_fill(all_banks, MAX_NR_BANKS);
1486 machine_check_poll(MCP_UC | m_fl, &all_banks);
1488 cr4_set_bits(X86_CR4_MCE);
1490 rdmsrl(MSR_IA32_MCG_CAP, cap);
1491 if (cap & MCG_CTL_P)
1492 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1494 for (i = 0; i < mca_cfg.banks; i++) {
1495 struct mce_bank *b = &mce_banks[i];
1499 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1500 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1505 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1506 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1507 * Vol 3B Table 15-20). But this confuses both the code that determines
1508 * whether the machine check occurred in kernel or user mode, and also
1509 * the severity assessment code. Pretend that EIPV was set, and take the
1510 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1512 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1516 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1518 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1519 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1520 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1522 (MCI_STATUS_UC|MCI_STATUS_EN|
1523 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1524 MCI_STATUS_AR|MCACOD_INSTR))
1527 m->mcgstatus |= MCG_STATUS_EIPV;
1532 /* Add per CPU specific workarounds here */
1533 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1535 struct mca_config *cfg = &mca_cfg;
1537 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1538 pr_info("unknown CPU type - not enabling MCE support\n");
1542 /* This should be disabled by the BIOS, but isn't always */
1543 if (c->x86_vendor == X86_VENDOR_AMD) {
1544 if (c->x86 == 15 && cfg->banks > 4) {
1546 * disable GART TBL walk error reporting, which
1547 * trips off incorrectly with the IOMMU & 3ware
1550 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1552 if (c->x86 <= 17 && cfg->bootlog < 0) {
1554 * Lots of broken BIOS around that don't clear them
1555 * by default and leave crap in there. Don't log:
1560 * Various K7s with broken bank 0 around. Always disable
1563 if (c->x86 == 6 && cfg->banks > 0)
1564 mce_banks[0].ctl = 0;
1567 * overflow_recov is supported for F15h Models 00h-0fh
1568 * even though we don't have a CPUID bit for it.
1570 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1571 mce_flags.overflow_recov = 1;
1574 * Turn off MC4_MISC thresholding banks on those models since
1575 * they're not supported there.
1577 if (c->x86 == 0x15 &&
1578 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1583 0x00000413, /* MC4_MISC0 */
1584 0xc0000408, /* MC4_MISC1 */
1587 rdmsrl(MSR_K7_HWCR, hwcr);
1589 /* McStatusWrEn has to be set */
1590 need_toggle = !(hwcr & BIT(18));
1593 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1595 /* Clear CntP bit safely */
1596 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1597 msr_clear_bit(msrs[i], 62);
1599 /* restore old settings */
1601 wrmsrl(MSR_K7_HWCR, hwcr);
1605 if (c->x86_vendor == X86_VENDOR_INTEL) {
1607 * SDM documents that on family 6 bank 0 should not be written
1608 * because it aliases to another special BIOS controlled
1610 * But it's not aliased anymore on model 0x1a+
1611 * Don't ignore bank 0 completely because there could be a
1612 * valid event later, merely don't write CTL0.
1615 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1616 mce_banks[0].init = 0;
1619 * All newer Intel systems support MCE broadcasting. Enable
1620 * synchronization with a one second timeout.
1622 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1623 cfg->monarch_timeout < 0)
1624 cfg->monarch_timeout = USEC_PER_SEC;
1627 * There are also broken BIOSes on some Pentium M and
1630 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1633 if (c->x86 == 6 && c->x86_model == 45)
1634 quirk_no_way_out = quirk_sandybridge_ifu;
1636 if (cfg->monarch_timeout < 0)
1637 cfg->monarch_timeout = 0;
1638 if (cfg->bootlog != 0)
1639 cfg->panic_timeout = 30;
1644 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1649 switch (c->x86_vendor) {
1650 case X86_VENDOR_INTEL:
1651 intel_p5_mcheck_init(c);
1654 case X86_VENDOR_CENTAUR:
1655 winchip_mcheck_init(c);
1663 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1665 switch (c->x86_vendor) {
1666 case X86_VENDOR_INTEL:
1667 mce_intel_feature_init(c);
1668 mce_adjust_timer = cmci_intel_adjust_timer;
1670 case X86_VENDOR_AMD:
1671 mce_amd_feature_init(c);
1672 mce_flags.overflow_recov = cpuid_ebx(0x80000007) & 0x1;
1679 static void mce_start_timer(unsigned int cpu, struct hrtimer *t)
1681 unsigned long iv = check_interval * HZ;
1683 if (mca_cfg.ignore_ce || !iv)
1686 per_cpu(mce_next_interval, cpu) = iv;
1688 hrtimer_start_range_ns(t, ns_to_ktime(jiffies_to_usecs(iv) * 1000ULL),
1689 0, HRTIMER_MODE_REL_PINNED);
1692 static void __mcheck_cpu_init_timer(void)
1694 struct hrtimer *t = this_cpu_ptr(&mce_timer);
1695 unsigned int cpu = smp_processor_id();
1697 hrtimer_init(t, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1698 t->function = mce_timer_fn;
1699 mce_start_timer(cpu, t);
1702 /* Handle unconfigured int18 (should never happen) */
1703 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1705 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1706 smp_processor_id());
1709 /* Call the installed machine check handler for this CPU setup. */
1710 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1711 unexpected_machine_check;
1714 * Called for each booted CPU to set up machine checks.
1715 * Must be called with preempt off:
1717 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1719 if (mca_cfg.disabled)
1722 if (__mcheck_cpu_ancient_init(c))
1725 if (!mce_available(c))
1728 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1729 mca_cfg.disabled = true;
1733 machine_check_vector = do_machine_check;
1735 __mcheck_cpu_init_generic();
1736 __mcheck_cpu_init_vendor(c);
1737 __mcheck_cpu_init_timer();
1738 INIT_WORK(this_cpu_ptr(&mce_work), mce_process_work);
1739 init_irq_work(this_cpu_ptr(&mce_irq_work), &mce_irq_work_cb);
1743 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1746 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1747 static int mce_chrdev_open_count; /* #times opened */
1748 static int mce_chrdev_open_exclu; /* already open exclusive? */
1750 static int mce_chrdev_open(struct inode *inode, struct file *file)
1752 spin_lock(&mce_chrdev_state_lock);
1754 if (mce_chrdev_open_exclu ||
1755 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1756 spin_unlock(&mce_chrdev_state_lock);
1761 if (file->f_flags & O_EXCL)
1762 mce_chrdev_open_exclu = 1;
1763 mce_chrdev_open_count++;
1765 spin_unlock(&mce_chrdev_state_lock);
1767 return nonseekable_open(inode, file);
1770 static int mce_chrdev_release(struct inode *inode, struct file *file)
1772 spin_lock(&mce_chrdev_state_lock);
1774 mce_chrdev_open_count--;
1775 mce_chrdev_open_exclu = 0;
1777 spin_unlock(&mce_chrdev_state_lock);
1782 static void collect_tscs(void *data)
1784 unsigned long *cpu_tsc = (unsigned long *)data;
1786 rdtscll(cpu_tsc[smp_processor_id()]);
1789 static int mce_apei_read_done;
1791 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1792 static int __mce_read_apei(char __user **ubuf, size_t usize)
1798 if (usize < sizeof(struct mce))
1801 rc = apei_read_mce(&m, &record_id);
1802 /* Error or no more MCE record */
1804 mce_apei_read_done = 1;
1806 * When ERST is disabled, mce_chrdev_read() should return
1807 * "no record" instead of "no device."
1814 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1817 * In fact, we should have cleared the record after that has
1818 * been flushed to the disk or sent to network in
1819 * /sbin/mcelog, but we have no interface to support that now,
1820 * so just clear it to avoid duplication.
1822 rc = apei_clear_mce(record_id);
1824 mce_apei_read_done = 1;
1827 *ubuf += sizeof(struct mce);
1832 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1833 size_t usize, loff_t *off)
1835 char __user *buf = ubuf;
1836 unsigned long *cpu_tsc;
1837 unsigned prev, next;
1840 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1844 mutex_lock(&mce_chrdev_read_mutex);
1846 if (!mce_apei_read_done) {
1847 err = __mce_read_apei(&buf, usize);
1848 if (err || buf != ubuf)
1852 next = rcu_dereference_check_mce(mcelog.next);
1854 /* Only supports full reads right now */
1856 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1862 for (i = prev; i < next; i++) {
1863 unsigned long start = jiffies;
1864 struct mce *m = &mcelog.entry[i];
1866 while (!m->finished) {
1867 if (time_after_eq(jiffies, start + 2)) {
1868 memset(m, 0, sizeof(*m));
1874 err |= copy_to_user(buf, m, sizeof(*m));
1880 memset(mcelog.entry + prev, 0,
1881 (next - prev) * sizeof(struct mce));
1883 next = cmpxchg(&mcelog.next, prev, 0);
1884 } while (next != prev);
1886 synchronize_sched();
1889 * Collect entries that were still getting written before the
1892 on_each_cpu(collect_tscs, cpu_tsc, 1);
1894 for (i = next; i < MCE_LOG_LEN; i++) {
1895 struct mce *m = &mcelog.entry[i];
1897 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1898 err |= copy_to_user(buf, m, sizeof(*m));
1901 memset(m, 0, sizeof(*m));
1909 mutex_unlock(&mce_chrdev_read_mutex);
1912 return err ? err : buf - ubuf;
1915 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1917 poll_wait(file, &mce_chrdev_wait, wait);
1918 if (rcu_access_index(mcelog.next))
1919 return POLLIN | POLLRDNORM;
1920 if (!mce_apei_read_done && apei_check_mce())
1921 return POLLIN | POLLRDNORM;
1925 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1928 int __user *p = (int __user *)arg;
1930 if (!capable(CAP_SYS_ADMIN))
1934 case MCE_GET_RECORD_LEN:
1935 return put_user(sizeof(struct mce), p);
1936 case MCE_GET_LOG_LEN:
1937 return put_user(MCE_LOG_LEN, p);
1938 case MCE_GETCLEAR_FLAGS: {
1942 flags = mcelog.flags;
1943 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1945 return put_user(flags, p);
1952 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1953 size_t usize, loff_t *off);
1955 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1956 const char __user *ubuf,
1957 size_t usize, loff_t *off))
1961 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1963 ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1964 size_t usize, loff_t *off)
1967 return mce_write(filp, ubuf, usize, off);
1972 static const struct file_operations mce_chrdev_ops = {
1973 .open = mce_chrdev_open,
1974 .release = mce_chrdev_release,
1975 .read = mce_chrdev_read,
1976 .write = mce_chrdev_write,
1977 .poll = mce_chrdev_poll,
1978 .unlocked_ioctl = mce_chrdev_ioctl,
1979 .llseek = no_llseek,
1982 static struct miscdevice mce_chrdev_device = {
1988 static void __mce_disable_bank(void *arg)
1990 int bank = *((int *)arg);
1991 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1992 cmci_disable_bank(bank);
1995 void mce_disable_bank(int bank)
1997 if (bank >= mca_cfg.banks) {
1999 "Ignoring request to disable invalid MCA bank %d.\n",
2003 set_bit(bank, mce_banks_ce_disabled);
2004 on_each_cpu(__mce_disable_bank, &bank, 1);
2008 * mce=off Disables machine check
2009 * mce=no_cmci Disables CMCI
2010 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2011 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2012 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2013 * monarchtimeout is how long to wait for other CPUs on machine
2014 * check, or 0 to not wait
2015 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2016 * mce=nobootlog Don't log MCEs from before booting.
2017 * mce=bios_cmci_threshold Don't program the CMCI threshold
2019 static int __init mcheck_enable(char *str)
2021 struct mca_config *cfg = &mca_cfg;
2029 if (!strcmp(str, "off"))
2030 cfg->disabled = true;
2031 else if (!strcmp(str, "no_cmci"))
2032 cfg->cmci_disabled = true;
2033 else if (!strcmp(str, "dont_log_ce"))
2034 cfg->dont_log_ce = true;
2035 else if (!strcmp(str, "ignore_ce"))
2036 cfg->ignore_ce = true;
2037 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2038 cfg->bootlog = (str[0] == 'b');
2039 else if (!strcmp(str, "bios_cmci_threshold"))
2040 cfg->bios_cmci_threshold = true;
2041 else if (isdigit(str[0])) {
2042 get_option(&str, &(cfg->tolerant));
2045 get_option(&str, &(cfg->monarch_timeout));
2048 pr_info("mce argument %s ignored. Please use /sys\n", str);
2053 __setup("mce", mcheck_enable);
2055 int __init mcheck_init(void)
2057 mcheck_intel_therm_init();
2058 mcheck_vendor_init_severity();
2064 * mce_syscore: PM support
2068 * Disable machine checks on suspend and shutdown. We can't really handle
2071 static int mce_disable_error_reporting(void)
2075 for (i = 0; i < mca_cfg.banks; i++) {
2076 struct mce_bank *b = &mce_banks[i];
2079 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2084 static int mce_syscore_suspend(void)
2086 return mce_disable_error_reporting();
2089 static void mce_syscore_shutdown(void)
2091 mce_disable_error_reporting();
2095 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2096 * Only one CPU is active at this time, the others get re-added later using
2099 static void mce_syscore_resume(void)
2101 __mcheck_cpu_init_generic();
2102 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2105 static struct syscore_ops mce_syscore_ops = {
2106 .suspend = mce_syscore_suspend,
2107 .shutdown = mce_syscore_shutdown,
2108 .resume = mce_syscore_resume,
2112 * mce_device: Sysfs support
2115 static void mce_cpu_restart(void *data)
2117 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2119 __mcheck_cpu_init_generic();
2120 __mcheck_cpu_init_timer();
2123 /* Reinit MCEs after user configuration changes */
2124 static void mce_restart(void)
2126 mce_timer_delete_all();
2127 on_each_cpu(mce_cpu_restart, NULL, 1);
2130 /* Toggle features for corrected errors */
2131 static void mce_disable_cmci(void *data)
2133 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2138 static void mce_enable_ce(void *all)
2140 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2145 __mcheck_cpu_init_timer();
2148 static struct bus_type mce_subsys = {
2149 .name = "machinecheck",
2150 .dev_name = "machinecheck",
2153 DEFINE_PER_CPU(struct device *, mce_device);
2155 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2157 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2159 return container_of(attr, struct mce_bank, attr);
2162 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2165 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2168 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2169 const char *buf, size_t size)
2173 if (kstrtou64(buf, 0, &new) < 0)
2176 attr_to_bank(attr)->ctl = new;
2183 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2185 strcpy(buf, mce_helper);
2187 return strlen(mce_helper) + 1;
2190 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2191 const char *buf, size_t siz)
2195 strncpy(mce_helper, buf, sizeof(mce_helper));
2196 mce_helper[sizeof(mce_helper)-1] = 0;
2197 p = strchr(mce_helper, '\n');
2202 return strlen(mce_helper) + !!p;
2205 static ssize_t set_ignore_ce(struct device *s,
2206 struct device_attribute *attr,
2207 const char *buf, size_t size)
2211 if (kstrtou64(buf, 0, &new) < 0)
2214 if (mca_cfg.ignore_ce ^ !!new) {
2216 /* disable ce features */
2217 mce_timer_delete_all();
2218 on_each_cpu(mce_disable_cmci, NULL, 1);
2219 mca_cfg.ignore_ce = true;
2221 /* enable ce features */
2222 mca_cfg.ignore_ce = false;
2223 on_each_cpu(mce_enable_ce, (void *)1, 1);
2229 static ssize_t set_cmci_disabled(struct device *s,
2230 struct device_attribute *attr,
2231 const char *buf, size_t size)
2235 if (kstrtou64(buf, 0, &new) < 0)
2238 if (mca_cfg.cmci_disabled ^ !!new) {
2241 on_each_cpu(mce_disable_cmci, NULL, 1);
2242 mca_cfg.cmci_disabled = true;
2245 mca_cfg.cmci_disabled = false;
2246 on_each_cpu(mce_enable_ce, NULL, 1);
2252 static ssize_t store_int_with_restart(struct device *s,
2253 struct device_attribute *attr,
2254 const char *buf, size_t size)
2256 ssize_t ret = device_store_int(s, attr, buf, size);
2261 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2262 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2263 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2264 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2266 static struct dev_ext_attribute dev_attr_check_interval = {
2267 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2271 static struct dev_ext_attribute dev_attr_ignore_ce = {
2272 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2276 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2277 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2278 &mca_cfg.cmci_disabled
2281 static struct device_attribute *mce_device_attrs[] = {
2282 &dev_attr_tolerant.attr,
2283 &dev_attr_check_interval.attr,
2285 &dev_attr_monarch_timeout.attr,
2286 &dev_attr_dont_log_ce.attr,
2287 &dev_attr_ignore_ce.attr,
2288 &dev_attr_cmci_disabled.attr,
2292 static cpumask_var_t mce_device_initialized;
2294 static void mce_device_release(struct device *dev)
2299 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2300 static int mce_device_create(unsigned int cpu)
2306 if (!mce_available(&boot_cpu_data))
2309 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2313 dev->bus = &mce_subsys;
2314 dev->release = &mce_device_release;
2316 err = device_register(dev);
2322 for (i = 0; mce_device_attrs[i]; i++) {
2323 err = device_create_file(dev, mce_device_attrs[i]);
2327 for (j = 0; j < mca_cfg.banks; j++) {
2328 err = device_create_file(dev, &mce_banks[j].attr);
2332 cpumask_set_cpu(cpu, mce_device_initialized);
2333 per_cpu(mce_device, cpu) = dev;
2338 device_remove_file(dev, &mce_banks[j].attr);
2341 device_remove_file(dev, mce_device_attrs[i]);
2343 device_unregister(dev);
2348 static void mce_device_remove(unsigned int cpu)
2350 struct device *dev = per_cpu(mce_device, cpu);
2353 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2356 for (i = 0; mce_device_attrs[i]; i++)
2357 device_remove_file(dev, mce_device_attrs[i]);
2359 for (i = 0; i < mca_cfg.banks; i++)
2360 device_remove_file(dev, &mce_banks[i].attr);
2362 device_unregister(dev);
2363 cpumask_clear_cpu(cpu, mce_device_initialized);
2364 per_cpu(mce_device, cpu) = NULL;
2367 /* Make sure there are no machine checks on offlined CPUs. */
2368 static void mce_disable_cpu(void *h)
2370 unsigned long action = *(unsigned long *)h;
2373 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2376 hrtimer_cancel(this_cpu_ptr(&mce_timer));
2378 if (!(action & CPU_TASKS_FROZEN))
2380 for (i = 0; i < mca_cfg.banks; i++) {
2381 struct mce_bank *b = &mce_banks[i];
2384 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2388 static void mce_reenable_cpu(void *h)
2390 unsigned long action = *(unsigned long *)h;
2393 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2396 if (!(action & CPU_TASKS_FROZEN))
2398 for (i = 0; i < mca_cfg.banks; i++) {
2399 struct mce_bank *b = &mce_banks[i];
2402 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2404 __mcheck_cpu_init_timer();
2407 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2409 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2411 unsigned int cpu = (unsigned long)hcpu;
2413 switch (action & ~CPU_TASKS_FROZEN) {
2415 mce_device_create(cpu);
2416 if (threshold_cpu_callback)
2417 threshold_cpu_callback(action, cpu);
2420 if (threshold_cpu_callback)
2421 threshold_cpu_callback(action, cpu);
2422 mce_device_remove(cpu);
2423 mce_intel_hcpu_update(cpu);
2425 /* intentionally ignoring frozen here */
2426 if (!(action & CPU_TASKS_FROZEN))
2429 case CPU_DOWN_PREPARE:
2430 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);
2440 static struct notifier_block mce_cpu_notifier = {
2441 .notifier_call = mce_cpu_callback,
2444 static __init void mce_init_banks(void)
2448 for (i = 0; i < mca_cfg.banks; i++) {
2449 struct mce_bank *b = &mce_banks[i];
2450 struct device_attribute *a = &b->attr;
2452 sysfs_attr_init(&a->attr);
2453 a->attr.name = b->attrname;
2454 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2456 a->attr.mode = 0644;
2457 a->show = show_bank;
2458 a->store = set_bank;
2462 static __init int mcheck_init_device(void)
2467 if (!mce_available(&boot_cpu_data)) {
2472 err = mce_notify_work_init();
2476 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2483 err = subsys_system_register(&mce_subsys, NULL);
2487 cpu_notifier_register_begin();
2488 for_each_online_cpu(i) {
2489 err = mce_device_create(i);
2492 * Register notifier anyway (and do not unreg it) so
2493 * that we don't leave undeleted timers, see notifier
2496 __register_hotcpu_notifier(&mce_cpu_notifier);
2497 cpu_notifier_register_done();
2498 goto err_device_create;
2502 __register_hotcpu_notifier(&mce_cpu_notifier);
2503 cpu_notifier_register_done();
2505 register_syscore_ops(&mce_syscore_ops);
2507 /* register character device /dev/mcelog */
2508 err = misc_register(&mce_chrdev_device);
2515 unregister_syscore_ops(&mce_syscore_ops);
2519 * We didn't keep track of which devices were created above, but
2520 * even if we had, the set of online cpus might have changed.
2521 * Play safe and remove for every possible cpu, since
2522 * mce_device_remove() will do the right thing.
2524 for_each_possible_cpu(i)
2525 mce_device_remove(i);
2528 free_cpumask_var(mce_device_initialized);
2531 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2535 device_initcall_sync(mcheck_init_device);
2538 * Old style boot options parsing. Only for compatibility.
2540 static int __init mcheck_disable(char *str)
2542 mca_cfg.disabled = true;
2545 __setup("nomce", mcheck_disable);
2547 #ifdef CONFIG_DEBUG_FS
2548 struct dentry *mce_get_debugfs_dir(void)
2550 static struct dentry *dmce;
2553 dmce = debugfs_create_dir("mce", NULL);
2558 static void mce_reset(void)
2561 atomic_set(&mce_fake_panicked, 0);
2562 atomic_set(&mce_executing, 0);
2563 atomic_set(&mce_callin, 0);
2564 atomic_set(&global_nwo, 0);
2567 static int fake_panic_get(void *data, u64 *val)
2573 static int fake_panic_set(void *data, u64 val)
2580 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2581 fake_panic_set, "%llu\n");
2583 static int __init mcheck_debugfs_init(void)
2585 struct dentry *dmce, *ffake_panic;
2587 dmce = mce_get_debugfs_dir();
2590 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2597 late_initcall(mcheck_debugfs_init);