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>
49 #include "mce-internal.h"
51 static DEFINE_MUTEX(mce_chrdev_read_mutex);
53 #define rcu_dereference_check_mce(p) \
54 rcu_dereference_index_check((p), \
55 rcu_read_lock_sched_held() || \
56 lockdep_is_held(&mce_chrdev_read_mutex))
58 #define CREATE_TRACE_POINTS
59 #include <trace/events/mce.h>
61 #define SPINUNIT 100 /* 100ns */
65 DEFINE_PER_CPU(unsigned, mce_exception_count);
67 struct mce_bank *mce_banks __read_mostly;
69 struct mca_config mca_cfg __read_mostly = {
73 * 0: always panic on uncorrected errors, log corrected errors
74 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
75 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
76 * 3: never panic or SIGBUS, log all errors (for testing only)
82 /* User mode helper program triggered by machine check event */
83 static unsigned long mce_need_notify;
84 static char mce_helper[128];
85 static char *mce_helper_argv[2] = { mce_helper, NULL };
87 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
89 static DEFINE_PER_CPU(struct mce, mces_seen);
90 static int cpu_missing;
92 /* CMCI storm detection filter */
93 static DEFINE_PER_CPU(unsigned long, mce_polled_error);
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 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;
157 /* Emit the trace record: */
158 trace_mce_record(mce);
160 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, mce);
161 if (ret == NOTIFY_STOP)
167 entry = rcu_dereference_check_mce(mcelog.next);
171 * When the buffer fills up discard new entries.
172 * Assume that the earlier errors are the more
175 if (entry >= MCE_LOG_LEN) {
176 set_bit(MCE_OVERFLOW,
177 (unsigned long *)&mcelog.flags);
180 /* Old left over entry. Skip: */
181 if (mcelog.entry[entry].finished) {
189 if (cmpxchg(&mcelog.next, entry, next) == entry)
192 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
194 mcelog.entry[entry].finished = 1;
198 set_bit(0, &mce_need_notify);
201 static void drain_mcelog_buffer(void)
203 unsigned int next, i, prev = 0;
205 next = ACCESS_ONCE(mcelog.next);
210 /* drain what was logged during boot */
211 for (i = prev; i < next; i++) {
212 unsigned long start = jiffies;
213 unsigned retries = 1;
215 m = &mcelog.entry[i];
217 while (!m->finished) {
218 if (time_after_eq(jiffies, start + 2*retries))
223 if (!m->finished && retries >= 4) {
224 pr_err("skipping error being logged currently!\n");
229 atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
232 memset(mcelog.entry + prev, 0, (next - prev) * sizeof(*m));
234 next = cmpxchg(&mcelog.next, prev, 0);
235 } while (next != prev);
239 void mce_register_decode_chain(struct notifier_block *nb)
241 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
242 drain_mcelog_buffer();
244 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
246 void mce_unregister_decode_chain(struct notifier_block *nb)
248 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
250 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
252 static void print_mce(struct mce *m)
256 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
257 m->extcpu, m->mcgstatus, m->bank, m->status);
260 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
261 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
264 if (m->cs == __KERNEL_CS)
265 print_symbol("{%s}", m->ip);
269 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
271 pr_cont("ADDR %llx ", m->addr);
273 pr_cont("MISC %llx ", m->misc);
277 * Note this output is parsed by external tools and old fields
278 * should not be changed.
280 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
281 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
282 cpu_data(m->extcpu).microcode);
285 * Print out human-readable details about the MCE error,
286 * (if the CPU has an implementation for that)
288 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
289 if (ret == NOTIFY_STOP)
292 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
295 #define PANIC_TIMEOUT 5 /* 5 seconds */
297 static atomic_t mce_paniced;
299 static int fake_panic;
300 static atomic_t mce_fake_paniced;
302 /* Panic in progress. Enable interrupts and wait for final IPI */
303 static void wait_for_panic(void)
305 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
309 while (timeout-- > 0)
311 if (panic_timeout == 0)
312 panic_timeout = mca_cfg.panic_timeout;
313 panic("Panicing machine check CPU died");
316 static void mce_panic(char *msg, struct mce *final, char *exp)
322 * Make sure only one CPU runs in machine check panic
324 if (atomic_inc_return(&mce_paniced) > 1)
331 /* Don't log too much for fake panic */
332 if (atomic_inc_return(&mce_fake_paniced) > 1)
335 /* First print corrected ones that are still unlogged */
336 for (i = 0; i < MCE_LOG_LEN; i++) {
337 struct mce *m = &mcelog.entry[i];
338 if (!(m->status & MCI_STATUS_VAL))
340 if (!(m->status & MCI_STATUS_UC)) {
343 apei_err = apei_write_mce(m);
346 /* Now print uncorrected but with the final one last */
347 for (i = 0; i < MCE_LOG_LEN; i++) {
348 struct mce *m = &mcelog.entry[i];
349 if (!(m->status & MCI_STATUS_VAL))
351 if (!(m->status & MCI_STATUS_UC))
353 if (!final || memcmp(m, final, sizeof(struct mce))) {
356 apei_err = apei_write_mce(m);
362 apei_err = apei_write_mce(final);
365 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
367 pr_emerg(HW_ERR "Machine check: %s\n", exp);
369 if (panic_timeout == 0)
370 panic_timeout = mca_cfg.panic_timeout;
373 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
376 /* Support code for software error injection */
378 static int msr_to_offset(u32 msr)
380 unsigned bank = __this_cpu_read(injectm.bank);
382 if (msr == mca_cfg.rip_msr)
383 return offsetof(struct mce, ip);
384 if (msr == MSR_IA32_MCx_STATUS(bank))
385 return offsetof(struct mce, status);
386 if (msr == MSR_IA32_MCx_ADDR(bank))
387 return offsetof(struct mce, addr);
388 if (msr == MSR_IA32_MCx_MISC(bank))
389 return offsetof(struct mce, misc);
390 if (msr == MSR_IA32_MCG_STATUS)
391 return offsetof(struct mce, mcgstatus);
395 /* MSR access wrappers used for error injection */
396 static u64 mce_rdmsrl(u32 msr)
400 if (__this_cpu_read(injectm.finished)) {
401 int offset = msr_to_offset(msr);
405 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
408 if (rdmsrl_safe(msr, &v)) {
409 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
411 * Return zero in case the access faulted. This should
412 * not happen normally but can happen if the CPU does
413 * something weird, or if the code is buggy.
421 static void mce_wrmsrl(u32 msr, u64 v)
423 if (__this_cpu_read(injectm.finished)) {
424 int offset = msr_to_offset(msr);
427 *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
434 * Collect all global (w.r.t. this processor) status about this machine
435 * check into our "mce" struct so that we can use it later to assess
436 * the severity of the problem as we read per-bank specific details.
438 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
442 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
445 * Get the address of the instruction at the time of
446 * the machine check error.
448 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
453 * When in VM86 mode make the cs look like ring 3
454 * always. This is a lie, but it's better than passing
455 * the additional vm86 bit around everywhere.
457 if (v8086_mode(regs))
460 /* Use accurate RIP reporting if available. */
462 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
467 * Simple lockless ring to communicate PFNs from the exception handler with the
468 * process context work function. This is vastly simplified because there's
469 * only a single reader and a single writer.
471 #define MCE_RING_SIZE 16 /* we use one entry less */
474 unsigned short start;
476 unsigned long ring[MCE_RING_SIZE];
478 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
480 /* Runs with CPU affinity in workqueue */
481 static int mce_ring_empty(void)
483 struct mce_ring *r = &__get_cpu_var(mce_ring);
485 return r->start == r->end;
488 static int mce_ring_get(unsigned long *pfn)
495 r = &__get_cpu_var(mce_ring);
496 if (r->start == r->end)
498 *pfn = r->ring[r->start];
499 r->start = (r->start + 1) % MCE_RING_SIZE;
506 /* Always runs in MCE context with preempt off */
507 static int mce_ring_add(unsigned long pfn)
509 struct mce_ring *r = &__get_cpu_var(mce_ring);
512 next = (r->end + 1) % MCE_RING_SIZE;
513 if (next == r->start)
515 r->ring[r->end] = pfn;
521 int mce_available(struct cpuinfo_x86 *c)
523 if (mca_cfg.disabled)
525 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
528 static void mce_schedule_work(void)
530 if (!mce_ring_empty())
531 schedule_work(&__get_cpu_var(mce_work));
534 DEFINE_PER_CPU(struct irq_work, mce_irq_work);
536 static void mce_irq_work_cb(struct irq_work *entry)
542 static void mce_report_event(struct pt_regs *regs)
544 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
547 * Triggering the work queue here is just an insurance
548 * policy in case the syscall exit notify handler
549 * doesn't run soon enough or ends up running on the
550 * wrong CPU (can happen when audit sleeps)
556 irq_work_queue(&__get_cpu_var(mce_irq_work));
560 * Read ADDR and MISC registers.
562 static void mce_read_aux(struct mce *m, int i)
564 if (m->status & MCI_STATUS_MISCV)
565 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
566 if (m->status & MCI_STATUS_ADDRV) {
567 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
570 * Mask the reported address by the reported granularity.
572 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
573 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
580 DEFINE_PER_CPU(unsigned, mce_poll_count);
583 * Poll for corrected events or events that happened before reset.
584 * Those are just logged through /dev/mcelog.
586 * This is executed in standard interrupt context.
588 * Note: spec recommends to panic for fatal unsignalled
589 * errors here. However this would be quite problematic --
590 * we would need to reimplement the Monarch handling and
591 * it would mess up the exclusion between exception handler
592 * and poll hander -- * so we skip this for now.
593 * These cases should not happen anyways, or only when the CPU
594 * is already totally * confused. In this case it's likely it will
595 * not fully execute the machine check handler either.
597 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
603 this_cpu_inc(mce_poll_count);
605 mce_gather_info(&m, NULL);
607 for (i = 0; i < mca_cfg.banks; i++) {
608 if (!mce_banks[i].ctl || !test_bit(i, *b))
617 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
618 if (!(m.status & MCI_STATUS_VAL))
621 v = &get_cpu_var(mce_polled_error);
624 * Uncorrected or signalled events are handled by the exception
625 * handler when it is enabled, so don't process those here.
627 * TBD do the same check for MCI_STATUS_EN here?
629 if (!(flags & MCP_UC) &&
630 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
635 if (!(flags & MCP_TIMESTAMP))
638 * Don't get the IP here because it's unlikely to
639 * have anything to do with the actual error location.
641 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
645 * Clear state for this bank.
647 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
651 * Don't clear MCG_STATUS here because it's only defined for
657 EXPORT_SYMBOL_GPL(machine_check_poll);
660 * Do a quick check if any of the events requires a panic.
661 * This decides if we keep the events around or clear them.
663 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
664 struct pt_regs *regs)
668 for (i = 0; i < mca_cfg.banks; i++) {
669 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
670 if (m->status & MCI_STATUS_VAL) {
671 __set_bit(i, validp);
672 if (quirk_no_way_out)
673 quirk_no_way_out(i, m, regs);
675 if (mce_severity(m, mca_cfg.tolerant, msg) >= MCE_PANIC_SEVERITY)
682 * Variable to establish order between CPUs while scanning.
683 * Each CPU spins initially until executing is equal its number.
685 static atomic_t mce_executing;
688 * Defines order of CPUs on entry. First CPU becomes Monarch.
690 static atomic_t mce_callin;
693 * Check if a timeout waiting for other CPUs happened.
695 static int mce_timed_out(u64 *t)
698 * The others already did panic for some reason.
699 * Bail out like in a timeout.
700 * rmb() to tell the compiler that system_state
701 * might have been modified by someone else.
704 if (atomic_read(&mce_paniced))
706 if (!mca_cfg.monarch_timeout)
708 if ((s64)*t < SPINUNIT) {
709 /* CHECKME: Make panic default for 1 too? */
710 if (mca_cfg.tolerant < 1)
711 mce_panic("Timeout synchronizing machine check over CPUs",
718 touch_nmi_watchdog();
723 * The Monarch's reign. The Monarch is the CPU who entered
724 * the machine check handler first. It waits for the others to
725 * raise the exception too and then grades them. When any
726 * error is fatal panic. Only then let the others continue.
728 * The other CPUs entering the MCE handler will be controlled by the
729 * Monarch. They are called Subjects.
731 * This way we prevent any potential data corruption in a unrecoverable case
732 * and also makes sure always all CPU's errors are examined.
734 * Also this detects the case of a machine check event coming from outer
735 * space (not detected by any CPUs) In this case some external agent wants
736 * us to shut down, so panic too.
738 * The other CPUs might still decide to panic if the handler happens
739 * in a unrecoverable place, but in this case the system is in a semi-stable
740 * state and won't corrupt anything by itself. It's ok to let the others
741 * continue for a bit first.
743 * All the spin loops have timeouts; when a timeout happens a CPU
744 * typically elects itself to be Monarch.
746 static void mce_reign(void)
749 struct mce *m = NULL;
750 int global_worst = 0;
755 * This CPU is the Monarch and the other CPUs have run
756 * through their handlers.
757 * Grade the severity of the errors of all the CPUs.
759 for_each_possible_cpu(cpu) {
760 int severity = mce_severity(&per_cpu(mces_seen, cpu),
763 if (severity > global_worst) {
765 global_worst = severity;
766 m = &per_cpu(mces_seen, cpu);
771 * Cannot recover? Panic here then.
772 * This dumps all the mces in the log buffer and stops the
775 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
776 mce_panic("Fatal Machine check", m, msg);
779 * For UC somewhere we let the CPU who detects it handle it.
780 * Also must let continue the others, otherwise the handling
781 * CPU could deadlock on a lock.
785 * No machine check event found. Must be some external
786 * source or one CPU is hung. Panic.
788 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
789 mce_panic("Machine check from unknown source", NULL, NULL);
792 * Now clear all the mces_seen so that they don't reappear on
795 for_each_possible_cpu(cpu)
796 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
799 static atomic_t global_nwo;
802 * Start of Monarch synchronization. This waits until all CPUs have
803 * entered the exception handler and then determines if any of them
804 * saw a fatal event that requires panic. Then it executes them
805 * in the entry order.
806 * TBD double check parallel CPU hotunplug
808 static int mce_start(int *no_way_out)
811 int cpus = num_online_cpus();
812 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
817 atomic_add(*no_way_out, &global_nwo);
819 * global_nwo should be updated before mce_callin
822 order = atomic_inc_return(&mce_callin);
827 while (atomic_read(&mce_callin) != cpus) {
828 if (mce_timed_out(&timeout)) {
829 atomic_set(&global_nwo, 0);
836 * mce_callin should be read before global_nwo
842 * Monarch: Starts executing now, the others wait.
844 atomic_set(&mce_executing, 1);
847 * Subject: Now start the scanning loop one by one in
848 * the original callin order.
849 * This way when there are any shared banks it will be
850 * only seen by one CPU before cleared, avoiding duplicates.
852 while (atomic_read(&mce_executing) < order) {
853 if (mce_timed_out(&timeout)) {
854 atomic_set(&global_nwo, 0);
862 * Cache the global no_way_out state.
864 *no_way_out = atomic_read(&global_nwo);
870 * Synchronize between CPUs after main scanning loop.
871 * This invokes the bulk of the Monarch processing.
873 static int mce_end(int order)
876 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
884 * Allow others to run.
886 atomic_inc(&mce_executing);
889 /* CHECKME: Can this race with a parallel hotplug? */
890 int cpus = num_online_cpus();
893 * Monarch: Wait for everyone to go through their scanning
896 while (atomic_read(&mce_executing) <= cpus) {
897 if (mce_timed_out(&timeout))
907 * Subject: Wait for Monarch to finish.
909 while (atomic_read(&mce_executing) != 0) {
910 if (mce_timed_out(&timeout))
916 * Don't reset anything. That's done by the Monarch.
922 * Reset all global state.
925 atomic_set(&global_nwo, 0);
926 atomic_set(&mce_callin, 0);
930 * Let others run again.
932 atomic_set(&mce_executing, 0);
937 * Check if the address reported by the CPU is in a format we can parse.
938 * It would be possible to add code for most other cases, but all would
939 * be somewhat complicated (e.g. segment offset would require an instruction
940 * parser). So only support physical addresses up to page granuality for now.
942 static int mce_usable_address(struct mce *m)
944 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
946 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
948 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
953 static void mce_clear_state(unsigned long *toclear)
957 for (i = 0; i < mca_cfg.banks; i++) {
958 if (test_bit(i, toclear))
959 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
964 * Need to save faulting physical address associated with a process
965 * in the machine check handler some place where we can grab it back
966 * later in mce_notify_process()
968 #define MCE_INFO_MAX 16
972 struct task_struct *t;
975 } mce_info[MCE_INFO_MAX];
977 static void mce_save_info(__u64 addr, int c)
981 for (mi = mce_info; mi < &mce_info[MCE_INFO_MAX]; mi++) {
982 if (atomic_cmpxchg(&mi->inuse, 0, 1) == 0) {
990 mce_panic("Too many concurrent recoverable errors", NULL, NULL);
993 static struct mce_info *mce_find_info(void)
997 for (mi = mce_info; mi < &mce_info[MCE_INFO_MAX]; mi++)
998 if (atomic_read(&mi->inuse) && mi->t == current)
1003 static void mce_clear_info(struct mce_info *mi)
1005 atomic_set(&mi->inuse, 0);
1009 * The actual machine check handler. This only handles real
1010 * exceptions when something got corrupted coming in through int 18.
1012 * This is executed in NMI context not subject to normal locking rules. This
1013 * implies that most kernel services cannot be safely used. Don't even
1014 * think about putting a printk in there!
1016 * On Intel systems this is entered on all CPUs in parallel through
1017 * MCE broadcast. However some CPUs might be broken beyond repair,
1018 * so be always careful when synchronizing with others.
1020 void do_machine_check(struct pt_regs *regs, long error_code)
1022 struct mca_config *cfg = &mca_cfg;
1023 struct mce m, *final;
1028 * Establish sequential order between the CPUs entering the machine
1033 * If no_way_out gets set, there is no safe way to recover from this
1034 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1038 * If kill_it gets set, there might be a way to recover from this
1042 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1043 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1044 char *msg = "Unknown";
1046 atomic_inc(&mce_entry);
1048 this_cpu_inc(mce_exception_count);
1053 mce_gather_info(&m, regs);
1055 final = &__get_cpu_var(mces_seen);
1058 memset(valid_banks, 0, sizeof(valid_banks));
1059 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1064 * When no restart IP might need to kill or panic.
1065 * Assume the worst for now, but if we find the
1066 * severity is MCE_AR_SEVERITY we have other options.
1068 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1072 * Go through all the banks in exclusion of the other CPUs.
1073 * This way we don't report duplicated events on shared banks
1074 * because the first one to see it will clear it.
1076 order = mce_start(&no_way_out);
1077 for (i = 0; i < cfg->banks; i++) {
1078 __clear_bit(i, toclear);
1079 if (!test_bit(i, valid_banks))
1081 if (!mce_banks[i].ctl)
1088 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1089 if ((m.status & MCI_STATUS_VAL) == 0)
1093 * Non uncorrected or non signaled errors are handled by
1094 * machine_check_poll. Leave them alone, unless this panics.
1096 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1101 * Set taint even when machine check was not enabled.
1103 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1105 severity = mce_severity(&m, cfg->tolerant, NULL);
1108 * When machine check was for corrected handler don't touch,
1109 * unless we're panicing.
1111 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
1113 __set_bit(i, toclear);
1114 if (severity == MCE_NO_SEVERITY) {
1116 * Machine check event was not enabled. Clear, but
1122 mce_read_aux(&m, i);
1125 * Action optional error. Queue address for later processing.
1126 * When the ring overflows we just ignore the AO error.
1127 * RED-PEN add some logging mechanism when
1128 * usable_address or mce_add_ring fails.
1129 * RED-PEN don't ignore overflow for mca_cfg.tolerant == 0
1131 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1132 mce_ring_add(m.addr >> PAGE_SHIFT);
1136 if (severity > worst) {
1142 /* mce_clear_state will clear *final, save locally for use later */
1146 mce_clear_state(toclear);
1149 * Do most of the synchronization with other CPUs.
1150 * When there's any problem use only local no_way_out state.
1152 if (mce_end(order) < 0)
1153 no_way_out = worst >= MCE_PANIC_SEVERITY;
1156 * At insane "tolerant" levels we take no action. Otherwise
1157 * we only die if we have no other choice. For less serious
1158 * issues we try to recover, or limit damage to the current
1161 if (cfg->tolerant < 3) {
1163 mce_panic("Fatal machine check on current CPU", &m, msg);
1164 if (worst == MCE_AR_SEVERITY) {
1165 /* schedule action before return to userland */
1166 mce_save_info(m.addr, m.mcgstatus & MCG_STATUS_RIPV);
1167 set_thread_flag(TIF_MCE_NOTIFY);
1168 } else if (kill_it) {
1169 force_sig(SIGBUS, current);
1174 mce_report_event(regs);
1175 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1177 atomic_dec(&mce_entry);
1180 EXPORT_SYMBOL_GPL(do_machine_check);
1182 #ifndef CONFIG_MEMORY_FAILURE
1183 int memory_failure(unsigned long pfn, int vector, int flags)
1185 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1186 BUG_ON(flags & MF_ACTION_REQUIRED);
1187 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1188 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1196 * Called in process context that interrupted by MCE and marked with
1197 * TIF_MCE_NOTIFY, just before returning to erroneous userland.
1198 * This code is allowed to sleep.
1199 * Attempt possible recovery such as calling the high level VM handler to
1200 * process any corrupted pages, and kill/signal current process if required.
1201 * Action required errors are handled here.
1203 void mce_notify_process(void)
1206 struct mce_info *mi = mce_find_info();
1207 int flags = MF_ACTION_REQUIRED;
1210 mce_panic("Lost physical address for unconsumed uncorrectable error", NULL, NULL);
1211 pfn = mi->paddr >> PAGE_SHIFT;
1213 clear_thread_flag(TIF_MCE_NOTIFY);
1215 pr_err("Uncorrected hardware memory error in user-access at %llx",
1218 * We must call memory_failure() here even if the current process is
1219 * doomed. We still need to mark the page as poisoned and alert any
1220 * other users of the page.
1222 if (!mi->restartable)
1223 flags |= MF_MUST_KILL;
1224 if (memory_failure(pfn, MCE_VECTOR, flags) < 0) {
1225 pr_err("Memory error not recovered");
1226 force_sig(SIGBUS, current);
1232 * Action optional processing happens here (picking up
1233 * from the list of faulting pages that do_machine_check()
1234 * placed into the "ring").
1236 static void mce_process_work(struct work_struct *dummy)
1240 while (mce_ring_get(&pfn))
1241 memory_failure(pfn, MCE_VECTOR, 0);
1244 #ifdef CONFIG_X86_MCE_INTEL
1246 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1247 * @cpu: The CPU on which the event occurred.
1248 * @status: Event status information
1250 * This function should be called by the thermal interrupt after the
1251 * event has been processed and the decision was made to log the event
1254 * The status parameter will be saved to the 'status' field of 'struct mce'
1255 * and historically has been the register value of the
1256 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1258 void mce_log_therm_throt_event(__u64 status)
1263 m.bank = MCE_THERMAL_BANK;
1267 #endif /* CONFIG_X86_MCE_INTEL */
1270 * Periodic polling timer for "silent" machine check errors. If the
1271 * poller finds an MCE, poll 2x faster. When the poller finds no more
1272 * errors, poll 2x slower (up to check_interval seconds).
1274 static unsigned long check_interval = 5 * 60; /* 5 minutes */
1276 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1277 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1279 static unsigned long mce_adjust_timer_default(unsigned long interval)
1284 static unsigned long (*mce_adjust_timer)(unsigned long interval) =
1285 mce_adjust_timer_default;
1287 static int cmc_error_seen(void)
1289 unsigned long *v = &__get_cpu_var(mce_polled_error);
1291 return test_and_clear_bit(0, v);
1294 static void mce_timer_fn(unsigned long data)
1296 struct timer_list *t = &__get_cpu_var(mce_timer);
1300 WARN_ON(smp_processor_id() != data);
1302 if (mce_available(__this_cpu_ptr(&cpu_info))) {
1303 machine_check_poll(MCP_TIMESTAMP,
1304 &__get_cpu_var(mce_poll_banks));
1305 mce_intel_cmci_poll();
1309 * Alert userspace if needed. If we logged an MCE, reduce the
1310 * polling interval, otherwise increase the polling interval.
1312 iv = __this_cpu_read(mce_next_interval);
1313 notify = mce_notify_irq();
1314 notify |= cmc_error_seen();
1316 iv = max(iv / 2, (unsigned long) HZ/100);
1318 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1319 iv = mce_adjust_timer(iv);
1321 __this_cpu_write(mce_next_interval, iv);
1322 /* Might have become 0 after CMCI storm subsided */
1324 t->expires = jiffies + iv;
1325 add_timer_on(t, smp_processor_id());
1330 * Ensure that the timer is firing in @interval from now.
1332 void mce_timer_kick(unsigned long interval)
1334 struct timer_list *t = &__get_cpu_var(mce_timer);
1335 unsigned long when = jiffies + interval;
1336 unsigned long iv = __this_cpu_read(mce_next_interval);
1338 if (timer_pending(t)) {
1339 if (time_before(when, t->expires))
1340 mod_timer_pinned(t, when);
1342 t->expires = round_jiffies(when);
1343 add_timer_on(t, smp_processor_id());
1346 __this_cpu_write(mce_next_interval, interval);
1349 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1350 static void mce_timer_delete_all(void)
1354 for_each_online_cpu(cpu)
1355 del_timer_sync(&per_cpu(mce_timer, cpu));
1358 static void mce_do_trigger(struct work_struct *work)
1360 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1363 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1366 * Notify the user(s) about new machine check events.
1367 * Can be called from interrupt context, but not from machine check/NMI
1370 int mce_notify_irq(void)
1372 /* Not more than two messages every minute */
1373 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1375 if (test_and_clear_bit(0, &mce_need_notify)) {
1376 /* wake processes polling /dev/mcelog */
1377 wake_up_interruptible(&mce_chrdev_wait);
1380 schedule_work(&mce_trigger_work);
1382 if (__ratelimit(&ratelimit))
1383 pr_info(HW_ERR "Machine check events logged\n");
1389 EXPORT_SYMBOL_GPL(mce_notify_irq);
1391 static int __mcheck_cpu_mce_banks_init(void)
1394 u8 num_banks = mca_cfg.banks;
1396 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1400 for (i = 0; i < num_banks; i++) {
1401 struct mce_bank *b = &mce_banks[i];
1410 * Initialize Machine Checks for a CPU.
1412 static int __mcheck_cpu_cap_init(void)
1417 rdmsrl(MSR_IA32_MCG_CAP, cap);
1419 b = cap & MCG_BANKCNT_MASK;
1421 pr_info("CPU supports %d MCE banks\n", b);
1423 if (b > MAX_NR_BANKS) {
1424 pr_warn("Using only %u machine check banks out of %u\n",
1429 /* Don't support asymmetric configurations today */
1430 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1434 int err = __mcheck_cpu_mce_banks_init();
1440 /* Use accurate RIP reporting if available. */
1441 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1442 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1444 if (cap & MCG_SER_P)
1450 static void __mcheck_cpu_init_generic(void)
1452 enum mcp_flags m_fl = 0;
1453 mce_banks_t all_banks;
1457 if (!mca_cfg.bootlog)
1461 * Log the machine checks left over from the previous reset.
1463 bitmap_fill(all_banks, MAX_NR_BANKS);
1464 machine_check_poll(MCP_UC | m_fl, &all_banks);
1466 set_in_cr4(X86_CR4_MCE);
1468 rdmsrl(MSR_IA32_MCG_CAP, cap);
1469 if (cap & MCG_CTL_P)
1470 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1472 for (i = 0; i < mca_cfg.banks; i++) {
1473 struct mce_bank *b = &mce_banks[i];
1477 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1478 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1483 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1484 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1485 * Vol 3B Table 15-20). But this confuses both the code that determines
1486 * whether the machine check occurred in kernel or user mode, and also
1487 * the severity assessment code. Pretend that EIPV was set, and take the
1488 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1490 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1494 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1496 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1497 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1498 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1500 (MCI_STATUS_UC|MCI_STATUS_EN|
1501 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1502 MCI_STATUS_AR|MCACOD_INSTR))
1505 m->mcgstatus |= MCG_STATUS_EIPV;
1510 /* Add per CPU specific workarounds here */
1511 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1513 struct mca_config *cfg = &mca_cfg;
1515 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1516 pr_info("unknown CPU type - not enabling MCE support\n");
1520 /* This should be disabled by the BIOS, but isn't always */
1521 if (c->x86_vendor == X86_VENDOR_AMD) {
1522 if (c->x86 == 15 && cfg->banks > 4) {
1524 * disable GART TBL walk error reporting, which
1525 * trips off incorrectly with the IOMMU & 3ware
1528 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1530 if (c->x86 <= 17 && cfg->bootlog < 0) {
1532 * Lots of broken BIOS around that don't clear them
1533 * by default and leave crap in there. Don't log:
1538 * Various K7s with broken bank 0 around. Always disable
1541 if (c->x86 == 6 && cfg->banks > 0)
1542 mce_banks[0].ctl = 0;
1545 * Turn off MC4_MISC thresholding banks on those models since
1546 * they're not supported there.
1548 if (c->x86 == 0x15 &&
1549 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1554 0x00000413, /* MC4_MISC0 */
1555 0xc0000408, /* MC4_MISC1 */
1558 rdmsrl(MSR_K7_HWCR, hwcr);
1560 /* McStatusWrEn has to be set */
1561 need_toggle = !(hwcr & BIT(18));
1564 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1566 for (i = 0; i < ARRAY_SIZE(msrs); i++) {
1567 rdmsrl(msrs[i], val);
1570 if (val & BIT_64(62)) {
1572 wrmsrl(msrs[i], val);
1576 /* restore old settings */
1578 wrmsrl(MSR_K7_HWCR, hwcr);
1582 if (c->x86_vendor == X86_VENDOR_INTEL) {
1584 * SDM documents that on family 6 bank 0 should not be written
1585 * because it aliases to another special BIOS controlled
1587 * But it's not aliased anymore on model 0x1a+
1588 * Don't ignore bank 0 completely because there could be a
1589 * valid event later, merely don't write CTL0.
1592 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1593 mce_banks[0].init = 0;
1596 * All newer Intel systems support MCE broadcasting. Enable
1597 * synchronization with a one second timeout.
1599 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1600 cfg->monarch_timeout < 0)
1601 cfg->monarch_timeout = USEC_PER_SEC;
1604 * There are also broken BIOSes on some Pentium M and
1607 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1610 if (c->x86 == 6 && c->x86_model == 45)
1611 quirk_no_way_out = quirk_sandybridge_ifu;
1613 if (cfg->monarch_timeout < 0)
1614 cfg->monarch_timeout = 0;
1615 if (cfg->bootlog != 0)
1616 cfg->panic_timeout = 30;
1621 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1626 switch (c->x86_vendor) {
1627 case X86_VENDOR_INTEL:
1628 intel_p5_mcheck_init(c);
1631 case X86_VENDOR_CENTAUR:
1632 winchip_mcheck_init(c);
1640 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1642 switch (c->x86_vendor) {
1643 case X86_VENDOR_INTEL:
1644 mce_intel_feature_init(c);
1645 mce_adjust_timer = mce_intel_adjust_timer;
1647 case X86_VENDOR_AMD:
1648 mce_amd_feature_init(c);
1655 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1657 unsigned long iv = check_interval * HZ;
1659 if (mca_cfg.ignore_ce || !iv)
1662 per_cpu(mce_next_interval, cpu) = iv;
1664 t->expires = round_jiffies(jiffies + iv);
1665 add_timer_on(t, cpu);
1668 static void __mcheck_cpu_init_timer(void)
1670 struct timer_list *t = &__get_cpu_var(mce_timer);
1671 unsigned int cpu = smp_processor_id();
1673 setup_timer(t, mce_timer_fn, cpu);
1674 mce_start_timer(cpu, t);
1677 /* Handle unconfigured int18 (should never happen) */
1678 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1680 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1681 smp_processor_id());
1684 /* Call the installed machine check handler for this CPU setup. */
1685 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1686 unexpected_machine_check;
1689 * Called for each booted CPU to set up machine checks.
1690 * Must be called with preempt off:
1692 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1694 if (mca_cfg.disabled)
1697 if (__mcheck_cpu_ancient_init(c))
1700 if (!mce_available(c))
1703 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1704 mca_cfg.disabled = true;
1708 machine_check_vector = do_machine_check;
1710 __mcheck_cpu_init_generic();
1711 __mcheck_cpu_init_vendor(c);
1712 __mcheck_cpu_init_timer();
1713 INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1714 init_irq_work(&__get_cpu_var(mce_irq_work), &mce_irq_work_cb);
1718 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1721 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1722 static int mce_chrdev_open_count; /* #times opened */
1723 static int mce_chrdev_open_exclu; /* already open exclusive? */
1725 static int mce_chrdev_open(struct inode *inode, struct file *file)
1727 spin_lock(&mce_chrdev_state_lock);
1729 if (mce_chrdev_open_exclu ||
1730 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1731 spin_unlock(&mce_chrdev_state_lock);
1736 if (file->f_flags & O_EXCL)
1737 mce_chrdev_open_exclu = 1;
1738 mce_chrdev_open_count++;
1740 spin_unlock(&mce_chrdev_state_lock);
1742 return nonseekable_open(inode, file);
1745 static int mce_chrdev_release(struct inode *inode, struct file *file)
1747 spin_lock(&mce_chrdev_state_lock);
1749 mce_chrdev_open_count--;
1750 mce_chrdev_open_exclu = 0;
1752 spin_unlock(&mce_chrdev_state_lock);
1757 static void collect_tscs(void *data)
1759 unsigned long *cpu_tsc = (unsigned long *)data;
1761 rdtscll(cpu_tsc[smp_processor_id()]);
1764 static int mce_apei_read_done;
1766 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1767 static int __mce_read_apei(char __user **ubuf, size_t usize)
1773 if (usize < sizeof(struct mce))
1776 rc = apei_read_mce(&m, &record_id);
1777 /* Error or no more MCE record */
1779 mce_apei_read_done = 1;
1781 * When ERST is disabled, mce_chrdev_read() should return
1782 * "no record" instead of "no device."
1789 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1792 * In fact, we should have cleared the record after that has
1793 * been flushed to the disk or sent to network in
1794 * /sbin/mcelog, but we have no interface to support that now,
1795 * so just clear it to avoid duplication.
1797 rc = apei_clear_mce(record_id);
1799 mce_apei_read_done = 1;
1802 *ubuf += sizeof(struct mce);
1807 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1808 size_t usize, loff_t *off)
1810 char __user *buf = ubuf;
1811 unsigned long *cpu_tsc;
1812 unsigned prev, next;
1815 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1819 mutex_lock(&mce_chrdev_read_mutex);
1821 if (!mce_apei_read_done) {
1822 err = __mce_read_apei(&buf, usize);
1823 if (err || buf != ubuf)
1827 next = rcu_dereference_check_mce(mcelog.next);
1829 /* Only supports full reads right now */
1831 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1837 for (i = prev; i < next; i++) {
1838 unsigned long start = jiffies;
1839 struct mce *m = &mcelog.entry[i];
1841 while (!m->finished) {
1842 if (time_after_eq(jiffies, start + 2)) {
1843 memset(m, 0, sizeof(*m));
1849 err |= copy_to_user(buf, m, sizeof(*m));
1855 memset(mcelog.entry + prev, 0,
1856 (next - prev) * sizeof(struct mce));
1858 next = cmpxchg(&mcelog.next, prev, 0);
1859 } while (next != prev);
1861 synchronize_sched();
1864 * Collect entries that were still getting written before the
1867 on_each_cpu(collect_tscs, cpu_tsc, 1);
1869 for (i = next; i < MCE_LOG_LEN; i++) {
1870 struct mce *m = &mcelog.entry[i];
1872 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1873 err |= copy_to_user(buf, m, sizeof(*m));
1876 memset(m, 0, sizeof(*m));
1884 mutex_unlock(&mce_chrdev_read_mutex);
1887 return err ? err : buf - ubuf;
1890 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1892 poll_wait(file, &mce_chrdev_wait, wait);
1893 if (rcu_access_index(mcelog.next))
1894 return POLLIN | POLLRDNORM;
1895 if (!mce_apei_read_done && apei_check_mce())
1896 return POLLIN | POLLRDNORM;
1900 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1903 int __user *p = (int __user *)arg;
1905 if (!capable(CAP_SYS_ADMIN))
1909 case MCE_GET_RECORD_LEN:
1910 return put_user(sizeof(struct mce), p);
1911 case MCE_GET_LOG_LEN:
1912 return put_user(MCE_LOG_LEN, p);
1913 case MCE_GETCLEAR_FLAGS: {
1917 flags = mcelog.flags;
1918 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1920 return put_user(flags, p);
1927 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1928 size_t usize, loff_t *off);
1930 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1931 const char __user *ubuf,
1932 size_t usize, loff_t *off))
1936 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1938 ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1939 size_t usize, loff_t *off)
1942 return mce_write(filp, ubuf, usize, off);
1947 static const struct file_operations mce_chrdev_ops = {
1948 .open = mce_chrdev_open,
1949 .release = mce_chrdev_release,
1950 .read = mce_chrdev_read,
1951 .write = mce_chrdev_write,
1952 .poll = mce_chrdev_poll,
1953 .unlocked_ioctl = mce_chrdev_ioctl,
1954 .llseek = no_llseek,
1957 static struct miscdevice mce_chrdev_device = {
1963 static void __mce_disable_bank(void *arg)
1965 int bank = *((int *)arg);
1966 __clear_bit(bank, __get_cpu_var(mce_poll_banks));
1967 cmci_disable_bank(bank);
1970 void mce_disable_bank(int bank)
1972 if (bank >= mca_cfg.banks) {
1974 "Ignoring request to disable invalid MCA bank %d.\n",
1978 set_bit(bank, mce_banks_ce_disabled);
1979 on_each_cpu(__mce_disable_bank, &bank, 1);
1983 * mce=off Disables machine check
1984 * mce=no_cmci Disables CMCI
1985 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1986 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1987 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1988 * monarchtimeout is how long to wait for other CPUs on machine
1989 * check, or 0 to not wait
1990 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1991 * mce=nobootlog Don't log MCEs from before booting.
1992 * mce=bios_cmci_threshold Don't program the CMCI threshold
1994 static int __init mcheck_enable(char *str)
1996 struct mca_config *cfg = &mca_cfg;
2004 if (!strcmp(str, "off"))
2005 cfg->disabled = true;
2006 else if (!strcmp(str, "no_cmci"))
2007 cfg->cmci_disabled = true;
2008 else if (!strcmp(str, "dont_log_ce"))
2009 cfg->dont_log_ce = true;
2010 else if (!strcmp(str, "ignore_ce"))
2011 cfg->ignore_ce = true;
2012 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2013 cfg->bootlog = (str[0] == 'b');
2014 else if (!strcmp(str, "bios_cmci_threshold"))
2015 cfg->bios_cmci_threshold = true;
2016 else if (isdigit(str[0])) {
2017 get_option(&str, &(cfg->tolerant));
2020 get_option(&str, &(cfg->monarch_timeout));
2023 pr_info("mce argument %s ignored. Please use /sys\n", str);
2028 __setup("mce", mcheck_enable);
2030 int __init mcheck_init(void)
2032 mcheck_intel_therm_init();
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(__this_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(__this_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(__this_cpu_ptr(&cpu_info)))
2112 static void mce_enable_ce(void *all)
2114 if (!mce_available(__this_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 (strict_strtoull(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 (strict_strtoull(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 (strict_strtoull(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(__this_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(__this_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 case CPU_DOWN_PREPARE:
2398 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2401 case CPU_DOWN_FAILED:
2402 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2403 mce_start_timer(cpu, t);
2407 if (action == CPU_POST_DEAD) {
2408 /* intentionally ignoring frozen here */
2415 static struct notifier_block mce_cpu_notifier = {
2416 .notifier_call = mce_cpu_callback,
2419 static __init void mce_init_banks(void)
2423 for (i = 0; i < mca_cfg.banks; i++) {
2424 struct mce_bank *b = &mce_banks[i];
2425 struct device_attribute *a = &b->attr;
2427 sysfs_attr_init(&a->attr);
2428 a->attr.name = b->attrname;
2429 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2431 a->attr.mode = 0644;
2432 a->show = show_bank;
2433 a->store = set_bank;
2437 static __init int mcheck_init_device(void)
2442 if (!mce_available(&boot_cpu_data))
2445 zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL);
2449 err = subsys_system_register(&mce_subsys, NULL);
2453 cpu_notifier_register_begin();
2454 for_each_online_cpu(i) {
2455 err = mce_device_create(i);
2457 cpu_notifier_register_done();
2462 register_syscore_ops(&mce_syscore_ops);
2463 __register_hotcpu_notifier(&mce_cpu_notifier);
2464 cpu_notifier_register_done();
2466 /* register character device /dev/mcelog */
2467 misc_register(&mce_chrdev_device);
2471 device_initcall_sync(mcheck_init_device);
2474 * Old style boot options parsing. Only for compatibility.
2476 static int __init mcheck_disable(char *str)
2478 mca_cfg.disabled = true;
2481 __setup("nomce", mcheck_disable);
2483 #ifdef CONFIG_DEBUG_FS
2484 struct dentry *mce_get_debugfs_dir(void)
2486 static struct dentry *dmce;
2489 dmce = debugfs_create_dir("mce", NULL);
2494 static void mce_reset(void)
2497 atomic_set(&mce_fake_paniced, 0);
2498 atomic_set(&mce_executing, 0);
2499 atomic_set(&mce_callin, 0);
2500 atomic_set(&global_nwo, 0);
2503 static int fake_panic_get(void *data, u64 *val)
2509 static int fake_panic_set(void *data, u64 val)
2516 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2517 fake_panic_set, "%llu\n");
2519 static int __init mcheck_debugfs_init(void)
2521 struct dentry *dmce, *ffake_panic;
2523 dmce = mce_get_debugfs_dir();
2526 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2533 late_initcall(mcheck_debugfs_init);