x86/mce/AMD: Save MCA_IPID in MCE struct on SMCA systems
[linux-2.6/btrfs-unstable.git] / arch / x86 / kernel / cpu / mcheck / mce.c
blob17e9ff011c0ed40fadc850b55ab85af86cdf2021
1 /*
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
8 * Author: Andi Kleen
9 */
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>
39 #include <linux/fs.h>
40 #include <linux/mm.h>
41 #include <linux/debugfs.h>
42 #include <linux/irq_work.h>
43 #include <linux/export.h>
44 #include <linux/jump_label.h>
46 #include <asm/processor.h>
47 #include <asm/traps.h>
48 #include <asm/tlbflush.h>
49 #include <asm/mce.h>
50 #include <asm/msr.h>
52 #include "mce-internal.h"
54 static DEFINE_MUTEX(mce_chrdev_read_mutex);
56 #define mce_log_get_idx_check(p) \
57 ({ \
58 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
59 !lockdep_is_held(&mce_chrdev_read_mutex), \
60 "suspicious mce_log_get_idx_check() usage"); \
61 smp_load_acquire(&(p)); \
64 #define CREATE_TRACE_POINTS
65 #include <trace/events/mce.h>
67 #define SPINUNIT 100 /* 100ns */
69 DEFINE_PER_CPU(unsigned, mce_exception_count);
71 struct mce_bank *mce_banks __read_mostly;
72 struct mce_vendor_flags mce_flags __read_mostly;
74 struct mca_config mca_cfg __read_mostly = {
75 .bootlog = -1,
77 * Tolerant levels:
78 * 0: always panic on uncorrected errors, log corrected errors
79 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
80 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
81 * 3: never panic or SIGBUS, log all errors (for testing only)
83 .tolerant = 1,
84 .monarch_timeout = -1
87 /* User mode helper program triggered by machine check event */
88 static unsigned long mce_need_notify;
89 static char mce_helper[128];
90 static char *mce_helper_argv[2] = { mce_helper, NULL };
92 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
94 static DEFINE_PER_CPU(struct mce, mces_seen);
95 static int cpu_missing;
98 * MCA banks polled by the period polling timer for corrected events.
99 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
101 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
102 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
106 * MCA banks controlled through firmware first for corrected errors.
107 * This is a global list of banks for which we won't enable CMCI and we
108 * won't poll. Firmware controls these banks and is responsible for
109 * reporting corrected errors through GHES. Uncorrected/recoverable
110 * errors are still notified through a machine check.
112 mce_banks_t mce_banks_ce_disabled;
114 static struct work_struct mce_work;
115 static struct irq_work mce_irq_work;
117 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
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();
130 m->tsc = rdtsc();
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,
151 .len = MCE_LOG_LEN,
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);
165 wmb();
166 for (;;) {
167 entry = mce_log_get_idx_check(mcelog.next);
168 for (;;) {
171 * When the buffer fills up discard new entries.
172 * Assume that the earlier errors are the more
173 * interesting ones:
175 if (entry >= MCE_LOG_LEN) {
176 set_bit(MCE_OVERFLOW,
177 (unsigned long *)&mcelog.flags);
178 return;
180 /* Old left over entry. Skip: */
181 if (mcelog.entry[entry].finished) {
182 entry++;
183 continue;
185 break;
187 smp_rmb();
188 next = entry + 1;
189 if (cmpxchg(&mcelog.next, entry, next) == entry)
190 break;
192 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
193 wmb();
194 mcelog.entry[entry].finished = 1;
195 wmb();
197 set_bit(0, &mce_need_notify);
200 void mce_inject_log(struct mce *m)
202 mutex_lock(&mce_chrdev_read_mutex);
203 mce_log(m);
204 mutex_unlock(&mce_chrdev_read_mutex);
206 EXPORT_SYMBOL_GPL(mce_inject_log);
208 static struct notifier_block mce_srao_nb;
210 void mce_register_decode_chain(struct notifier_block *nb)
212 /* Ensure SRAO notifier has the highest priority in the decode chain. */
213 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
214 nb->priority -= 1;
216 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
218 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
220 void mce_unregister_decode_chain(struct notifier_block *nb)
222 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
224 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
226 static inline u32 ctl_reg(int bank)
228 return MSR_IA32_MCx_CTL(bank);
231 static inline u32 status_reg(int bank)
233 return MSR_IA32_MCx_STATUS(bank);
236 static inline u32 addr_reg(int bank)
238 return MSR_IA32_MCx_ADDR(bank);
241 static inline u32 misc_reg(int bank)
243 return MSR_IA32_MCx_MISC(bank);
246 static inline u32 smca_ctl_reg(int bank)
248 return MSR_AMD64_SMCA_MCx_CTL(bank);
251 static inline u32 smca_status_reg(int bank)
253 return MSR_AMD64_SMCA_MCx_STATUS(bank);
256 static inline u32 smca_addr_reg(int bank)
258 return MSR_AMD64_SMCA_MCx_ADDR(bank);
261 static inline u32 smca_misc_reg(int bank)
263 return MSR_AMD64_SMCA_MCx_MISC(bank);
266 struct mca_msr_regs msr_ops = {
267 .ctl = ctl_reg,
268 .status = status_reg,
269 .addr = addr_reg,
270 .misc = misc_reg
273 static void print_mce(struct mce *m)
275 int ret = 0;
277 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
278 m->extcpu, m->mcgstatus, m->bank, m->status);
280 if (m->ip) {
281 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
282 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
283 m->cs, m->ip);
285 if (m->cs == __KERNEL_CS)
286 print_symbol("{%s}", m->ip);
287 pr_cont("\n");
290 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
291 if (m->addr)
292 pr_cont("ADDR %llx ", m->addr);
293 if (m->misc)
294 pr_cont("MISC %llx ", m->misc);
296 pr_cont("\n");
298 * Note this output is parsed by external tools and old fields
299 * should not be changed.
301 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
302 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
303 cpu_data(m->extcpu).microcode);
306 * Print out human-readable details about the MCE error,
307 * (if the CPU has an implementation for that)
309 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
310 if (ret == NOTIFY_STOP)
311 return;
313 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
316 #define PANIC_TIMEOUT 5 /* 5 seconds */
318 static atomic_t mce_panicked;
320 static int fake_panic;
321 static atomic_t mce_fake_panicked;
323 /* Panic in progress. Enable interrupts and wait for final IPI */
324 static void wait_for_panic(void)
326 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
328 preempt_disable();
329 local_irq_enable();
330 while (timeout-- > 0)
331 udelay(1);
332 if (panic_timeout == 0)
333 panic_timeout = mca_cfg.panic_timeout;
334 panic("Panicing machine check CPU died");
337 static void mce_panic(const char *msg, struct mce *final, char *exp)
339 int apei_err = 0;
340 struct llist_node *pending;
341 struct mce_evt_llist *l;
343 if (!fake_panic) {
345 * Make sure only one CPU runs in machine check panic
347 if (atomic_inc_return(&mce_panicked) > 1)
348 wait_for_panic();
349 barrier();
351 bust_spinlocks(1);
352 console_verbose();
353 } else {
354 /* Don't log too much for fake panic */
355 if (atomic_inc_return(&mce_fake_panicked) > 1)
356 return;
358 pending = mce_gen_pool_prepare_records();
359 /* First print corrected ones that are still unlogged */
360 llist_for_each_entry(l, pending, llnode) {
361 struct mce *m = &l->mce;
362 if (!(m->status & MCI_STATUS_UC)) {
363 print_mce(m);
364 if (!apei_err)
365 apei_err = apei_write_mce(m);
368 /* Now print uncorrected but with the final one last */
369 llist_for_each_entry(l, pending, llnode) {
370 struct mce *m = &l->mce;
371 if (!(m->status & MCI_STATUS_UC))
372 continue;
373 if (!final || mce_cmp(m, final)) {
374 print_mce(m);
375 if (!apei_err)
376 apei_err = apei_write_mce(m);
379 if (final) {
380 print_mce(final);
381 if (!apei_err)
382 apei_err = apei_write_mce(final);
384 if (cpu_missing)
385 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
386 if (exp)
387 pr_emerg(HW_ERR "Machine check: %s\n", exp);
388 if (!fake_panic) {
389 if (panic_timeout == 0)
390 panic_timeout = mca_cfg.panic_timeout;
391 panic(msg);
392 } else
393 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
396 /* Support code for software error injection */
398 static int msr_to_offset(u32 msr)
400 unsigned bank = __this_cpu_read(injectm.bank);
402 if (msr == mca_cfg.rip_msr)
403 return offsetof(struct mce, ip);
404 if (msr == msr_ops.status(bank))
405 return offsetof(struct mce, status);
406 if (msr == msr_ops.addr(bank))
407 return offsetof(struct mce, addr);
408 if (msr == msr_ops.misc(bank))
409 return offsetof(struct mce, misc);
410 if (msr == MSR_IA32_MCG_STATUS)
411 return offsetof(struct mce, mcgstatus);
412 return -1;
415 /* MSR access wrappers used for error injection */
416 static u64 mce_rdmsrl(u32 msr)
418 u64 v;
420 if (__this_cpu_read(injectm.finished)) {
421 int offset = msr_to_offset(msr);
423 if (offset < 0)
424 return 0;
425 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
428 if (rdmsrl_safe(msr, &v)) {
429 WARN_ONCE(1, "mce: Unable to read MSR 0x%x!\n", msr);
431 * Return zero in case the access faulted. This should
432 * not happen normally but can happen if the CPU does
433 * something weird, or if the code is buggy.
435 v = 0;
438 return v;
441 static void mce_wrmsrl(u32 msr, u64 v)
443 if (__this_cpu_read(injectm.finished)) {
444 int offset = msr_to_offset(msr);
446 if (offset >= 0)
447 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
448 return;
450 wrmsrl(msr, v);
454 * Collect all global (w.r.t. this processor) status about this machine
455 * check into our "mce" struct so that we can use it later to assess
456 * the severity of the problem as we read per-bank specific details.
458 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
460 mce_setup(m);
462 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
463 if (regs) {
465 * Get the address of the instruction at the time of
466 * the machine check error.
468 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
469 m->ip = regs->ip;
470 m->cs = regs->cs;
473 * When in VM86 mode make the cs look like ring 3
474 * always. This is a lie, but it's better than passing
475 * the additional vm86 bit around everywhere.
477 if (v8086_mode(regs))
478 m->cs |= 3;
480 /* Use accurate RIP reporting if available. */
481 if (mca_cfg.rip_msr)
482 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
486 int mce_available(struct cpuinfo_x86 *c)
488 if (mca_cfg.disabled)
489 return 0;
490 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
493 static void mce_schedule_work(void)
495 if (!mce_gen_pool_empty() && keventd_up())
496 schedule_work(&mce_work);
499 static void mce_irq_work_cb(struct irq_work *entry)
501 mce_notify_irq();
502 mce_schedule_work();
505 static void mce_report_event(struct pt_regs *regs)
507 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
508 mce_notify_irq();
510 * Triggering the work queue here is just an insurance
511 * policy in case the syscall exit notify handler
512 * doesn't run soon enough or ends up running on the
513 * wrong CPU (can happen when audit sleeps)
515 mce_schedule_work();
516 return;
519 irq_work_queue(&mce_irq_work);
523 * Check if the address reported by the CPU is in a format we can parse.
524 * It would be possible to add code for most other cases, but all would
525 * be somewhat complicated (e.g. segment offset would require an instruction
526 * parser). So only support physical addresses up to page granuality for now.
528 static int mce_usable_address(struct mce *m)
530 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
531 return 0;
533 /* Checks after this one are Intel-specific: */
534 if (boot_cpu_data.x86_vendor != X86_VENDOR_INTEL)
535 return 1;
537 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
538 return 0;
539 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
540 return 0;
541 return 1;
544 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
545 void *data)
547 struct mce *mce = (struct mce *)data;
548 unsigned long pfn;
550 if (!mce)
551 return NOTIFY_DONE;
553 if (mce_usable_address(mce) && (mce->severity == MCE_AO_SEVERITY)) {
554 pfn = mce->addr >> PAGE_SHIFT;
555 memory_failure(pfn, MCE_VECTOR, 0);
558 return NOTIFY_OK;
560 static struct notifier_block mce_srao_nb = {
561 .notifier_call = srao_decode_notifier,
562 .priority = INT_MAX,
566 * Read ADDR and MISC registers.
568 static void mce_read_aux(struct mce *m, int i)
570 if (m->status & MCI_STATUS_MISCV)
571 m->misc = mce_rdmsrl(msr_ops.misc(i));
573 if (m->status & MCI_STATUS_ADDRV) {
574 m->addr = mce_rdmsrl(msr_ops.addr(i));
577 * Mask the reported address by the reported granularity.
579 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
580 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
581 m->addr >>= shift;
582 m->addr <<= shift;
586 if (mce_flags.smca) {
587 m->ipid = mce_rdmsrl(MSR_AMD64_SMCA_MCx_IPID(i));
589 if (m->status & MCI_STATUS_SYNDV)
590 m->synd = mce_rdmsrl(MSR_AMD64_SMCA_MCx_SYND(i));
594 static bool memory_error(struct mce *m)
596 struct cpuinfo_x86 *c = &boot_cpu_data;
598 if (c->x86_vendor == X86_VENDOR_AMD) {
599 /* ErrCodeExt[20:16] */
600 u8 xec = (m->status >> 16) & 0x1f;
602 return (xec == 0x0 || xec == 0x8);
603 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
605 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
607 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
608 * indicating a memory error. Bit 8 is used for indicating a
609 * cache hierarchy error. The combination of bit 2 and bit 3
610 * is used for indicating a `generic' cache hierarchy error
611 * But we can't just blindly check the above bits, because if
612 * bit 11 is set, then it is a bus/interconnect error - and
613 * either way the above bits just gives more detail on what
614 * bus/interconnect error happened. Note that bit 12 can be
615 * ignored, as it's the "filter" bit.
617 return (m->status & 0xef80) == BIT(7) ||
618 (m->status & 0xef00) == BIT(8) ||
619 (m->status & 0xeffc) == 0xc;
622 return false;
625 DEFINE_PER_CPU(unsigned, mce_poll_count);
628 * Poll for corrected events or events that happened before reset.
629 * Those are just logged through /dev/mcelog.
631 * This is executed in standard interrupt context.
633 * Note: spec recommends to panic for fatal unsignalled
634 * errors here. However this would be quite problematic --
635 * we would need to reimplement the Monarch handling and
636 * it would mess up the exclusion between exception handler
637 * and poll hander -- * so we skip this for now.
638 * These cases should not happen anyways, or only when the CPU
639 * is already totally * confused. In this case it's likely it will
640 * not fully execute the machine check handler either.
642 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
644 bool error_seen = false;
645 struct mce m;
646 int severity;
647 int i;
649 this_cpu_inc(mce_poll_count);
651 mce_gather_info(&m, NULL);
653 for (i = 0; i < mca_cfg.banks; i++) {
654 if (!mce_banks[i].ctl || !test_bit(i, *b))
655 continue;
657 m.misc = 0;
658 m.addr = 0;
659 m.bank = i;
660 m.tsc = 0;
662 barrier();
663 m.status = mce_rdmsrl(msr_ops.status(i));
664 if (!(m.status & MCI_STATUS_VAL))
665 continue;
669 * Uncorrected or signalled events are handled by the exception
670 * handler when it is enabled, so don't process those here.
672 * TBD do the same check for MCI_STATUS_EN here?
674 if (!(flags & MCP_UC) &&
675 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
676 continue;
678 error_seen = true;
680 mce_read_aux(&m, i);
682 if (!(flags & MCP_TIMESTAMP))
683 m.tsc = 0;
685 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
687 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m))
688 if (m.status & MCI_STATUS_ADDRV)
689 m.severity = severity;
692 * Don't get the IP here because it's unlikely to
693 * have anything to do with the actual error location.
695 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
696 mce_log(&m);
697 else if (mce_usable_address(&m)) {
699 * Although we skipped logging this, we still want
700 * to take action. Add to the pool so the registered
701 * notifiers will see it.
703 if (!mce_gen_pool_add(&m))
704 mce_schedule_work();
708 * Clear state for this bank.
710 mce_wrmsrl(msr_ops.status(i), 0);
714 * Don't clear MCG_STATUS here because it's only defined for
715 * exceptions.
718 sync_core();
720 return error_seen;
722 EXPORT_SYMBOL_GPL(machine_check_poll);
725 * Do a quick check if any of the events requires a panic.
726 * This decides if we keep the events around or clear them.
728 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
729 struct pt_regs *regs)
731 int i, ret = 0;
732 char *tmp;
734 for (i = 0; i < mca_cfg.banks; i++) {
735 m->status = mce_rdmsrl(msr_ops.status(i));
736 if (m->status & MCI_STATUS_VAL) {
737 __set_bit(i, validp);
738 if (quirk_no_way_out)
739 quirk_no_way_out(i, m, regs);
742 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
743 *msg = tmp;
744 ret = 1;
747 return ret;
751 * Variable to establish order between CPUs while scanning.
752 * Each CPU spins initially until executing is equal its number.
754 static atomic_t mce_executing;
757 * Defines order of CPUs on entry. First CPU becomes Monarch.
759 static atomic_t mce_callin;
762 * Check if a timeout waiting for other CPUs happened.
764 static int mce_timed_out(u64 *t, const char *msg)
767 * The others already did panic for some reason.
768 * Bail out like in a timeout.
769 * rmb() to tell the compiler that system_state
770 * might have been modified by someone else.
772 rmb();
773 if (atomic_read(&mce_panicked))
774 wait_for_panic();
775 if (!mca_cfg.monarch_timeout)
776 goto out;
777 if ((s64)*t < SPINUNIT) {
778 if (mca_cfg.tolerant <= 1)
779 mce_panic(msg, NULL, NULL);
780 cpu_missing = 1;
781 return 1;
783 *t -= SPINUNIT;
784 out:
785 touch_nmi_watchdog();
786 return 0;
790 * The Monarch's reign. The Monarch is the CPU who entered
791 * the machine check handler first. It waits for the others to
792 * raise the exception too and then grades them. When any
793 * error is fatal panic. Only then let the others continue.
795 * The other CPUs entering the MCE handler will be controlled by the
796 * Monarch. They are called Subjects.
798 * This way we prevent any potential data corruption in a unrecoverable case
799 * and also makes sure always all CPU's errors are examined.
801 * Also this detects the case of a machine check event coming from outer
802 * space (not detected by any CPUs) In this case some external agent wants
803 * us to shut down, so panic too.
805 * The other CPUs might still decide to panic if the handler happens
806 * in a unrecoverable place, but in this case the system is in a semi-stable
807 * state and won't corrupt anything by itself. It's ok to let the others
808 * continue for a bit first.
810 * All the spin loops have timeouts; when a timeout happens a CPU
811 * typically elects itself to be Monarch.
813 static void mce_reign(void)
815 int cpu;
816 struct mce *m = NULL;
817 int global_worst = 0;
818 char *msg = NULL;
819 char *nmsg = NULL;
822 * This CPU is the Monarch and the other CPUs have run
823 * through their handlers.
824 * Grade the severity of the errors of all the CPUs.
826 for_each_possible_cpu(cpu) {
827 int severity = mce_severity(&per_cpu(mces_seen, cpu),
828 mca_cfg.tolerant,
829 &nmsg, true);
830 if (severity > global_worst) {
831 msg = nmsg;
832 global_worst = severity;
833 m = &per_cpu(mces_seen, cpu);
838 * Cannot recover? Panic here then.
839 * This dumps all the mces in the log buffer and stops the
840 * other CPUs.
842 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
843 mce_panic("Fatal machine check", m, msg);
846 * For UC somewhere we let the CPU who detects it handle it.
847 * Also must let continue the others, otherwise the handling
848 * CPU could deadlock on a lock.
852 * No machine check event found. Must be some external
853 * source or one CPU is hung. Panic.
855 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
856 mce_panic("Fatal machine check from unknown source", NULL, NULL);
859 * Now clear all the mces_seen so that they don't reappear on
860 * the next mce.
862 for_each_possible_cpu(cpu)
863 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
866 static atomic_t global_nwo;
869 * Start of Monarch synchronization. This waits until all CPUs have
870 * entered the exception handler and then determines if any of them
871 * saw a fatal event that requires panic. Then it executes them
872 * in the entry order.
873 * TBD double check parallel CPU hotunplug
875 static int mce_start(int *no_way_out)
877 int order;
878 int cpus = num_online_cpus();
879 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
881 if (!timeout)
882 return -1;
884 atomic_add(*no_way_out, &global_nwo);
886 * Rely on the implied barrier below, such that global_nwo
887 * is updated before mce_callin.
889 order = atomic_inc_return(&mce_callin);
892 * Wait for everyone.
894 while (atomic_read(&mce_callin) != cpus) {
895 if (mce_timed_out(&timeout,
896 "Timeout: Not all CPUs entered broadcast exception handler")) {
897 atomic_set(&global_nwo, 0);
898 return -1;
900 ndelay(SPINUNIT);
904 * mce_callin should be read before global_nwo
906 smp_rmb();
908 if (order == 1) {
910 * Monarch: Starts executing now, the others wait.
912 atomic_set(&mce_executing, 1);
913 } else {
915 * Subject: Now start the scanning loop one by one in
916 * the original callin order.
917 * This way when there are any shared banks it will be
918 * only seen by one CPU before cleared, avoiding duplicates.
920 while (atomic_read(&mce_executing) < order) {
921 if (mce_timed_out(&timeout,
922 "Timeout: Subject CPUs unable to finish machine check processing")) {
923 atomic_set(&global_nwo, 0);
924 return -1;
926 ndelay(SPINUNIT);
931 * Cache the global no_way_out state.
933 *no_way_out = atomic_read(&global_nwo);
935 return order;
939 * Synchronize between CPUs after main scanning loop.
940 * This invokes the bulk of the Monarch processing.
942 static int mce_end(int order)
944 int ret = -1;
945 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
947 if (!timeout)
948 goto reset;
949 if (order < 0)
950 goto reset;
953 * Allow others to run.
955 atomic_inc(&mce_executing);
957 if (order == 1) {
958 /* CHECKME: Can this race with a parallel hotplug? */
959 int cpus = num_online_cpus();
962 * Monarch: Wait for everyone to go through their scanning
963 * loops.
965 while (atomic_read(&mce_executing) <= cpus) {
966 if (mce_timed_out(&timeout,
967 "Timeout: Monarch CPU unable to finish machine check processing"))
968 goto reset;
969 ndelay(SPINUNIT);
972 mce_reign();
973 barrier();
974 ret = 0;
975 } else {
977 * Subject: Wait for Monarch to finish.
979 while (atomic_read(&mce_executing) != 0) {
980 if (mce_timed_out(&timeout,
981 "Timeout: Monarch CPU did not finish machine check processing"))
982 goto reset;
983 ndelay(SPINUNIT);
987 * Don't reset anything. That's done by the Monarch.
989 return 0;
993 * Reset all global state.
995 reset:
996 atomic_set(&global_nwo, 0);
997 atomic_set(&mce_callin, 0);
998 barrier();
1001 * Let others run again.
1003 atomic_set(&mce_executing, 0);
1004 return ret;
1007 static void mce_clear_state(unsigned long *toclear)
1009 int i;
1011 for (i = 0; i < mca_cfg.banks; i++) {
1012 if (test_bit(i, toclear))
1013 mce_wrmsrl(msr_ops.status(i), 0);
1017 static int do_memory_failure(struct mce *m)
1019 int flags = MF_ACTION_REQUIRED;
1020 int ret;
1022 pr_err("Uncorrected hardware memory error in user-access at %llx", m->addr);
1023 if (!(m->mcgstatus & MCG_STATUS_RIPV))
1024 flags |= MF_MUST_KILL;
1025 ret = memory_failure(m->addr >> PAGE_SHIFT, MCE_VECTOR, flags);
1026 if (ret)
1027 pr_err("Memory error not recovered");
1028 return ret;
1032 * The actual machine check handler. This only handles real
1033 * exceptions when something got corrupted coming in through int 18.
1035 * This is executed in NMI context not subject to normal locking rules. This
1036 * implies that most kernel services cannot be safely used. Don't even
1037 * think about putting a printk in there!
1039 * On Intel systems this is entered on all CPUs in parallel through
1040 * MCE broadcast. However some CPUs might be broken beyond repair,
1041 * so be always careful when synchronizing with others.
1043 void do_machine_check(struct pt_regs *regs, long error_code)
1045 struct mca_config *cfg = &mca_cfg;
1046 struct mce m, *final;
1047 int i;
1048 int worst = 0;
1049 int severity;
1052 * Establish sequential order between the CPUs entering the machine
1053 * check handler.
1055 int order = -1;
1057 * If no_way_out gets set, there is no safe way to recover from this
1058 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
1060 int no_way_out = 0;
1062 * If kill_it gets set, there might be a way to recover from this
1063 * error.
1065 int kill_it = 0;
1066 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1067 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1068 char *msg = "Unknown";
1071 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1072 * on Intel.
1074 int lmce = 1;
1076 /* If this CPU is offline, just bail out. */
1077 if (cpu_is_offline(smp_processor_id())) {
1078 u64 mcgstatus;
1080 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1081 if (mcgstatus & MCG_STATUS_RIPV) {
1082 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1083 return;
1087 ist_enter(regs);
1089 this_cpu_inc(mce_exception_count);
1091 if (!cfg->banks)
1092 goto out;
1094 mce_gather_info(&m, regs);
1096 final = this_cpu_ptr(&mces_seen);
1097 *final = m;
1099 memset(valid_banks, 0, sizeof(valid_banks));
1100 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1102 barrier();
1105 * When no restart IP might need to kill or panic.
1106 * Assume the worst for now, but if we find the
1107 * severity is MCE_AR_SEVERITY we have other options.
1109 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1110 kill_it = 1;
1113 * Check if this MCE is signaled to only this logical processor,
1114 * on Intel only.
1116 if (m.cpuvendor == X86_VENDOR_INTEL)
1117 lmce = m.mcgstatus & MCG_STATUS_LMCES;
1120 * Go through all banks in exclusion of the other CPUs. This way we
1121 * don't report duplicated events on shared banks because the first one
1122 * to see it will clear it. If this is a Local MCE, then no need to
1123 * perform rendezvous.
1125 if (!lmce)
1126 order = mce_start(&no_way_out);
1128 for (i = 0; i < cfg->banks; i++) {
1129 __clear_bit(i, toclear);
1130 if (!test_bit(i, valid_banks))
1131 continue;
1132 if (!mce_banks[i].ctl)
1133 continue;
1135 m.misc = 0;
1136 m.addr = 0;
1137 m.bank = i;
1139 m.status = mce_rdmsrl(msr_ops.status(i));
1140 if ((m.status & MCI_STATUS_VAL) == 0)
1141 continue;
1144 * Non uncorrected or non signaled errors are handled by
1145 * machine_check_poll. Leave them alone, unless this panics.
1147 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1148 !no_way_out)
1149 continue;
1152 * Set taint even when machine check was not enabled.
1154 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1156 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1159 * When machine check was for corrected/deferred handler don't
1160 * touch, unless we're panicing.
1162 if ((severity == MCE_KEEP_SEVERITY ||
1163 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1164 continue;
1165 __set_bit(i, toclear);
1166 if (severity == MCE_NO_SEVERITY) {
1168 * Machine check event was not enabled. Clear, but
1169 * ignore.
1171 continue;
1174 mce_read_aux(&m, i);
1176 /* assuming valid severity level != 0 */
1177 m.severity = severity;
1179 mce_log(&m);
1181 if (severity > worst) {
1182 *final = m;
1183 worst = severity;
1187 /* mce_clear_state will clear *final, save locally for use later */
1188 m = *final;
1190 if (!no_way_out)
1191 mce_clear_state(toclear);
1194 * Do most of the synchronization with other CPUs.
1195 * When there's any problem use only local no_way_out state.
1197 if (!lmce) {
1198 if (mce_end(order) < 0)
1199 no_way_out = worst >= MCE_PANIC_SEVERITY;
1200 } else {
1202 * Local MCE skipped calling mce_reign()
1203 * If we found a fatal error, we need to panic here.
1205 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1206 mce_panic("Machine check from unknown source",
1207 NULL, NULL);
1211 * If tolerant is at an insane level we drop requests to kill
1212 * processes and continue even when there is no way out.
1214 if (cfg->tolerant == 3)
1215 kill_it = 0;
1216 else if (no_way_out)
1217 mce_panic("Fatal machine check on current CPU", &m, msg);
1219 if (worst > 0)
1220 mce_report_event(regs);
1221 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1222 out:
1223 sync_core();
1225 if (worst != MCE_AR_SEVERITY && !kill_it)
1226 goto out_ist;
1228 /* Fault was in user mode and we need to take some action */
1229 if ((m.cs & 3) == 3) {
1230 ist_begin_non_atomic(regs);
1231 local_irq_enable();
1233 if (kill_it || do_memory_failure(&m))
1234 force_sig(SIGBUS, current);
1235 local_irq_disable();
1236 ist_end_non_atomic();
1237 } else {
1238 if (!fixup_exception(regs, X86_TRAP_MC))
1239 mce_panic("Failed kernel mode recovery", &m, NULL);
1242 out_ist:
1243 ist_exit(regs);
1245 EXPORT_SYMBOL_GPL(do_machine_check);
1247 #ifndef CONFIG_MEMORY_FAILURE
1248 int memory_failure(unsigned long pfn, int vector, int flags)
1250 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1251 BUG_ON(flags & MF_ACTION_REQUIRED);
1252 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1253 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1254 pfn);
1256 return 0;
1258 #endif
1261 * Action optional processing happens here (picking up
1262 * from the list of faulting pages that do_machine_check()
1263 * placed into the genpool).
1265 static void mce_process_work(struct work_struct *dummy)
1267 mce_gen_pool_process();
1270 #ifdef CONFIG_X86_MCE_INTEL
1271 /***
1272 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1273 * @cpu: The CPU on which the event occurred.
1274 * @status: Event status information
1276 * This function should be called by the thermal interrupt after the
1277 * event has been processed and the decision was made to log the event
1278 * further.
1280 * The status parameter will be saved to the 'status' field of 'struct mce'
1281 * and historically has been the register value of the
1282 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1284 void mce_log_therm_throt_event(__u64 status)
1286 struct mce m;
1288 mce_setup(&m);
1289 m.bank = MCE_THERMAL_BANK;
1290 m.status = status;
1291 mce_log(&m);
1293 #endif /* CONFIG_X86_MCE_INTEL */
1296 * Periodic polling timer for "silent" machine check errors. If the
1297 * poller finds an MCE, poll 2x faster. When the poller finds no more
1298 * errors, poll 2x slower (up to check_interval seconds).
1300 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1302 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1303 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1305 static unsigned long mce_adjust_timer_default(unsigned long interval)
1307 return interval;
1310 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1312 static void __restart_timer(struct timer_list *t, unsigned long interval)
1314 unsigned long when = jiffies + interval;
1315 unsigned long flags;
1317 local_irq_save(flags);
1319 if (timer_pending(t)) {
1320 if (time_before(when, t->expires))
1321 mod_timer(t, when);
1322 } else {
1323 t->expires = round_jiffies(when);
1324 add_timer_on(t, smp_processor_id());
1327 local_irq_restore(flags);
1330 static void mce_timer_fn(unsigned long data)
1332 struct timer_list *t = this_cpu_ptr(&mce_timer);
1333 int cpu = smp_processor_id();
1334 unsigned long iv;
1336 WARN_ON(cpu != data);
1338 iv = __this_cpu_read(mce_next_interval);
1340 if (mce_available(this_cpu_ptr(&cpu_info))) {
1341 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1343 if (mce_intel_cmci_poll()) {
1344 iv = mce_adjust_timer(iv);
1345 goto done;
1350 * Alert userspace if needed. If we logged an MCE, reduce the polling
1351 * interval, otherwise increase the polling interval.
1353 if (mce_notify_irq())
1354 iv = max(iv / 2, (unsigned long) HZ/100);
1355 else
1356 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1358 done:
1359 __this_cpu_write(mce_next_interval, iv);
1360 __restart_timer(t, iv);
1364 * Ensure that the timer is firing in @interval from now.
1366 void mce_timer_kick(unsigned long interval)
1368 struct timer_list *t = this_cpu_ptr(&mce_timer);
1369 unsigned long iv = __this_cpu_read(mce_next_interval);
1371 __restart_timer(t, interval);
1373 if (interval < iv)
1374 __this_cpu_write(mce_next_interval, interval);
1377 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1378 static void mce_timer_delete_all(void)
1380 int cpu;
1382 for_each_online_cpu(cpu)
1383 del_timer_sync(&per_cpu(mce_timer, cpu));
1386 static void mce_do_trigger(struct work_struct *work)
1388 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1391 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1394 * Notify the user(s) about new machine check events.
1395 * Can be called from interrupt context, but not from machine check/NMI
1396 * context.
1398 int mce_notify_irq(void)
1400 /* Not more than two messages every minute */
1401 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1403 if (test_and_clear_bit(0, &mce_need_notify)) {
1404 /* wake processes polling /dev/mcelog */
1405 wake_up_interruptible(&mce_chrdev_wait);
1407 if (mce_helper[0])
1408 schedule_work(&mce_trigger_work);
1410 if (__ratelimit(&ratelimit))
1411 pr_info(HW_ERR "Machine check events logged\n");
1413 return 1;
1415 return 0;
1417 EXPORT_SYMBOL_GPL(mce_notify_irq);
1419 static int __mcheck_cpu_mce_banks_init(void)
1421 int i;
1422 u8 num_banks = mca_cfg.banks;
1424 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1425 if (!mce_banks)
1426 return -ENOMEM;
1428 for (i = 0; i < num_banks; i++) {
1429 struct mce_bank *b = &mce_banks[i];
1431 b->ctl = -1ULL;
1432 b->init = 1;
1434 return 0;
1438 * Initialize Machine Checks for a CPU.
1440 static int __mcheck_cpu_cap_init(void)
1442 unsigned b;
1443 u64 cap;
1445 rdmsrl(MSR_IA32_MCG_CAP, cap);
1447 b = cap & MCG_BANKCNT_MASK;
1448 if (!mca_cfg.banks)
1449 pr_info("CPU supports %d MCE banks\n", b);
1451 if (b > MAX_NR_BANKS) {
1452 pr_warn("Using only %u machine check banks out of %u\n",
1453 MAX_NR_BANKS, b);
1454 b = MAX_NR_BANKS;
1457 /* Don't support asymmetric configurations today */
1458 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1459 mca_cfg.banks = b;
1461 if (!mce_banks) {
1462 int err = __mcheck_cpu_mce_banks_init();
1464 if (err)
1465 return err;
1468 /* Use accurate RIP reporting if available. */
1469 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1470 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1472 if (cap & MCG_SER_P)
1473 mca_cfg.ser = true;
1475 return 0;
1478 static void __mcheck_cpu_init_generic(void)
1480 enum mcp_flags m_fl = 0;
1481 mce_banks_t all_banks;
1482 u64 cap;
1484 if (!mca_cfg.bootlog)
1485 m_fl = MCP_DONTLOG;
1488 * Log the machine checks left over from the previous reset.
1490 bitmap_fill(all_banks, MAX_NR_BANKS);
1491 machine_check_poll(MCP_UC | m_fl, &all_banks);
1493 cr4_set_bits(X86_CR4_MCE);
1495 rdmsrl(MSR_IA32_MCG_CAP, cap);
1496 if (cap & MCG_CTL_P)
1497 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1500 static void __mcheck_cpu_init_clear_banks(void)
1502 int i;
1504 for (i = 0; i < mca_cfg.banks; i++) {
1505 struct mce_bank *b = &mce_banks[i];
1507 if (!b->init)
1508 continue;
1509 wrmsrl(msr_ops.ctl(i), b->ctl);
1510 wrmsrl(msr_ops.status(i), 0);
1515 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1516 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1517 * Vol 3B Table 15-20). But this confuses both the code that determines
1518 * whether the machine check occurred in kernel or user mode, and also
1519 * the severity assessment code. Pretend that EIPV was set, and take the
1520 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1522 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1524 if (bank != 0)
1525 return;
1526 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1527 return;
1528 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1529 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1530 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1531 MCACOD)) !=
1532 (MCI_STATUS_UC|MCI_STATUS_EN|
1533 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1534 MCI_STATUS_AR|MCACOD_INSTR))
1535 return;
1537 m->mcgstatus |= MCG_STATUS_EIPV;
1538 m->ip = regs->ip;
1539 m->cs = regs->cs;
1542 /* Add per CPU specific workarounds here */
1543 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1545 struct mca_config *cfg = &mca_cfg;
1547 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1548 pr_info("unknown CPU type - not enabling MCE support\n");
1549 return -EOPNOTSUPP;
1552 /* This should be disabled by the BIOS, but isn't always */
1553 if (c->x86_vendor == X86_VENDOR_AMD) {
1554 if (c->x86 == 15 && cfg->banks > 4) {
1556 * disable GART TBL walk error reporting, which
1557 * trips off incorrectly with the IOMMU & 3ware
1558 * & Cerberus:
1560 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1562 if (c->x86 < 17 && cfg->bootlog < 0) {
1564 * Lots of broken BIOS around that don't clear them
1565 * by default and leave crap in there. Don't log:
1567 cfg->bootlog = 0;
1570 * Various K7s with broken bank 0 around. Always disable
1571 * by default.
1573 if (c->x86 == 6 && cfg->banks > 0)
1574 mce_banks[0].ctl = 0;
1577 * overflow_recov is supported for F15h Models 00h-0fh
1578 * even though we don't have a CPUID bit for it.
1580 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1581 mce_flags.overflow_recov = 1;
1584 * Turn off MC4_MISC thresholding banks on those models since
1585 * they're not supported there.
1587 if (c->x86 == 0x15 &&
1588 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1589 int i;
1590 u64 hwcr;
1591 bool need_toggle;
1592 u32 msrs[] = {
1593 0x00000413, /* MC4_MISC0 */
1594 0xc0000408, /* MC4_MISC1 */
1597 rdmsrl(MSR_K7_HWCR, hwcr);
1599 /* McStatusWrEn has to be set */
1600 need_toggle = !(hwcr & BIT(18));
1602 if (need_toggle)
1603 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1605 /* Clear CntP bit safely */
1606 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1607 msr_clear_bit(msrs[i], 62);
1609 /* restore old settings */
1610 if (need_toggle)
1611 wrmsrl(MSR_K7_HWCR, hwcr);
1615 if (c->x86_vendor == X86_VENDOR_INTEL) {
1617 * SDM documents that on family 6 bank 0 should not be written
1618 * because it aliases to another special BIOS controlled
1619 * register.
1620 * But it's not aliased anymore on model 0x1a+
1621 * Don't ignore bank 0 completely because there could be a
1622 * valid event later, merely don't write CTL0.
1625 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1626 mce_banks[0].init = 0;
1629 * All newer Intel systems support MCE broadcasting. Enable
1630 * synchronization with a one second timeout.
1632 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1633 cfg->monarch_timeout < 0)
1634 cfg->monarch_timeout = USEC_PER_SEC;
1637 * There are also broken BIOSes on some Pentium M and
1638 * earlier systems:
1640 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1641 cfg->bootlog = 0;
1643 if (c->x86 == 6 && c->x86_model == 45)
1644 quirk_no_way_out = quirk_sandybridge_ifu;
1646 if (cfg->monarch_timeout < 0)
1647 cfg->monarch_timeout = 0;
1648 if (cfg->bootlog != 0)
1649 cfg->panic_timeout = 30;
1651 return 0;
1654 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1656 if (c->x86 != 5)
1657 return 0;
1659 switch (c->x86_vendor) {
1660 case X86_VENDOR_INTEL:
1661 intel_p5_mcheck_init(c);
1662 return 1;
1663 break;
1664 case X86_VENDOR_CENTAUR:
1665 winchip_mcheck_init(c);
1666 return 1;
1667 break;
1668 default:
1669 return 0;
1672 return 0;
1675 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1677 switch (c->x86_vendor) {
1678 case X86_VENDOR_INTEL:
1679 mce_intel_feature_init(c);
1680 mce_adjust_timer = cmci_intel_adjust_timer;
1681 break;
1683 case X86_VENDOR_AMD: {
1684 mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
1685 mce_flags.succor = !!cpu_has(c, X86_FEATURE_SUCCOR);
1686 mce_flags.smca = !!cpu_has(c, X86_FEATURE_SMCA);
1689 * Install proper ops for Scalable MCA enabled processors
1691 if (mce_flags.smca) {
1692 msr_ops.ctl = smca_ctl_reg;
1693 msr_ops.status = smca_status_reg;
1694 msr_ops.addr = smca_addr_reg;
1695 msr_ops.misc = smca_misc_reg;
1697 mce_amd_feature_init(c);
1699 break;
1702 default:
1703 break;
1707 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1709 switch (c->x86_vendor) {
1710 case X86_VENDOR_INTEL:
1711 mce_intel_feature_clear(c);
1712 break;
1713 default:
1714 break;
1718 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1720 unsigned long iv = check_interval * HZ;
1722 if (mca_cfg.ignore_ce || !iv)
1723 return;
1725 per_cpu(mce_next_interval, cpu) = iv;
1727 t->expires = round_jiffies(jiffies + iv);
1728 add_timer_on(t, cpu);
1731 static void __mcheck_cpu_init_timer(void)
1733 struct timer_list *t = this_cpu_ptr(&mce_timer);
1734 unsigned int cpu = smp_processor_id();
1736 setup_pinned_timer(t, mce_timer_fn, cpu);
1737 mce_start_timer(cpu, t);
1740 /* Handle unconfigured int18 (should never happen) */
1741 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1743 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1744 smp_processor_id());
1747 /* Call the installed machine check handler for this CPU setup. */
1748 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1749 unexpected_machine_check;
1752 * Called for each booted CPU to set up machine checks.
1753 * Must be called with preempt off:
1755 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1757 if (mca_cfg.disabled)
1758 return;
1760 if (__mcheck_cpu_ancient_init(c))
1761 return;
1763 if (!mce_available(c))
1764 return;
1766 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1767 mca_cfg.disabled = true;
1768 return;
1771 if (mce_gen_pool_init()) {
1772 mca_cfg.disabled = true;
1773 pr_emerg("Couldn't allocate MCE records pool!\n");
1774 return;
1777 machine_check_vector = do_machine_check;
1779 __mcheck_cpu_init_generic();
1780 __mcheck_cpu_init_vendor(c);
1781 __mcheck_cpu_init_clear_banks();
1782 __mcheck_cpu_init_timer();
1786 * Called for each booted CPU to clear some machine checks opt-ins
1788 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1790 if (mca_cfg.disabled)
1791 return;
1793 if (!mce_available(c))
1794 return;
1797 * Possibly to clear general settings generic to x86
1798 * __mcheck_cpu_clear_generic(c);
1800 __mcheck_cpu_clear_vendor(c);
1805 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1808 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1809 static int mce_chrdev_open_count; /* #times opened */
1810 static int mce_chrdev_open_exclu; /* already open exclusive? */
1812 static int mce_chrdev_open(struct inode *inode, struct file *file)
1814 spin_lock(&mce_chrdev_state_lock);
1816 if (mce_chrdev_open_exclu ||
1817 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1818 spin_unlock(&mce_chrdev_state_lock);
1820 return -EBUSY;
1823 if (file->f_flags & O_EXCL)
1824 mce_chrdev_open_exclu = 1;
1825 mce_chrdev_open_count++;
1827 spin_unlock(&mce_chrdev_state_lock);
1829 return nonseekable_open(inode, file);
1832 static int mce_chrdev_release(struct inode *inode, struct file *file)
1834 spin_lock(&mce_chrdev_state_lock);
1836 mce_chrdev_open_count--;
1837 mce_chrdev_open_exclu = 0;
1839 spin_unlock(&mce_chrdev_state_lock);
1841 return 0;
1844 static void collect_tscs(void *data)
1846 unsigned long *cpu_tsc = (unsigned long *)data;
1848 cpu_tsc[smp_processor_id()] = rdtsc();
1851 static int mce_apei_read_done;
1853 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1854 static int __mce_read_apei(char __user **ubuf, size_t usize)
1856 int rc;
1857 u64 record_id;
1858 struct mce m;
1860 if (usize < sizeof(struct mce))
1861 return -EINVAL;
1863 rc = apei_read_mce(&m, &record_id);
1864 /* Error or no more MCE record */
1865 if (rc <= 0) {
1866 mce_apei_read_done = 1;
1868 * When ERST is disabled, mce_chrdev_read() should return
1869 * "no record" instead of "no device."
1871 if (rc == -ENODEV)
1872 return 0;
1873 return rc;
1875 rc = -EFAULT;
1876 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1877 return rc;
1879 * In fact, we should have cleared the record after that has
1880 * been flushed to the disk or sent to network in
1881 * /sbin/mcelog, but we have no interface to support that now,
1882 * so just clear it to avoid duplication.
1884 rc = apei_clear_mce(record_id);
1885 if (rc) {
1886 mce_apei_read_done = 1;
1887 return rc;
1889 *ubuf += sizeof(struct mce);
1891 return 0;
1894 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1895 size_t usize, loff_t *off)
1897 char __user *buf = ubuf;
1898 unsigned long *cpu_tsc;
1899 unsigned prev, next;
1900 int i, err;
1902 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1903 if (!cpu_tsc)
1904 return -ENOMEM;
1906 mutex_lock(&mce_chrdev_read_mutex);
1908 if (!mce_apei_read_done) {
1909 err = __mce_read_apei(&buf, usize);
1910 if (err || buf != ubuf)
1911 goto out;
1914 next = mce_log_get_idx_check(mcelog.next);
1916 /* Only supports full reads right now */
1917 err = -EINVAL;
1918 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1919 goto out;
1921 err = 0;
1922 prev = 0;
1923 do {
1924 for (i = prev; i < next; i++) {
1925 unsigned long start = jiffies;
1926 struct mce *m = &mcelog.entry[i];
1928 while (!m->finished) {
1929 if (time_after_eq(jiffies, start + 2)) {
1930 memset(m, 0, sizeof(*m));
1931 goto timeout;
1933 cpu_relax();
1935 smp_rmb();
1936 err |= copy_to_user(buf, m, sizeof(*m));
1937 buf += sizeof(*m);
1938 timeout:
1942 memset(mcelog.entry + prev, 0,
1943 (next - prev) * sizeof(struct mce));
1944 prev = next;
1945 next = cmpxchg(&mcelog.next, prev, 0);
1946 } while (next != prev);
1948 synchronize_sched();
1951 * Collect entries that were still getting written before the
1952 * synchronize.
1954 on_each_cpu(collect_tscs, cpu_tsc, 1);
1956 for (i = next; i < MCE_LOG_LEN; i++) {
1957 struct mce *m = &mcelog.entry[i];
1959 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1960 err |= copy_to_user(buf, m, sizeof(*m));
1961 smp_rmb();
1962 buf += sizeof(*m);
1963 memset(m, 0, sizeof(*m));
1967 if (err)
1968 err = -EFAULT;
1970 out:
1971 mutex_unlock(&mce_chrdev_read_mutex);
1972 kfree(cpu_tsc);
1974 return err ? err : buf - ubuf;
1977 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1979 poll_wait(file, &mce_chrdev_wait, wait);
1980 if (READ_ONCE(mcelog.next))
1981 return POLLIN | POLLRDNORM;
1982 if (!mce_apei_read_done && apei_check_mce())
1983 return POLLIN | POLLRDNORM;
1984 return 0;
1987 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1988 unsigned long arg)
1990 int __user *p = (int __user *)arg;
1992 if (!capable(CAP_SYS_ADMIN))
1993 return -EPERM;
1995 switch (cmd) {
1996 case MCE_GET_RECORD_LEN:
1997 return put_user(sizeof(struct mce), p);
1998 case MCE_GET_LOG_LEN:
1999 return put_user(MCE_LOG_LEN, p);
2000 case MCE_GETCLEAR_FLAGS: {
2001 unsigned flags;
2003 do {
2004 flags = mcelog.flags;
2005 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
2007 return put_user(flags, p);
2009 default:
2010 return -ENOTTY;
2014 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
2015 size_t usize, loff_t *off);
2017 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
2018 const char __user *ubuf,
2019 size_t usize, loff_t *off))
2021 mce_write = fn;
2023 EXPORT_SYMBOL_GPL(register_mce_write_callback);
2025 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
2026 size_t usize, loff_t *off)
2028 if (mce_write)
2029 return mce_write(filp, ubuf, usize, off);
2030 else
2031 return -EINVAL;
2034 static const struct file_operations mce_chrdev_ops = {
2035 .open = mce_chrdev_open,
2036 .release = mce_chrdev_release,
2037 .read = mce_chrdev_read,
2038 .write = mce_chrdev_write,
2039 .poll = mce_chrdev_poll,
2040 .unlocked_ioctl = mce_chrdev_ioctl,
2041 .llseek = no_llseek,
2044 static struct miscdevice mce_chrdev_device = {
2045 MISC_MCELOG_MINOR,
2046 "mcelog",
2047 &mce_chrdev_ops,
2050 static void __mce_disable_bank(void *arg)
2052 int bank = *((int *)arg);
2053 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2054 cmci_disable_bank(bank);
2057 void mce_disable_bank(int bank)
2059 if (bank >= mca_cfg.banks) {
2060 pr_warn(FW_BUG
2061 "Ignoring request to disable invalid MCA bank %d.\n",
2062 bank);
2063 return;
2065 set_bit(bank, mce_banks_ce_disabled);
2066 on_each_cpu(__mce_disable_bank, &bank, 1);
2070 * mce=off Disables machine check
2071 * mce=no_cmci Disables CMCI
2072 * mce=no_lmce Disables LMCE
2073 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2074 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2075 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2076 * monarchtimeout is how long to wait for other CPUs on machine
2077 * check, or 0 to not wait
2078 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2079 * mce=nobootlog Don't log MCEs from before booting.
2080 * mce=bios_cmci_threshold Don't program the CMCI threshold
2081 * mce=recovery force enable memcpy_mcsafe()
2083 static int __init mcheck_enable(char *str)
2085 struct mca_config *cfg = &mca_cfg;
2087 if (*str == 0) {
2088 enable_p5_mce();
2089 return 1;
2091 if (*str == '=')
2092 str++;
2093 if (!strcmp(str, "off"))
2094 cfg->disabled = true;
2095 else if (!strcmp(str, "no_cmci"))
2096 cfg->cmci_disabled = true;
2097 else if (!strcmp(str, "no_lmce"))
2098 cfg->lmce_disabled = true;
2099 else if (!strcmp(str, "dont_log_ce"))
2100 cfg->dont_log_ce = true;
2101 else if (!strcmp(str, "ignore_ce"))
2102 cfg->ignore_ce = true;
2103 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2104 cfg->bootlog = (str[0] == 'b');
2105 else if (!strcmp(str, "bios_cmci_threshold"))
2106 cfg->bios_cmci_threshold = true;
2107 else if (!strcmp(str, "recovery"))
2108 cfg->recovery = true;
2109 else if (isdigit(str[0])) {
2110 if (get_option(&str, &cfg->tolerant) == 2)
2111 get_option(&str, &(cfg->monarch_timeout));
2112 } else {
2113 pr_info("mce argument %s ignored. Please use /sys\n", str);
2114 return 0;
2116 return 1;
2118 __setup("mce", mcheck_enable);
2120 int __init mcheck_init(void)
2122 mcheck_intel_therm_init();
2123 mce_register_decode_chain(&mce_srao_nb);
2124 mcheck_vendor_init_severity();
2126 INIT_WORK(&mce_work, mce_process_work);
2127 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2129 return 0;
2133 * mce_syscore: PM support
2137 * Disable machine checks on suspend and shutdown. We can't really handle
2138 * them later.
2140 static void mce_disable_error_reporting(void)
2142 int i;
2144 for (i = 0; i < mca_cfg.banks; i++) {
2145 struct mce_bank *b = &mce_banks[i];
2147 if (b->init)
2148 wrmsrl(msr_ops.ctl(i), 0);
2150 return;
2153 static void vendor_disable_error_reporting(void)
2156 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2157 * Disabling them for just a single offlined CPU is bad, since it will
2158 * inhibit reporting for all shared resources on the socket like the
2159 * last level cache (LLC), the integrated memory controller (iMC), etc.
2161 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2162 return;
2164 mce_disable_error_reporting();
2167 static int mce_syscore_suspend(void)
2169 vendor_disable_error_reporting();
2170 return 0;
2173 static void mce_syscore_shutdown(void)
2175 vendor_disable_error_reporting();
2179 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2180 * Only one CPU is active at this time, the others get re-added later using
2181 * CPU hotplug:
2183 static void mce_syscore_resume(void)
2185 __mcheck_cpu_init_generic();
2186 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2187 __mcheck_cpu_init_clear_banks();
2190 static struct syscore_ops mce_syscore_ops = {
2191 .suspend = mce_syscore_suspend,
2192 .shutdown = mce_syscore_shutdown,
2193 .resume = mce_syscore_resume,
2197 * mce_device: Sysfs support
2200 static void mce_cpu_restart(void *data)
2202 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2203 return;
2204 __mcheck_cpu_init_generic();
2205 __mcheck_cpu_init_clear_banks();
2206 __mcheck_cpu_init_timer();
2209 /* Reinit MCEs after user configuration changes */
2210 static void mce_restart(void)
2212 mce_timer_delete_all();
2213 on_each_cpu(mce_cpu_restart, NULL, 1);
2216 /* Toggle features for corrected errors */
2217 static void mce_disable_cmci(void *data)
2219 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2220 return;
2221 cmci_clear();
2224 static void mce_enable_ce(void *all)
2226 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2227 return;
2228 cmci_reenable();
2229 cmci_recheck();
2230 if (all)
2231 __mcheck_cpu_init_timer();
2234 static struct bus_type mce_subsys = {
2235 .name = "machinecheck",
2236 .dev_name = "machinecheck",
2239 DEFINE_PER_CPU(struct device *, mce_device);
2241 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2243 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2245 return container_of(attr, struct mce_bank, attr);
2248 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2249 char *buf)
2251 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2254 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2255 const char *buf, size_t size)
2257 u64 new;
2259 if (kstrtou64(buf, 0, &new) < 0)
2260 return -EINVAL;
2262 attr_to_bank(attr)->ctl = new;
2263 mce_restart();
2265 return size;
2268 static ssize_t
2269 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2271 strcpy(buf, mce_helper);
2272 strcat(buf, "\n");
2273 return strlen(mce_helper) + 1;
2276 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2277 const char *buf, size_t siz)
2279 char *p;
2281 strncpy(mce_helper, buf, sizeof(mce_helper));
2282 mce_helper[sizeof(mce_helper)-1] = 0;
2283 p = strchr(mce_helper, '\n');
2285 if (p)
2286 *p = 0;
2288 return strlen(mce_helper) + !!p;
2291 static ssize_t set_ignore_ce(struct device *s,
2292 struct device_attribute *attr,
2293 const char *buf, size_t size)
2295 u64 new;
2297 if (kstrtou64(buf, 0, &new) < 0)
2298 return -EINVAL;
2300 if (mca_cfg.ignore_ce ^ !!new) {
2301 if (new) {
2302 /* disable ce features */
2303 mce_timer_delete_all();
2304 on_each_cpu(mce_disable_cmci, NULL, 1);
2305 mca_cfg.ignore_ce = true;
2306 } else {
2307 /* enable ce features */
2308 mca_cfg.ignore_ce = false;
2309 on_each_cpu(mce_enable_ce, (void *)1, 1);
2312 return size;
2315 static ssize_t set_cmci_disabled(struct device *s,
2316 struct device_attribute *attr,
2317 const char *buf, size_t size)
2319 u64 new;
2321 if (kstrtou64(buf, 0, &new) < 0)
2322 return -EINVAL;
2324 if (mca_cfg.cmci_disabled ^ !!new) {
2325 if (new) {
2326 /* disable cmci */
2327 on_each_cpu(mce_disable_cmci, NULL, 1);
2328 mca_cfg.cmci_disabled = true;
2329 } else {
2330 /* enable cmci */
2331 mca_cfg.cmci_disabled = false;
2332 on_each_cpu(mce_enable_ce, NULL, 1);
2335 return size;
2338 static ssize_t store_int_with_restart(struct device *s,
2339 struct device_attribute *attr,
2340 const char *buf, size_t size)
2342 ssize_t ret = device_store_int(s, attr, buf, size);
2343 mce_restart();
2344 return ret;
2347 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2348 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2349 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2350 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2352 static struct dev_ext_attribute dev_attr_check_interval = {
2353 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2354 &check_interval
2357 static struct dev_ext_attribute dev_attr_ignore_ce = {
2358 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2359 &mca_cfg.ignore_ce
2362 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2363 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2364 &mca_cfg.cmci_disabled
2367 static struct device_attribute *mce_device_attrs[] = {
2368 &dev_attr_tolerant.attr,
2369 &dev_attr_check_interval.attr,
2370 &dev_attr_trigger,
2371 &dev_attr_monarch_timeout.attr,
2372 &dev_attr_dont_log_ce.attr,
2373 &dev_attr_ignore_ce.attr,
2374 &dev_attr_cmci_disabled.attr,
2375 NULL
2378 static cpumask_var_t mce_device_initialized;
2380 static void mce_device_release(struct device *dev)
2382 kfree(dev);
2385 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2386 static int mce_device_create(unsigned int cpu)
2388 struct device *dev;
2389 int err;
2390 int i, j;
2392 if (!mce_available(&boot_cpu_data))
2393 return -EIO;
2395 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2396 if (!dev)
2397 return -ENOMEM;
2398 dev->id = cpu;
2399 dev->bus = &mce_subsys;
2400 dev->release = &mce_device_release;
2402 err = device_register(dev);
2403 if (err) {
2404 put_device(dev);
2405 return err;
2408 for (i = 0; mce_device_attrs[i]; i++) {
2409 err = device_create_file(dev, mce_device_attrs[i]);
2410 if (err)
2411 goto error;
2413 for (j = 0; j < mca_cfg.banks; j++) {
2414 err = device_create_file(dev, &mce_banks[j].attr);
2415 if (err)
2416 goto error2;
2418 cpumask_set_cpu(cpu, mce_device_initialized);
2419 per_cpu(mce_device, cpu) = dev;
2421 return 0;
2422 error2:
2423 while (--j >= 0)
2424 device_remove_file(dev, &mce_banks[j].attr);
2425 error:
2426 while (--i >= 0)
2427 device_remove_file(dev, mce_device_attrs[i]);
2429 device_unregister(dev);
2431 return err;
2434 static void mce_device_remove(unsigned int cpu)
2436 struct device *dev = per_cpu(mce_device, cpu);
2437 int i;
2439 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2440 return;
2442 for (i = 0; mce_device_attrs[i]; i++)
2443 device_remove_file(dev, mce_device_attrs[i]);
2445 for (i = 0; i < mca_cfg.banks; i++)
2446 device_remove_file(dev, &mce_banks[i].attr);
2448 device_unregister(dev);
2449 cpumask_clear_cpu(cpu, mce_device_initialized);
2450 per_cpu(mce_device, cpu) = NULL;
2453 /* Make sure there are no machine checks on offlined CPUs. */
2454 static void mce_disable_cpu(void *h)
2456 unsigned long action = *(unsigned long *)h;
2458 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2459 return;
2461 if (!(action & CPU_TASKS_FROZEN))
2462 cmci_clear();
2464 vendor_disable_error_reporting();
2467 static void mce_reenable_cpu(void *h)
2469 unsigned long action = *(unsigned long *)h;
2470 int i;
2472 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2473 return;
2475 if (!(action & CPU_TASKS_FROZEN))
2476 cmci_reenable();
2477 for (i = 0; i < mca_cfg.banks; i++) {
2478 struct mce_bank *b = &mce_banks[i];
2480 if (b->init)
2481 wrmsrl(msr_ops.ctl(i), b->ctl);
2485 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2486 static int
2487 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2489 unsigned int cpu = (unsigned long)hcpu;
2490 struct timer_list *t = &per_cpu(mce_timer, cpu);
2492 switch (action & ~CPU_TASKS_FROZEN) {
2493 case CPU_ONLINE:
2494 mce_device_create(cpu);
2495 if (threshold_cpu_callback)
2496 threshold_cpu_callback(action, cpu);
2497 break;
2498 case CPU_DEAD:
2499 if (threshold_cpu_callback)
2500 threshold_cpu_callback(action, cpu);
2501 mce_device_remove(cpu);
2502 mce_intel_hcpu_update(cpu);
2504 /* intentionally ignoring frozen here */
2505 if (!(action & CPU_TASKS_FROZEN))
2506 cmci_rediscover();
2507 break;
2508 case CPU_DOWN_PREPARE:
2509 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2510 del_timer_sync(t);
2511 break;
2512 case CPU_DOWN_FAILED:
2513 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2514 mce_start_timer(cpu, t);
2515 break;
2518 return NOTIFY_OK;
2521 static struct notifier_block mce_cpu_notifier = {
2522 .notifier_call = mce_cpu_callback,
2525 static __init void mce_init_banks(void)
2527 int i;
2529 for (i = 0; i < mca_cfg.banks; i++) {
2530 struct mce_bank *b = &mce_banks[i];
2531 struct device_attribute *a = &b->attr;
2533 sysfs_attr_init(&a->attr);
2534 a->attr.name = b->attrname;
2535 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2537 a->attr.mode = 0644;
2538 a->show = show_bank;
2539 a->store = set_bank;
2543 static __init int mcheck_init_device(void)
2545 int err;
2546 int i = 0;
2548 if (!mce_available(&boot_cpu_data)) {
2549 err = -EIO;
2550 goto err_out;
2553 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2554 err = -ENOMEM;
2555 goto err_out;
2558 mce_init_banks();
2560 err = subsys_system_register(&mce_subsys, NULL);
2561 if (err)
2562 goto err_out_mem;
2564 cpu_notifier_register_begin();
2565 for_each_online_cpu(i) {
2566 err = mce_device_create(i);
2567 if (err) {
2569 * Register notifier anyway (and do not unreg it) so
2570 * that we don't leave undeleted timers, see notifier
2571 * callback above.
2573 __register_hotcpu_notifier(&mce_cpu_notifier);
2574 cpu_notifier_register_done();
2575 goto err_device_create;
2579 __register_hotcpu_notifier(&mce_cpu_notifier);
2580 cpu_notifier_register_done();
2582 register_syscore_ops(&mce_syscore_ops);
2584 /* register character device /dev/mcelog */
2585 err = misc_register(&mce_chrdev_device);
2586 if (err)
2587 goto err_register;
2589 return 0;
2591 err_register:
2592 unregister_syscore_ops(&mce_syscore_ops);
2594 err_device_create:
2596 * We didn't keep track of which devices were created above, but
2597 * even if we had, the set of online cpus might have changed.
2598 * Play safe and remove for every possible cpu, since
2599 * mce_device_remove() will do the right thing.
2601 for_each_possible_cpu(i)
2602 mce_device_remove(i);
2604 err_out_mem:
2605 free_cpumask_var(mce_device_initialized);
2607 err_out:
2608 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2610 return err;
2612 device_initcall_sync(mcheck_init_device);
2615 * Old style boot options parsing. Only for compatibility.
2617 static int __init mcheck_disable(char *str)
2619 mca_cfg.disabled = true;
2620 return 1;
2622 __setup("nomce", mcheck_disable);
2624 #ifdef CONFIG_DEBUG_FS
2625 struct dentry *mce_get_debugfs_dir(void)
2627 static struct dentry *dmce;
2629 if (!dmce)
2630 dmce = debugfs_create_dir("mce", NULL);
2632 return dmce;
2635 static void mce_reset(void)
2637 cpu_missing = 0;
2638 atomic_set(&mce_fake_panicked, 0);
2639 atomic_set(&mce_executing, 0);
2640 atomic_set(&mce_callin, 0);
2641 atomic_set(&global_nwo, 0);
2644 static int fake_panic_get(void *data, u64 *val)
2646 *val = fake_panic;
2647 return 0;
2650 static int fake_panic_set(void *data, u64 val)
2652 mce_reset();
2653 fake_panic = val;
2654 return 0;
2657 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2658 fake_panic_set, "%llu\n");
2660 static int __init mcheck_debugfs_init(void)
2662 struct dentry *dmce, *ffake_panic;
2664 dmce = mce_get_debugfs_dir();
2665 if (!dmce)
2666 return -ENOMEM;
2667 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2668 &fake_panic_fops);
2669 if (!ffake_panic)
2670 return -ENOMEM;
2672 return 0;
2674 #else
2675 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2676 #endif
2678 DEFINE_STATIC_KEY_FALSE(mcsafe_key);
2679 EXPORT_SYMBOL_GPL(mcsafe_key);
2681 static int __init mcheck_late_init(void)
2683 if (mca_cfg.recovery)
2684 static_branch_inc(&mcsafe_key);
2686 mcheck_debugfs_init();
2689 * Flush out everything that has been logged during early boot, now that
2690 * everything has been initialized (workqueues, decoders, ...).
2692 mce_schedule_work();
2694 return 0;
2696 late_initcall(mcheck_late_init);