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);
117 static int mce_usable_address(struct mce *m);
120 * CPU/chipset specific EDAC code can register a notifier call here to print
121 * MCE errors in a human-readable form.
123 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
125 /* Do initial initialization of a struct mce */
126 void mce_setup(struct mce *m)
128 memset(m, 0, sizeof(struct mce));
129 m->cpu = m->extcpu = smp_processor_id();
131 /* We hope get_seconds stays lockless */
132 m->time = get_seconds();
133 m->cpuvendor = boot_cpu_data.x86_vendor;
134 m->cpuid = cpuid_eax(1);
135 m->socketid = cpu_data(m->extcpu).phys_proc_id;
136 m->apicid = cpu_data(m->extcpu).initial_apicid;
137 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
140 DEFINE_PER_CPU(struct mce, injectm);
141 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
144 * Lockless MCE logging infrastructure.
145 * This avoids deadlocks on printk locks without having to break locks. Also
146 * separate MCEs from kernel messages to avoid bogus bug reports.
149 static struct mce_log mcelog = {
150 .signature = MCE_LOG_SIGNATURE,
152 .recordlen = sizeof(struct mce),
155 void mce_log(struct mce *mce)
157 unsigned next, entry;
159 /* Emit the trace record: */
160 trace_mce_record(mce);
162 if (!mce_gen_pool_add(mce))
163 irq_work_queue(&mce_irq_work);
168 entry = mce_log_get_idx_check(mcelog.next);
172 * When the buffer fills up discard new entries.
173 * Assume that the earlier errors are the more
176 if (entry >= MCE_LOG_LEN) {
177 set_bit(MCE_OVERFLOW,
178 (unsigned long *)&mcelog.flags);
181 /* Old left over entry. Skip: */
182 if (mcelog.entry[entry].finished) {
190 if (cmpxchg(&mcelog.next, entry, next) == entry)
193 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
195 mcelog.entry[entry].finished = 1;
199 set_bit(0, &mce_need_notify);
202 void mce_inject_log(struct mce *m)
204 mutex_lock(&mce_chrdev_read_mutex);
206 mutex_unlock(&mce_chrdev_read_mutex);
208 EXPORT_SYMBOL_GPL(mce_inject_log);
210 static struct notifier_block mce_srao_nb;
212 void mce_register_decode_chain(struct notifier_block *nb)
214 /* Ensure SRAO notifier has the highest priority in the decode chain. */
215 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
218 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
220 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
222 void mce_unregister_decode_chain(struct notifier_block *nb)
224 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
226 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
228 static void print_mce(struct mce *m)
232 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
233 m->extcpu, m->mcgstatus, m->bank, m->status);
236 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
237 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
240 if (m->cs == __KERNEL_CS)
241 print_symbol("{%s}", m->ip);
245 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
247 pr_cont("ADDR %llx ", m->addr);
249 pr_cont("MISC %llx ", m->misc);
253 * Note this output is parsed by external tools and old fields
254 * should not be changed.
256 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
257 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
258 cpu_data(m->extcpu).microcode);
261 * Print out human-readable details about the MCE error,
262 * (if the CPU has an implementation for that)
264 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
265 if (ret == NOTIFY_STOP)
268 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
271 #define PANIC_TIMEOUT 5 /* 5 seconds */
273 static atomic_t mce_panicked;
275 static int fake_panic;
276 static atomic_t mce_fake_panicked;
278 /* Panic in progress. Enable interrupts and wait for final IPI */
279 static void wait_for_panic(void)
281 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
285 while (timeout-- > 0)
287 if (panic_timeout == 0)
288 panic_timeout = mca_cfg.panic_timeout;
289 panic("Panicing machine check CPU died");
292 static void mce_panic(const char *msg, struct mce *final, char *exp)
298 * Make sure only one CPU runs in machine check panic
300 if (atomic_inc_return(&mce_panicked) > 1)
307 /* Don't log too much for fake panic */
308 if (atomic_inc_return(&mce_fake_panicked) > 1)
311 /* First print corrected ones that are still unlogged */
312 for (i = 0; i < MCE_LOG_LEN; i++) {
313 struct mce *m = &mcelog.entry[i];
314 if (!(m->status & MCI_STATUS_VAL))
316 if (!(m->status & MCI_STATUS_UC)) {
319 apei_err = apei_write_mce(m);
322 /* Now print uncorrected but with the final one last */
323 for (i = 0; i < MCE_LOG_LEN; i++) {
324 struct mce *m = &mcelog.entry[i];
325 if (!(m->status & MCI_STATUS_VAL))
327 if (!(m->status & MCI_STATUS_UC))
329 if (!final || memcmp(m, final, sizeof(struct mce))) {
332 apei_err = apei_write_mce(m);
338 apei_err = apei_write_mce(final);
341 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
343 pr_emerg(HW_ERR "Machine check: %s\n", exp);
345 if (panic_timeout == 0)
346 panic_timeout = mca_cfg.panic_timeout;
349 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
352 /* Support code for software error injection */
354 static int msr_to_offset(u32 msr)
356 unsigned bank = __this_cpu_read(injectm.bank);
358 if (msr == mca_cfg.rip_msr)
359 return offsetof(struct mce, ip);
360 if (msr == MSR_IA32_MCx_STATUS(bank))
361 return offsetof(struct mce, status);
362 if (msr == MSR_IA32_MCx_ADDR(bank))
363 return offsetof(struct mce, addr);
364 if (msr == MSR_IA32_MCx_MISC(bank))
365 return offsetof(struct mce, misc);
366 if (msr == MSR_IA32_MCG_STATUS)
367 return offsetof(struct mce, mcgstatus);
371 /* MSR access wrappers used for error injection */
372 static u64 mce_rdmsrl(u32 msr)
376 if (__this_cpu_read(injectm.finished)) {
377 int offset = msr_to_offset(msr);
381 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
384 if (rdmsrl_safe(msr, &v)) {
385 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
387 * Return zero in case the access faulted. This should
388 * not happen normally but can happen if the CPU does
389 * something weird, or if the code is buggy.
397 static void mce_wrmsrl(u32 msr, u64 v)
399 if (__this_cpu_read(injectm.finished)) {
400 int offset = msr_to_offset(msr);
403 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
410 * Collect all global (w.r.t. this processor) status about this machine
411 * check into our "mce" struct so that we can use it later to assess
412 * the severity of the problem as we read per-bank specific details.
414 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
418 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
421 * Get the address of the instruction at the time of
422 * the machine check error.
424 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
429 * When in VM86 mode make the cs look like ring 3
430 * always. This is a lie, but it's better than passing
431 * the additional vm86 bit around everywhere.
433 if (v8086_mode(regs))
436 /* Use accurate RIP reporting if available. */
438 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
442 int mce_available(struct cpuinfo_x86 *c)
444 if (mca_cfg.disabled)
446 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
449 static void mce_schedule_work(void)
451 if (!mce_gen_pool_empty() && keventd_up())
452 schedule_work(&mce_work);
455 static void mce_irq_work_cb(struct irq_work *entry)
461 static void mce_report_event(struct pt_regs *regs)
463 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
466 * Triggering the work queue here is just an insurance
467 * policy in case the syscall exit notify handler
468 * doesn't run soon enough or ends up running on the
469 * wrong CPU (can happen when audit sleeps)
475 irq_work_queue(&mce_irq_work);
478 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
481 struct mce *mce = (struct mce *)data;
487 if (mce->usable_addr && (mce->severity == MCE_AO_SEVERITY)) {
488 pfn = mce->addr >> PAGE_SHIFT;
489 memory_failure(pfn, MCE_VECTOR, 0);
494 static struct notifier_block mce_srao_nb = {
495 .notifier_call = srao_decode_notifier,
500 * Read ADDR and MISC registers.
502 static void mce_read_aux(struct mce *m, int i)
504 if (m->status & MCI_STATUS_MISCV)
505 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
506 if (m->status & MCI_STATUS_ADDRV) {
507 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
510 * Mask the reported address by the reported granularity.
512 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
513 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
520 static bool memory_error(struct mce *m)
522 struct cpuinfo_x86 *c = &boot_cpu_data;
524 if (c->x86_vendor == X86_VENDOR_AMD) {
529 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
531 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
533 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
534 * indicating a memory error. Bit 8 is used for indicating a
535 * cache hierarchy error. The combination of bit 2 and bit 3
536 * is used for indicating a `generic' cache hierarchy error
537 * But we can't just blindly check the above bits, because if
538 * bit 11 is set, then it is a bus/interconnect error - and
539 * either way the above bits just gives more detail on what
540 * bus/interconnect error happened. Note that bit 12 can be
541 * ignored, as it's the "filter" bit.
543 return (m->status & 0xef80) == BIT(7) ||
544 (m->status & 0xef00) == BIT(8) ||
545 (m->status & 0xeffc) == 0xc;
551 DEFINE_PER_CPU(unsigned, mce_poll_count);
554 * Poll for corrected events or events that happened before reset.
555 * Those are just logged through /dev/mcelog.
557 * This is executed in standard interrupt context.
559 * Note: spec recommends to panic for fatal unsignalled
560 * errors here. However this would be quite problematic --
561 * we would need to reimplement the Monarch handling and
562 * it would mess up the exclusion between exception handler
563 * and poll hander -- * so we skip this for now.
564 * These cases should not happen anyways, or only when the CPU
565 * is already totally * confused. In this case it's likely it will
566 * not fully execute the machine check handler either.
568 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
570 bool error_logged = false;
575 this_cpu_inc(mce_poll_count);
577 mce_gather_info(&m, NULL);
579 for (i = 0; i < mca_cfg.banks; i++) {
580 if (!mce_banks[i].ctl || !test_bit(i, *b))
589 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
590 if (!(m.status & MCI_STATUS_VAL))
595 * Uncorrected or signalled events are handled by the exception
596 * handler when it is enabled, so don't process those here.
598 * TBD do the same check for MCI_STATUS_EN here?
600 if (!(flags & MCP_UC) &&
601 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
606 if (!(flags & MCP_TIMESTAMP))
609 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
612 * In the cases where we don't have a valid address after all,
613 * do not add it into the ring buffer.
615 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m)) {
616 if (m.status & MCI_STATUS_ADDRV) {
617 m.severity = severity;
618 m.usable_addr = mce_usable_address(&m);
620 if (!mce_gen_pool_add(&m))
626 * Don't get the IP here because it's unlikely to
627 * have anything to do with the actual error location.
629 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce) {
635 * Clear state for this bank.
637 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
641 * Don't clear MCG_STATUS here because it's only defined for
649 EXPORT_SYMBOL_GPL(machine_check_poll);
652 * Do a quick check if any of the events requires a panic.
653 * This decides if we keep the events around or clear them.
655 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
656 struct pt_regs *regs)
661 for (i = 0; i < mca_cfg.banks; i++) {
662 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
663 if (m->status & MCI_STATUS_VAL) {
664 __set_bit(i, validp);
665 if (quirk_no_way_out)
666 quirk_no_way_out(i, m, regs);
669 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
678 * Variable to establish order between CPUs while scanning.
679 * Each CPU spins initially until executing is equal its number.
681 static atomic_t mce_executing;
684 * Defines order of CPUs on entry. First CPU becomes Monarch.
686 static atomic_t mce_callin;
689 * Check if a timeout waiting for other CPUs happened.
691 static int mce_timed_out(u64 *t, const char *msg)
694 * The others already did panic for some reason.
695 * Bail out like in a timeout.
696 * rmb() to tell the compiler that system_state
697 * might have been modified by someone else.
700 if (atomic_read(&mce_panicked))
702 if (!mca_cfg.monarch_timeout)
704 if ((s64)*t < SPINUNIT) {
705 if (mca_cfg.tolerant <= 1)
706 mce_panic(msg, NULL, NULL);
712 touch_nmi_watchdog();
717 * The Monarch's reign. The Monarch is the CPU who entered
718 * the machine check handler first. It waits for the others to
719 * raise the exception too and then grades them. When any
720 * error is fatal panic. Only then let the others continue.
722 * The other CPUs entering the MCE handler will be controlled by the
723 * Monarch. They are called Subjects.
725 * This way we prevent any potential data corruption in a unrecoverable case
726 * and also makes sure always all CPU's errors are examined.
728 * Also this detects the case of a machine check event coming from outer
729 * space (not detected by any CPUs) In this case some external agent wants
730 * us to shut down, so panic too.
732 * The other CPUs might still decide to panic if the handler happens
733 * in a unrecoverable place, but in this case the system is in a semi-stable
734 * state and won't corrupt anything by itself. It's ok to let the others
735 * continue for a bit first.
737 * All the spin loops have timeouts; when a timeout happens a CPU
738 * typically elects itself to be Monarch.
740 static void mce_reign(void)
743 struct mce *m = NULL;
744 int global_worst = 0;
749 * This CPU is the Monarch and the other CPUs have run
750 * through their handlers.
751 * Grade the severity of the errors of all the CPUs.
753 for_each_possible_cpu(cpu) {
754 int severity = mce_severity(&per_cpu(mces_seen, cpu),
757 if (severity > global_worst) {
759 global_worst = severity;
760 m = &per_cpu(mces_seen, cpu);
765 * Cannot recover? Panic here then.
766 * This dumps all the mces in the log buffer and stops the
769 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
770 mce_panic("Fatal machine check", m, msg);
773 * For UC somewhere we let the CPU who detects it handle it.
774 * Also must let continue the others, otherwise the handling
775 * CPU could deadlock on a lock.
779 * No machine check event found. Must be some external
780 * source or one CPU is hung. Panic.
782 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
783 mce_panic("Fatal machine check from unknown source", NULL, NULL);
786 * Now clear all the mces_seen so that they don't reappear on
789 for_each_possible_cpu(cpu)
790 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
793 static atomic_t global_nwo;
796 * Start of Monarch synchronization. This waits until all CPUs have
797 * entered the exception handler and then determines if any of them
798 * saw a fatal event that requires panic. Then it executes them
799 * in the entry order.
800 * TBD double check parallel CPU hotunplug
802 static int mce_start(int *no_way_out)
805 int cpus = num_online_cpus();
806 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
811 atomic_add(*no_way_out, &global_nwo);
813 * global_nwo should be updated before mce_callin
816 order = atomic_inc_return(&mce_callin);
821 while (atomic_read(&mce_callin) != cpus) {
822 if (mce_timed_out(&timeout,
823 "Timeout: Not all CPUs entered broadcast exception handler")) {
824 atomic_set(&global_nwo, 0);
831 * mce_callin should be read before global_nwo
837 * Monarch: Starts executing now, the others wait.
839 atomic_set(&mce_executing, 1);
842 * Subject: Now start the scanning loop one by one in
843 * the original callin order.
844 * This way when there are any shared banks it will be
845 * only seen by one CPU before cleared, avoiding duplicates.
847 while (atomic_read(&mce_executing) < order) {
848 if (mce_timed_out(&timeout,
849 "Timeout: Subject CPUs unable to finish machine check processing")) {
850 atomic_set(&global_nwo, 0);
858 * Cache the global no_way_out state.
860 *no_way_out = atomic_read(&global_nwo);
866 * Synchronize between CPUs after main scanning loop.
867 * This invokes the bulk of the Monarch processing.
869 static int mce_end(int order)
872 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
880 * Allow others to run.
882 atomic_inc(&mce_executing);
885 /* CHECKME: Can this race with a parallel hotplug? */
886 int cpus = num_online_cpus();
889 * Monarch: Wait for everyone to go through their scanning
892 while (atomic_read(&mce_executing) <= cpus) {
893 if (mce_timed_out(&timeout,
894 "Timeout: Monarch CPU unable to finish machine check processing"))
904 * Subject: Wait for Monarch to finish.
906 while (atomic_read(&mce_executing) != 0) {
907 if (mce_timed_out(&timeout,
908 "Timeout: Monarch CPU did not finish machine check processing"))
914 * Don't reset anything. That's done by the Monarch.
920 * Reset all global state.
923 atomic_set(&global_nwo, 0);
924 atomic_set(&mce_callin, 0);
928 * Let others run again.
930 atomic_set(&mce_executing, 0);
935 * Check if the address reported by the CPU is in a format we can parse.
936 * It would be possible to add code for most other cases, but all would
937 * be somewhat complicated (e.g. segment offset would require an instruction
938 * parser). So only support physical addresses up to page granuality for now.
940 static int mce_usable_address(struct mce *m)
942 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
944 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
946 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
951 static void mce_clear_state(unsigned long *toclear)
955 for (i = 0; i < mca_cfg.banks; i++) {
956 if (test_bit(i, toclear))
957 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
962 * The actual machine check handler. This only handles real
963 * exceptions when something got corrupted coming in through int 18.
965 * This is executed in NMI context not subject to normal locking rules. This
966 * implies that most kernel services cannot be safely used. Don't even
967 * think about putting a printk in there!
969 * On Intel systems this is entered on all CPUs in parallel through
970 * MCE broadcast. However some CPUs might be broken beyond repair,
971 * so be always careful when synchronizing with others.
973 void do_machine_check(struct pt_regs *regs, long error_code)
975 struct mca_config *cfg = &mca_cfg;
976 struct mce m, *final;
981 * Establish sequential order between the CPUs entering the machine
986 * If no_way_out gets set, there is no safe way to recover from this
987 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
991 * If kill_it gets set, there might be a way to recover from this
995 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
996 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
997 char *msg = "Unknown";
998 u64 recover_paddr = ~0ull;
999 int flags = MF_ACTION_REQUIRED;
1004 this_cpu_inc(mce_exception_count);
1009 mce_gather_info(&m, regs);
1011 final = this_cpu_ptr(&mces_seen);
1014 memset(valid_banks, 0, sizeof(valid_banks));
1015 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1020 * When no restart IP might need to kill or panic.
1021 * Assume the worst for now, but if we find the
1022 * severity is MCE_AR_SEVERITY we have other options.
1024 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1028 * Check if this MCE is signaled to only this logical processor
1030 if (m.mcgstatus & MCG_STATUS_LMCES)
1034 * Go through all the banks in exclusion of the other CPUs.
1035 * This way we don't report duplicated events on shared banks
1036 * because the first one to see it will clear it.
1037 * If this is a Local MCE, then no need to perform rendezvous.
1039 order = mce_start(&no_way_out);
1042 for (i = 0; i < cfg->banks; i++) {
1043 __clear_bit(i, toclear);
1044 if (!test_bit(i, valid_banks))
1046 if (!mce_banks[i].ctl)
1053 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1054 if ((m.status & MCI_STATUS_VAL) == 0)
1058 * Non uncorrected or non signaled errors are handled by
1059 * machine_check_poll. Leave them alone, unless this panics.
1061 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1066 * Set taint even when machine check was not enabled.
1068 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1070 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1073 * When machine check was for corrected/deferred handler don't
1074 * touch, unless we're panicing.
1076 if ((severity == MCE_KEEP_SEVERITY ||
1077 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1079 __set_bit(i, toclear);
1080 if (severity == MCE_NO_SEVERITY) {
1082 * Machine check event was not enabled. Clear, but
1088 mce_read_aux(&m, i);
1090 /* assuming valid severity level != 0 */
1091 m.severity = severity;
1092 m.usable_addr = mce_usable_address(&m);
1096 if (severity > worst) {
1102 /* mce_clear_state will clear *final, save locally for use later */
1106 mce_clear_state(toclear);
1109 * Do most of the synchronization with other CPUs.
1110 * When there's any problem use only local no_way_out state.
1113 if (mce_end(order) < 0)
1114 no_way_out = worst >= MCE_PANIC_SEVERITY;
1117 * Local MCE skipped calling mce_reign()
1118 * If we found a fatal error, we need to panic here.
1120 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1121 mce_panic("Machine check from unknown source",
1126 * At insane "tolerant" levels we take no action. Otherwise
1127 * we only die if we have no other choice. For less serious
1128 * issues we try to recover, or limit damage to the current
1131 if (cfg->tolerant < 3) {
1133 mce_panic("Fatal machine check on current CPU", &m, msg);
1134 if (worst == MCE_AR_SEVERITY) {
1135 recover_paddr = m.addr;
1136 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1137 flags |= MF_MUST_KILL;
1138 } else if (kill_it) {
1139 force_sig(SIGBUS, current);
1144 mce_report_event(regs);
1145 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1149 if (recover_paddr == ~0ull)
1152 pr_err("Uncorrected hardware memory error in user-access at %llx",
1155 * We must call memory_failure() here even if the current process is
1156 * doomed. We still need to mark the page as poisoned and alert any
1157 * other users of the page.
1159 ist_begin_non_atomic(regs);
1161 if (memory_failure(recover_paddr >> PAGE_SHIFT, MCE_VECTOR, flags) < 0) {
1162 pr_err("Memory error not recovered");
1163 force_sig(SIGBUS, current);
1165 local_irq_disable();
1166 ist_end_non_atomic();
1170 EXPORT_SYMBOL_GPL(do_machine_check);
1172 #ifndef CONFIG_MEMORY_FAILURE
1173 int memory_failure(unsigned long pfn, int vector, int flags)
1175 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1176 BUG_ON(flags & MF_ACTION_REQUIRED);
1177 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1178 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1186 * Action optional processing happens here (picking up
1187 * from the list of faulting pages that do_machine_check()
1188 * placed into the genpool).
1190 static void mce_process_work(struct work_struct *dummy)
1192 mce_gen_pool_process();
1195 #ifdef CONFIG_X86_MCE_INTEL
1197 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1198 * @cpu: The CPU on which the event occurred.
1199 * @status: Event status information
1201 * This function should be called by the thermal interrupt after the
1202 * event has been processed and the decision was made to log the event
1205 * The status parameter will be saved to the 'status' field of 'struct mce'
1206 * and historically has been the register value of the
1207 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1209 void mce_log_therm_throt_event(__u64 status)
1214 m.bank = MCE_THERMAL_BANK;
1218 #endif /* CONFIG_X86_MCE_INTEL */
1221 * Periodic polling timer for "silent" machine check errors. If the
1222 * poller finds an MCE, poll 2x faster. When the poller finds no more
1223 * errors, poll 2x slower (up to check_interval seconds).
1225 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1227 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1228 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1230 static unsigned long mce_adjust_timer_default(unsigned long interval)
1235 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1237 static void __restart_timer(struct timer_list *t, unsigned long interval)
1239 unsigned long when = jiffies + interval;
1240 unsigned long flags;
1242 local_irq_save(flags);
1244 if (timer_pending(t)) {
1245 if (time_before(when, t->expires))
1246 mod_timer_pinned(t, when);
1248 t->expires = round_jiffies(when);
1249 add_timer_on(t, smp_processor_id());
1252 local_irq_restore(flags);
1255 static void mce_timer_fn(unsigned long data)
1257 struct timer_list *t = this_cpu_ptr(&mce_timer);
1258 int cpu = smp_processor_id();
1261 WARN_ON(cpu != data);
1263 iv = __this_cpu_read(mce_next_interval);
1265 if (mce_available(this_cpu_ptr(&cpu_info))) {
1266 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1268 if (mce_intel_cmci_poll()) {
1269 iv = mce_adjust_timer(iv);
1275 * Alert userspace if needed. If we logged an MCE, reduce the polling
1276 * interval, otherwise increase the polling interval.
1278 if (mce_notify_irq())
1279 iv = max(iv / 2, (unsigned long) HZ/100);
1281 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1284 __this_cpu_write(mce_next_interval, iv);
1285 __restart_timer(t, iv);
1289 * Ensure that the timer is firing in @interval from now.
1291 void mce_timer_kick(unsigned long interval)
1293 struct timer_list *t = this_cpu_ptr(&mce_timer);
1294 unsigned long iv = __this_cpu_read(mce_next_interval);
1296 __restart_timer(t, interval);
1299 __this_cpu_write(mce_next_interval, interval);
1302 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1303 static void mce_timer_delete_all(void)
1307 for_each_online_cpu(cpu)
1308 del_timer_sync(&per_cpu(mce_timer, cpu));
1311 static void mce_do_trigger(struct work_struct *work)
1313 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1316 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1319 * Notify the user(s) about new machine check events.
1320 * Can be called from interrupt context, but not from machine check/NMI
1323 int mce_notify_irq(void)
1325 /* Not more than two messages every minute */
1326 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1328 if (test_and_clear_bit(0, &mce_need_notify)) {
1329 /* wake processes polling /dev/mcelog */
1330 wake_up_interruptible(&mce_chrdev_wait);
1333 schedule_work(&mce_trigger_work);
1335 if (__ratelimit(&ratelimit))
1336 pr_info(HW_ERR "Machine check events logged\n");
1342 EXPORT_SYMBOL_GPL(mce_notify_irq);
1344 static int __mcheck_cpu_mce_banks_init(void)
1347 u8 num_banks = mca_cfg.banks;
1349 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1353 for (i = 0; i < num_banks; i++) {
1354 struct mce_bank *b = &mce_banks[i];
1363 * Initialize Machine Checks for a CPU.
1365 static int __mcheck_cpu_cap_init(void)
1370 rdmsrl(MSR_IA32_MCG_CAP, cap);
1372 b = cap & MCG_BANKCNT_MASK;
1374 pr_info("CPU supports %d MCE banks\n", b);
1376 if (b > MAX_NR_BANKS) {
1377 pr_warn("Using only %u machine check banks out of %u\n",
1382 /* Don't support asymmetric configurations today */
1383 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1387 int err = __mcheck_cpu_mce_banks_init();
1393 /* Use accurate RIP reporting if available. */
1394 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1395 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1397 if (cap & MCG_SER_P)
1403 static void __mcheck_cpu_init_generic(void)
1405 enum mcp_flags m_fl = 0;
1406 mce_banks_t all_banks;
1410 if (!mca_cfg.bootlog)
1414 * Log the machine checks left over from the previous reset.
1416 bitmap_fill(all_banks, MAX_NR_BANKS);
1417 machine_check_poll(MCP_UC | m_fl, &all_banks);
1419 cr4_set_bits(X86_CR4_MCE);
1421 rdmsrl(MSR_IA32_MCG_CAP, cap);
1422 if (cap & MCG_CTL_P)
1423 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1425 for (i = 0; i < mca_cfg.banks; i++) {
1426 struct mce_bank *b = &mce_banks[i];
1430 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1431 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1436 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1437 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1438 * Vol 3B Table 15-20). But this confuses both the code that determines
1439 * whether the machine check occurred in kernel or user mode, and also
1440 * the severity assessment code. Pretend that EIPV was set, and take the
1441 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1443 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1447 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1449 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1450 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1451 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1453 (MCI_STATUS_UC|MCI_STATUS_EN|
1454 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1455 MCI_STATUS_AR|MCACOD_INSTR))
1458 m->mcgstatus |= MCG_STATUS_EIPV;
1463 /* Add per CPU specific workarounds here */
1464 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1466 struct mca_config *cfg = &mca_cfg;
1468 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1469 pr_info("unknown CPU type - not enabling MCE support\n");
1473 /* This should be disabled by the BIOS, but isn't always */
1474 if (c->x86_vendor == X86_VENDOR_AMD) {
1475 if (c->x86 == 15 && cfg->banks > 4) {
1477 * disable GART TBL walk error reporting, which
1478 * trips off incorrectly with the IOMMU & 3ware
1481 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1483 if (c->x86 <= 17 && cfg->bootlog < 0) {
1485 * Lots of broken BIOS around that don't clear them
1486 * by default and leave crap in there. Don't log:
1491 * Various K7s with broken bank 0 around. Always disable
1494 if (c->x86 == 6 && cfg->banks > 0)
1495 mce_banks[0].ctl = 0;
1498 * overflow_recov is supported for F15h Models 00h-0fh
1499 * even though we don't have a CPUID bit for it.
1501 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1502 mce_flags.overflow_recov = 1;
1505 * Turn off MC4_MISC thresholding banks on those models since
1506 * they're not supported there.
1508 if (c->x86 == 0x15 &&
1509 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1514 0x00000413, /* MC4_MISC0 */
1515 0xc0000408, /* MC4_MISC1 */
1518 rdmsrl(MSR_K7_HWCR, hwcr);
1520 /* McStatusWrEn has to be set */
1521 need_toggle = !(hwcr & BIT(18));
1524 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1526 /* Clear CntP bit safely */
1527 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1528 msr_clear_bit(msrs[i], 62);
1530 /* restore old settings */
1532 wrmsrl(MSR_K7_HWCR, hwcr);
1536 if (c->x86_vendor == X86_VENDOR_INTEL) {
1538 * SDM documents that on family 6 bank 0 should not be written
1539 * because it aliases to another special BIOS controlled
1541 * But it's not aliased anymore on model 0x1a+
1542 * Don't ignore bank 0 completely because there could be a
1543 * valid event later, merely don't write CTL0.
1546 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1547 mce_banks[0].init = 0;
1550 * All newer Intel systems support MCE broadcasting. Enable
1551 * synchronization with a one second timeout.
1553 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1554 cfg->monarch_timeout < 0)
1555 cfg->monarch_timeout = USEC_PER_SEC;
1558 * There are also broken BIOSes on some Pentium M and
1561 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1564 if (c->x86 == 6 && c->x86_model == 45)
1565 quirk_no_way_out = quirk_sandybridge_ifu;
1567 if (cfg->monarch_timeout < 0)
1568 cfg->monarch_timeout = 0;
1569 if (cfg->bootlog != 0)
1570 cfg->panic_timeout = 30;
1575 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1580 switch (c->x86_vendor) {
1581 case X86_VENDOR_INTEL:
1582 intel_p5_mcheck_init(c);
1585 case X86_VENDOR_CENTAUR:
1586 winchip_mcheck_init(c);
1594 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1596 switch (c->x86_vendor) {
1597 case X86_VENDOR_INTEL:
1598 mce_intel_feature_init(c);
1599 mce_adjust_timer = cmci_intel_adjust_timer;
1602 case X86_VENDOR_AMD: {
1603 u32 ebx = cpuid_ebx(0x80000007);
1605 mce_amd_feature_init(c);
1606 mce_flags.overflow_recov = !!(ebx & BIT(0));
1607 mce_flags.succor = !!(ebx & BIT(1));
1616 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1618 switch (c->x86_vendor) {
1619 case X86_VENDOR_INTEL:
1620 mce_intel_feature_clear(c);
1627 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1629 unsigned long iv = check_interval * HZ;
1631 if (mca_cfg.ignore_ce || !iv)
1634 per_cpu(mce_next_interval, cpu) = iv;
1636 t->expires = round_jiffies(jiffies + iv);
1637 add_timer_on(t, cpu);
1640 static void __mcheck_cpu_init_timer(void)
1642 struct timer_list *t = this_cpu_ptr(&mce_timer);
1643 unsigned int cpu = smp_processor_id();
1645 setup_timer(t, mce_timer_fn, cpu);
1646 mce_start_timer(cpu, t);
1649 /* Handle unconfigured int18 (should never happen) */
1650 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1652 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1653 smp_processor_id());
1656 /* Call the installed machine check handler for this CPU setup. */
1657 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1658 unexpected_machine_check;
1661 * Called for each booted CPU to set up machine checks.
1662 * Must be called with preempt off:
1664 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1666 if (mca_cfg.disabled)
1669 if (__mcheck_cpu_ancient_init(c))
1672 if (!mce_available(c))
1675 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1676 mca_cfg.disabled = true;
1680 if (mce_gen_pool_init()) {
1681 mca_cfg.disabled = true;
1682 pr_emerg("Couldn't allocate MCE records pool!\n");
1686 machine_check_vector = do_machine_check;
1688 __mcheck_cpu_init_generic();
1689 __mcheck_cpu_init_vendor(c);
1690 __mcheck_cpu_init_timer();
1694 * Called for each booted CPU to clear some machine checks opt-ins
1696 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1698 if (mca_cfg.disabled)
1701 if (!mce_available(c))
1705 * Possibly to clear general settings generic to x86
1706 * __mcheck_cpu_clear_generic(c);
1708 __mcheck_cpu_clear_vendor(c);
1713 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1716 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1717 static int mce_chrdev_open_count; /* #times opened */
1718 static int mce_chrdev_open_exclu; /* already open exclusive? */
1720 static int mce_chrdev_open(struct inode *inode, struct file *file)
1722 spin_lock(&mce_chrdev_state_lock);
1724 if (mce_chrdev_open_exclu ||
1725 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1726 spin_unlock(&mce_chrdev_state_lock);
1731 if (file->f_flags & O_EXCL)
1732 mce_chrdev_open_exclu = 1;
1733 mce_chrdev_open_count++;
1735 spin_unlock(&mce_chrdev_state_lock);
1737 return nonseekable_open(inode, file);
1740 static int mce_chrdev_release(struct inode *inode, struct file *file)
1742 spin_lock(&mce_chrdev_state_lock);
1744 mce_chrdev_open_count--;
1745 mce_chrdev_open_exclu = 0;
1747 spin_unlock(&mce_chrdev_state_lock);
1752 static void collect_tscs(void *data)
1754 unsigned long *cpu_tsc = (unsigned long *)data;
1756 cpu_tsc[smp_processor_id()] = rdtsc();
1759 static int mce_apei_read_done;
1761 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1762 static int __mce_read_apei(char __user **ubuf, size_t usize)
1768 if (usize < sizeof(struct mce))
1771 rc = apei_read_mce(&m, &record_id);
1772 /* Error or no more MCE record */
1774 mce_apei_read_done = 1;
1776 * When ERST is disabled, mce_chrdev_read() should return
1777 * "no record" instead of "no device."
1784 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1787 * In fact, we should have cleared the record after that has
1788 * been flushed to the disk or sent to network in
1789 * /sbin/mcelog, but we have no interface to support that now,
1790 * so just clear it to avoid duplication.
1792 rc = apei_clear_mce(record_id);
1794 mce_apei_read_done = 1;
1797 *ubuf += sizeof(struct mce);
1802 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1803 size_t usize, loff_t *off)
1805 char __user *buf = ubuf;
1806 unsigned long *cpu_tsc;
1807 unsigned prev, next;
1810 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1814 mutex_lock(&mce_chrdev_read_mutex);
1816 if (!mce_apei_read_done) {
1817 err = __mce_read_apei(&buf, usize);
1818 if (err || buf != ubuf)
1822 next = mce_log_get_idx_check(mcelog.next);
1824 /* Only supports full reads right now */
1826 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1832 for (i = prev; i < next; i++) {
1833 unsigned long start = jiffies;
1834 struct mce *m = &mcelog.entry[i];
1836 while (!m->finished) {
1837 if (time_after_eq(jiffies, start + 2)) {
1838 memset(m, 0, sizeof(*m));
1844 err |= copy_to_user(buf, m, sizeof(*m));
1850 memset(mcelog.entry + prev, 0,
1851 (next - prev) * sizeof(struct mce));
1853 next = cmpxchg(&mcelog.next, prev, 0);
1854 } while (next != prev);
1856 synchronize_sched();
1859 * Collect entries that were still getting written before the
1862 on_each_cpu(collect_tscs, cpu_tsc, 1);
1864 for (i = next; i < MCE_LOG_LEN; i++) {
1865 struct mce *m = &mcelog.entry[i];
1867 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1868 err |= copy_to_user(buf, m, sizeof(*m));
1871 memset(m, 0, sizeof(*m));
1879 mutex_unlock(&mce_chrdev_read_mutex);
1882 return err ? err : buf - ubuf;
1885 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1887 poll_wait(file, &mce_chrdev_wait, wait);
1888 if (READ_ONCE(mcelog.next))
1889 return POLLIN | POLLRDNORM;
1890 if (!mce_apei_read_done && apei_check_mce())
1891 return POLLIN | POLLRDNORM;
1895 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1898 int __user *p = (int __user *)arg;
1900 if (!capable(CAP_SYS_ADMIN))
1904 case MCE_GET_RECORD_LEN:
1905 return put_user(sizeof(struct mce), p);
1906 case MCE_GET_LOG_LEN:
1907 return put_user(MCE_LOG_LEN, p);
1908 case MCE_GETCLEAR_FLAGS: {
1912 flags = mcelog.flags;
1913 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1915 return put_user(flags, p);
1922 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1923 size_t usize, loff_t *off);
1925 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1926 const char __user *ubuf,
1927 size_t usize, loff_t *off))
1931 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1933 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1934 size_t usize, loff_t *off)
1937 return mce_write(filp, ubuf, usize, off);
1942 static const struct file_operations mce_chrdev_ops = {
1943 .open = mce_chrdev_open,
1944 .release = mce_chrdev_release,
1945 .read = mce_chrdev_read,
1946 .write = mce_chrdev_write,
1947 .poll = mce_chrdev_poll,
1948 .unlocked_ioctl = mce_chrdev_ioctl,
1949 .llseek = no_llseek,
1952 static struct miscdevice mce_chrdev_device = {
1958 static void __mce_disable_bank(void *arg)
1960 int bank = *((int *)arg);
1961 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1962 cmci_disable_bank(bank);
1965 void mce_disable_bank(int bank)
1967 if (bank >= mca_cfg.banks) {
1969 "Ignoring request to disable invalid MCA bank %d.\n",
1973 set_bit(bank, mce_banks_ce_disabled);
1974 on_each_cpu(__mce_disable_bank, &bank, 1);
1978 * mce=off Disables machine check
1979 * mce=no_cmci Disables CMCI
1980 * mce=no_lmce Disables LMCE
1981 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1982 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1983 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1984 * monarchtimeout is how long to wait for other CPUs on machine
1985 * check, or 0 to not wait
1986 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1987 * mce=nobootlog Don't log MCEs from before booting.
1988 * mce=bios_cmci_threshold Don't program the CMCI threshold
1990 static int __init mcheck_enable(char *str)
1992 struct mca_config *cfg = &mca_cfg;
2000 if (!strcmp(str, "off"))
2001 cfg->disabled = true;
2002 else if (!strcmp(str, "no_cmci"))
2003 cfg->cmci_disabled = true;
2004 else if (!strcmp(str, "no_lmce"))
2005 cfg->lmce_disabled = true;
2006 else if (!strcmp(str, "dont_log_ce"))
2007 cfg->dont_log_ce = true;
2008 else if (!strcmp(str, "ignore_ce"))
2009 cfg->ignore_ce = true;
2010 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2011 cfg->bootlog = (str[0] == 'b');
2012 else if (!strcmp(str, "bios_cmci_threshold"))
2013 cfg->bios_cmci_threshold = true;
2014 else if (isdigit(str[0])) {
2015 if (get_option(&str, &cfg->tolerant) == 2)
2016 get_option(&str, &(cfg->monarch_timeout));
2018 pr_info("mce argument %s ignored. Please use /sys\n", str);
2023 __setup("mce", mcheck_enable);
2025 int __init mcheck_init(void)
2027 mcheck_intel_therm_init();
2028 mce_register_decode_chain(&mce_srao_nb);
2029 mcheck_vendor_init_severity();
2031 INIT_WORK(&mce_work, mce_process_work);
2032 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2038 * mce_syscore: PM support
2042 * Disable machine checks on suspend and shutdown. We can't really handle
2045 static int mce_disable_error_reporting(void)
2049 for (i = 0; i < mca_cfg.banks; i++) {
2050 struct mce_bank *b = &mce_banks[i];
2053 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2058 static int mce_syscore_suspend(void)
2060 return mce_disable_error_reporting();
2063 static void mce_syscore_shutdown(void)
2065 mce_disable_error_reporting();
2069 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2070 * Only one CPU is active at this time, the others get re-added later using
2073 static void mce_syscore_resume(void)
2075 __mcheck_cpu_init_generic();
2076 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2079 static struct syscore_ops mce_syscore_ops = {
2080 .suspend = mce_syscore_suspend,
2081 .shutdown = mce_syscore_shutdown,
2082 .resume = mce_syscore_resume,
2086 * mce_device: Sysfs support
2089 static void mce_cpu_restart(void *data)
2091 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2093 __mcheck_cpu_init_generic();
2094 __mcheck_cpu_init_timer();
2097 /* Reinit MCEs after user configuration changes */
2098 static void mce_restart(void)
2100 mce_timer_delete_all();
2101 on_each_cpu(mce_cpu_restart, NULL, 1);
2104 /* Toggle features for corrected errors */
2105 static void mce_disable_cmci(void *data)
2107 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2112 static void mce_enable_ce(void *all)
2114 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2119 __mcheck_cpu_init_timer();
2122 static struct bus_type mce_subsys = {
2123 .name = "machinecheck",
2124 .dev_name = "machinecheck",
2127 DEFINE_PER_CPU(struct device *, mce_device);
2129 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2131 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2133 return container_of(attr, struct mce_bank, attr);
2136 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2139 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2142 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2143 const char *buf, size_t size)
2147 if (kstrtou64(buf, 0, &new) < 0)
2150 attr_to_bank(attr)->ctl = new;
2157 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2159 strcpy(buf, mce_helper);
2161 return strlen(mce_helper) + 1;
2164 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2165 const char *buf, size_t siz)
2169 strncpy(mce_helper, buf, sizeof(mce_helper));
2170 mce_helper[sizeof(mce_helper)-1] = 0;
2171 p = strchr(mce_helper, '\n');
2176 return strlen(mce_helper) + !!p;
2179 static ssize_t set_ignore_ce(struct device *s,
2180 struct device_attribute *attr,
2181 const char *buf, size_t size)
2185 if (kstrtou64(buf, 0, &new) < 0)
2188 if (mca_cfg.ignore_ce ^ !!new) {
2190 /* disable ce features */
2191 mce_timer_delete_all();
2192 on_each_cpu(mce_disable_cmci, NULL, 1);
2193 mca_cfg.ignore_ce = true;
2195 /* enable ce features */
2196 mca_cfg.ignore_ce = false;
2197 on_each_cpu(mce_enable_ce, (void *)1, 1);
2203 static ssize_t set_cmci_disabled(struct device *s,
2204 struct device_attribute *attr,
2205 const char *buf, size_t size)
2209 if (kstrtou64(buf, 0, &new) < 0)
2212 if (mca_cfg.cmci_disabled ^ !!new) {
2215 on_each_cpu(mce_disable_cmci, NULL, 1);
2216 mca_cfg.cmci_disabled = true;
2219 mca_cfg.cmci_disabled = false;
2220 on_each_cpu(mce_enable_ce, NULL, 1);
2226 static ssize_t store_int_with_restart(struct device *s,
2227 struct device_attribute *attr,
2228 const char *buf, size_t size)
2230 ssize_t ret = device_store_int(s, attr, buf, size);
2235 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2236 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2237 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2238 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2240 static struct dev_ext_attribute dev_attr_check_interval = {
2241 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2245 static struct dev_ext_attribute dev_attr_ignore_ce = {
2246 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2250 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2251 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2252 &mca_cfg.cmci_disabled
2255 static struct device_attribute *mce_device_attrs[] = {
2256 &dev_attr_tolerant.attr,
2257 &dev_attr_check_interval.attr,
2259 &dev_attr_monarch_timeout.attr,
2260 &dev_attr_dont_log_ce.attr,
2261 &dev_attr_ignore_ce.attr,
2262 &dev_attr_cmci_disabled.attr,
2266 static cpumask_var_t mce_device_initialized;
2268 static void mce_device_release(struct device *dev)
2273 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2274 static int mce_device_create(unsigned int cpu)
2280 if (!mce_available(&boot_cpu_data))
2283 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2287 dev->bus = &mce_subsys;
2288 dev->release = &mce_device_release;
2290 err = device_register(dev);
2296 for (i = 0; mce_device_attrs[i]; i++) {
2297 err = device_create_file(dev, mce_device_attrs[i]);
2301 for (j = 0; j < mca_cfg.banks; j++) {
2302 err = device_create_file(dev, &mce_banks[j].attr);
2306 cpumask_set_cpu(cpu, mce_device_initialized);
2307 per_cpu(mce_device, cpu) = dev;
2312 device_remove_file(dev, &mce_banks[j].attr);
2315 device_remove_file(dev, mce_device_attrs[i]);
2317 device_unregister(dev);
2322 static void mce_device_remove(unsigned int cpu)
2324 struct device *dev = per_cpu(mce_device, cpu);
2327 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2330 for (i = 0; mce_device_attrs[i]; i++)
2331 device_remove_file(dev, mce_device_attrs[i]);
2333 for (i = 0; i < mca_cfg.banks; i++)
2334 device_remove_file(dev, &mce_banks[i].attr);
2336 device_unregister(dev);
2337 cpumask_clear_cpu(cpu, mce_device_initialized);
2338 per_cpu(mce_device, cpu) = NULL;
2341 /* Make sure there are no machine checks on offlined CPUs. */
2342 static void mce_disable_cpu(void *h)
2344 unsigned long action = *(unsigned long *)h;
2347 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2350 if (!(action & CPU_TASKS_FROZEN))
2352 for (i = 0; i < mca_cfg.banks; i++) {
2353 struct mce_bank *b = &mce_banks[i];
2356 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2360 static void mce_reenable_cpu(void *h)
2362 unsigned long action = *(unsigned long *)h;
2365 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2368 if (!(action & CPU_TASKS_FROZEN))
2370 for (i = 0; i < mca_cfg.banks; i++) {
2371 struct mce_bank *b = &mce_banks[i];
2374 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2378 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2380 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2382 unsigned int cpu = (unsigned long)hcpu;
2383 struct timer_list *t = &per_cpu(mce_timer, cpu);
2385 switch (action & ~CPU_TASKS_FROZEN) {
2387 mce_device_create(cpu);
2388 if (threshold_cpu_callback)
2389 threshold_cpu_callback(action, cpu);
2392 if (threshold_cpu_callback)
2393 threshold_cpu_callback(action, cpu);
2394 mce_device_remove(cpu);
2395 mce_intel_hcpu_update(cpu);
2397 /* intentionally ignoring frozen here */
2398 if (!(action & CPU_TASKS_FROZEN))
2401 case CPU_DOWN_PREPARE:
2402 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2405 case CPU_DOWN_FAILED:
2406 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2407 mce_start_timer(cpu, t);
2414 static struct notifier_block mce_cpu_notifier = {
2415 .notifier_call = mce_cpu_callback,
2418 static __init void mce_init_banks(void)
2422 for (i = 0; i < mca_cfg.banks; i++) {
2423 struct mce_bank *b = &mce_banks[i];
2424 struct device_attribute *a = &b->attr;
2426 sysfs_attr_init(&a->attr);
2427 a->attr.name = b->attrname;
2428 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2430 a->attr.mode = 0644;
2431 a->show = show_bank;
2432 a->store = set_bank;
2436 static __init int mcheck_init_device(void)
2441 if (!mce_available(&boot_cpu_data)) {
2446 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2453 err = subsys_system_register(&mce_subsys, NULL);
2457 cpu_notifier_register_begin();
2458 for_each_online_cpu(i) {
2459 err = mce_device_create(i);
2462 * Register notifier anyway (and do not unreg it) so
2463 * that we don't leave undeleted timers, see notifier
2466 __register_hotcpu_notifier(&mce_cpu_notifier);
2467 cpu_notifier_register_done();
2468 goto err_device_create;
2472 __register_hotcpu_notifier(&mce_cpu_notifier);
2473 cpu_notifier_register_done();
2475 register_syscore_ops(&mce_syscore_ops);
2477 /* register character device /dev/mcelog */
2478 err = misc_register(&mce_chrdev_device);
2485 unregister_syscore_ops(&mce_syscore_ops);
2489 * We didn't keep track of which devices were created above, but
2490 * even if we had, the set of online cpus might have changed.
2491 * Play safe and remove for every possible cpu, since
2492 * mce_device_remove() will do the right thing.
2494 for_each_possible_cpu(i)
2495 mce_device_remove(i);
2498 free_cpumask_var(mce_device_initialized);
2501 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2505 device_initcall_sync(mcheck_init_device);
2508 * Old style boot options parsing. Only for compatibility.
2510 static int __init mcheck_disable(char *str)
2512 mca_cfg.disabled = true;
2515 __setup("nomce", mcheck_disable);
2517 #ifdef CONFIG_DEBUG_FS
2518 struct dentry *mce_get_debugfs_dir(void)
2520 static struct dentry *dmce;
2523 dmce = debugfs_create_dir("mce", NULL);
2528 static void mce_reset(void)
2531 atomic_set(&mce_fake_panicked, 0);
2532 atomic_set(&mce_executing, 0);
2533 atomic_set(&mce_callin, 0);
2534 atomic_set(&global_nwo, 0);
2537 static int fake_panic_get(void *data, u64 *val)
2543 static int fake_panic_set(void *data, u64 val)
2550 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2551 fake_panic_set, "%llu\n");
2553 static int __init mcheck_debugfs_init(void)
2555 struct dentry *dmce, *ffake_panic;
2557 dmce = mce_get_debugfs_dir();
2560 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2568 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2571 static int __init mcheck_late_init(void)
2573 mcheck_debugfs_init();
2576 * Flush out everything that has been logged during early boot, now that
2577 * everything has been initialized (workqueues, decoders, ...).
2579 mce_schedule_work();
2583 late_initcall(mcheck_late_init);