1 /*
2 * Machine check handler.
3 *
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 */
10
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12
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
45 #include <asm/processor.h>
46 #include <asm/traps.h>
47 #include <asm/tlbflush.h>
48 #include <asm/mce.h>
49 #include <asm/msr.h>
50
51 #include "mce-internal.h"
52
53 static DEFINE_MUTEX(mce_chrdev_read_mutex);
54
55 #define mce_log_get_idx_check(p) \
56 ({ \
57 RCU_LOCKDEP_WARN(!rcu_read_lock_sched_held() && \
58 !lockdep_is_held(&mce_chrdev_read_mutex), \
59 "suspicious mce_log_get_idx_check() usage"); \
60 smp_load_acquire(&(p)); \
61 })
62
63 #define CREATE_TRACE_POINTS
64 #include <trace/events/mce.h>
65
66 #define SPINUNIT 100 /* 100ns */
67
68 DEFINE_PER_CPU(unsigned, mce_exception_count);
69
70 struct mce_bank *mce_banks __read_mostly;
71 struct mce_vendor_flags mce_flags __read_mostly;
72
73 struct mca_config mca_cfg __read_mostly = {
74 .bootlog = -1,
75 /*
76 * Tolerant levels:
77 * 0: always panic on uncorrected errors, log corrected errors
78 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
79 * 2: SIGBUS or log uncorrected errors (if possible), log corr. errors
80 * 3: never panic or SIGBUS, log all errors (for testing only)
81 */
82 .tolerant = 1,
83 .monarch_timeout = -1
84 };
85
86 /* User mode helper program triggered by machine check event */
87 static unsigned long mce_need_notify;
88 static char mce_helper[128];
89 static char *mce_helper_argv[2] = { mce_helper, NULL };
90
91 static DECLARE_WAIT_QUEUE_HEAD(mce_chrdev_wait);
92
93 static DEFINE_PER_CPU(struct mce, mces_seen);
94 static int cpu_missing;
95
96 /*
97 * MCA banks polled by the period polling timer for corrected events.
98 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
99 */
100 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
101 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
102 };
103
104 /*
105 * MCA banks controlled through firmware first for corrected errors.
106 * This is a global list of banks for which we won't enable CMCI and we
107 * won't poll. Firmware controls these banks and is responsible for
108 * reporting corrected errors through GHES. Uncorrected/recoverable
109 * errors are still notified through a machine check.
110 */
111 mce_banks_t mce_banks_ce_disabled;
112
113 static struct work_struct mce_work;
114 static struct irq_work mce_irq_work;
115
116 static void (*quirk_no_way_out)(int bank, struct mce *m, struct pt_regs *regs);
117 static int mce_usable_address(struct mce *m);
118
119 /*
120 * CPU/chipset specific EDAC code can register a notifier call here to print
121 * MCE errors in a human-readable form.
122 */
123 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
124
125 /* Do initial initialization of a struct mce */
mce_setup(struct mce * m)126 void mce_setup(struct mce *m)
127 {
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);
138 }
139
140 DEFINE_PER_CPU(struct mce, injectm);
141 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
142
143 /*
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.
147 */
148
149 static struct mce_log mcelog = {
150 .signature = MCE_LOG_SIGNATURE,
151 .len = MCE_LOG_LEN,
152 .recordlen = sizeof(struct mce),
153 };
154
mce_log(struct mce * mce)155 void mce_log(struct mce *mce)
156 {
157 unsigned next, entry;
158
159 /* Emit the trace record: */
160 trace_mce_record(mce);
161
162 if (!mce_gen_pool_add(mce))
163 irq_work_queue(&mce_irq_work);
164
165 mce->finished = 0;
166 wmb();
167 for (;;) {
168 entry = mce_log_get_idx_check(mcelog.next);
169 for (;;) {
170
171 /*
172 * When the buffer fills up discard new entries.
173 * Assume that the earlier errors are the more
174 * interesting ones:
175 */
176 if (entry >= MCE_LOG_LEN) {
177 set_bit(MCE_OVERFLOW,
178 (unsigned long *)&mcelog.flags);
179 return;
180 }
181 /* Old left over entry. Skip: */
182 if (mcelog.entry[entry].finished) {
183 entry++;
184 continue;
185 }
186 break;
187 }
188 smp_rmb();
189 next = entry + 1;
190 if (cmpxchg(&mcelog.next, entry, next) == entry)
191 break;
192 }
193 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
194 wmb();
195 mcelog.entry[entry].finished = 1;
196 wmb();
197
198 mce->finished = 1;
199 set_bit(0, &mce_need_notify);
200 }
201
mce_inject_log(struct mce * m)202 void mce_inject_log(struct mce *m)
203 {
204 mutex_lock(&mce_chrdev_read_mutex);
205 mce_log(m);
206 mutex_unlock(&mce_chrdev_read_mutex);
207 }
208 EXPORT_SYMBOL_GPL(mce_inject_log);
209
210 static struct notifier_block mce_srao_nb;
211
mce_register_decode_chain(struct notifier_block * nb)212 void mce_register_decode_chain(struct notifier_block *nb)
213 {
214 /* Ensure SRAO notifier has the highest priority in the decode chain. */
215 if (nb != &mce_srao_nb && nb->priority == INT_MAX)
216 nb->priority -= 1;
217
218 atomic_notifier_chain_register(&x86_mce_decoder_chain, nb);
219 }
220 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
221
mce_unregister_decode_chain(struct notifier_block * nb)222 void mce_unregister_decode_chain(struct notifier_block *nb)
223 {
224 atomic_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
225 }
226 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
227
print_mce(struct mce * m)228 static void print_mce(struct mce *m)
229 {
230 int ret = 0;
231
232 pr_emerg(HW_ERR "CPU %d: Machine Check Exception: %Lx Bank %d: %016Lx\n",
233 m->extcpu, m->mcgstatus, m->bank, m->status);
234
235 if (m->ip) {
236 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
237 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
238 m->cs, m->ip);
239
240 if (m->cs == __KERNEL_CS)
241 print_symbol("{%s}", m->ip);
242 pr_cont("\n");
243 }
244
245 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
246 if (m->addr)
247 pr_cont("ADDR %llx ", m->addr);
248 if (m->misc)
249 pr_cont("MISC %llx ", m->misc);
250
251 pr_cont("\n");
252 /*
253 * Note this output is parsed by external tools and old fields
254 * should not be changed.
255 */
256 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
257 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
258 cpu_data(m->extcpu).microcode);
259
260 /*
261 * Print out human-readable details about the MCE error,
262 * (if the CPU has an implementation for that)
263 */
264 ret = atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
265 if (ret == NOTIFY_STOP)
266 return;
267
268 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
269 }
270
271 #define PANIC_TIMEOUT 5 /* 5 seconds */
272
273 static atomic_t mce_panicked;
274
275 static int fake_panic;
276 static atomic_t mce_fake_panicked;
277
278 /* Panic in progress. Enable interrupts and wait for final IPI */
wait_for_panic(void)279 static void wait_for_panic(void)
280 {
281 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
282
283 preempt_disable();
284 local_irq_enable();
285 while (timeout-- > 0)
286 udelay(1);
287 if (panic_timeout == 0)
288 panic_timeout = mca_cfg.panic_timeout;
289 panic("Panicing machine check CPU died");
290 }
291
mce_panic(const char * msg,struct mce * final,char * exp)292 static void mce_panic(const char *msg, struct mce *final, char *exp)
293 {
294 int i, apei_err = 0;
295
296 if (!fake_panic) {
297 /*
298 * Make sure only one CPU runs in machine check panic
299 */
300 if (atomic_inc_return(&mce_panicked) > 1)
301 wait_for_panic();
302 barrier();
303
304 bust_spinlocks(1);
305 console_verbose();
306 } else {
307 /* Don't log too much for fake panic */
308 if (atomic_inc_return(&mce_fake_panicked) > 1)
309 return;
310 }
311 /* First print corrected ones that are still unlogged */
312 for (i = 0; i < MCE_LOG_LEN; i++) {
313 struct mce *m = &mcelog.entry[i];
314 if (!(m->status & MCI_STATUS_VAL))
315 continue;
316 if (!(m->status & MCI_STATUS_UC)) {
317 print_mce(m);
318 if (!apei_err)
319 apei_err = apei_write_mce(m);
320 }
321 }
322 /* Now print uncorrected but with the final one last */
323 for (i = 0; i < MCE_LOG_LEN; i++) {
324 struct mce *m = &mcelog.entry[i];
325 if (!(m->status & MCI_STATUS_VAL))
326 continue;
327 if (!(m->status & MCI_STATUS_UC))
328 continue;
329 if (!final || memcmp(m, final, sizeof(struct mce))) {
330 print_mce(m);
331 if (!apei_err)
332 apei_err = apei_write_mce(m);
333 }
334 }
335 if (final) {
336 print_mce(final);
337 if (!apei_err)
338 apei_err = apei_write_mce(final);
339 }
340 if (cpu_missing)
341 pr_emerg(HW_ERR "Some CPUs didn't answer in synchronization\n");
342 if (exp)
343 pr_emerg(HW_ERR "Machine check: %s\n", exp);
344 if (!fake_panic) {
345 if (panic_timeout == 0)
346 panic_timeout = mca_cfg.panic_timeout;
347 panic(msg);
348 } else
349 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
350 }
351
352 /* Support code for software error injection */
353
msr_to_offset(u32 msr)354 static int msr_to_offset(u32 msr)
355 {
356 unsigned bank = __this_cpu_read(injectm.bank);
357
358 if (msr == mca_cfg.rip_msr)
359 return offsetof(struct mce, ip);
360 if (msr == MSR_IA32_MCx_STATUS(bank))
361 return offsetof(struct mce, status);
362 if (msr == MSR_IA32_MCx_ADDR(bank))
363 return offsetof(struct mce, addr);
364 if (msr == MSR_IA32_MCx_MISC(bank))
365 return offsetof(struct mce, misc);
366 if (msr == MSR_IA32_MCG_STATUS)
367 return offsetof(struct mce, mcgstatus);
368 return -1;
369 }
370
371 /* MSR access wrappers used for error injection */
mce_rdmsrl(u32 msr)372 static u64 mce_rdmsrl(u32 msr)
373 {
374 u64 v;
375
376 if (__this_cpu_read(injectm.finished)) {
377 int offset = msr_to_offset(msr);
378
379 if (offset < 0)
380 return 0;
381 return *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
382 }
383
384 if (rdmsrl_safe(msr, &v)) {
385 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
386 /*
387 * Return zero in case the access faulted. This should
388 * not happen normally but can happen if the CPU does
389 * something weird, or if the code is buggy.
390 */
391 v = 0;
392 }
393
394 return v;
395 }
396
mce_wrmsrl(u32 msr,u64 v)397 static void mce_wrmsrl(u32 msr, u64 v)
398 {
399 if (__this_cpu_read(injectm.finished)) {
400 int offset = msr_to_offset(msr);
401
402 if (offset >= 0)
403 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
404 return;
405 }
406 wrmsrl(msr, v);
407 }
408
409 /*
410 * Collect all global (w.r.t. this processor) status about this machine
411 * check into our "mce" struct so that we can use it later to assess
412 * the severity of the problem as we read per-bank specific details.
413 */
mce_gather_info(struct mce * m,struct pt_regs * regs)414 static inline void mce_gather_info(struct mce *m, struct pt_regs *regs)
415 {
416 mce_setup(m);
417
418 m->mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
419 if (regs) {
420 /*
421 * Get the address of the instruction at the time of
422 * the machine check error.
423 */
424 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
425 m->ip = regs->ip;
426 m->cs = regs->cs;
427
428 /*
429 * When in VM86 mode make the cs look like ring 3
430 * always. This is a lie, but it's better than passing
431 * the additional vm86 bit around everywhere.
432 */
433 if (v8086_mode(regs))
434 m->cs |= 3;
435 }
436 /* Use accurate RIP reporting if available. */
437 if (mca_cfg.rip_msr)
438 m->ip = mce_rdmsrl(mca_cfg.rip_msr);
439 }
440 }
441
mce_available(struct cpuinfo_x86 * c)442 int mce_available(struct cpuinfo_x86 *c)
443 {
444 if (mca_cfg.disabled)
445 return 0;
446 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
447 }
448
mce_schedule_work(void)449 static void mce_schedule_work(void)
450 {
451 if (!mce_gen_pool_empty() && keventd_up())
452 schedule_work(&mce_work);
453 }
454
mce_irq_work_cb(struct irq_work * entry)455 static void mce_irq_work_cb(struct irq_work *entry)
456 {
457 mce_notify_irq();
458 mce_schedule_work();
459 }
460
mce_report_event(struct pt_regs * regs)461 static void mce_report_event(struct pt_regs *regs)
462 {
463 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
464 mce_notify_irq();
465 /*
466 * Triggering the work queue here is just an insurance
467 * policy in case the syscall exit notify handler
468 * doesn't run soon enough or ends up running on the
469 * wrong CPU (can happen when audit sleeps)
470 */
471 mce_schedule_work();
472 return;
473 }
474
475 irq_work_queue(&mce_irq_work);
476 }
477
srao_decode_notifier(struct notifier_block * nb,unsigned long val,void * data)478 static int srao_decode_notifier(struct notifier_block *nb, unsigned long val,
479 void *data)
480 {
481 struct mce *mce = (struct mce *)data;
482 unsigned long pfn;
483
484 if (!mce)
485 return NOTIFY_DONE;
486
487 if (mce->usable_addr && (mce->severity == MCE_AO_SEVERITY)) {
488 pfn = mce->addr >> PAGE_SHIFT;
489 memory_failure(pfn, MCE_VECTOR, 0);
490 }
491
492 return NOTIFY_OK;
493 }
494 static struct notifier_block mce_srao_nb = {
495 .notifier_call = srao_decode_notifier,
496 .priority = INT_MAX,
497 };
498
499 /*
500 * Read ADDR and MISC registers.
501 */
mce_read_aux(struct mce * m,int i)502 static void mce_read_aux(struct mce *m, int i)
503 {
504 if (m->status & MCI_STATUS_MISCV)
505 m->misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
506 if (m->status & MCI_STATUS_ADDRV) {
507 m->addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
508
509 /*
510 * Mask the reported address by the reported granularity.
511 */
512 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
513 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
514 m->addr >>= shift;
515 m->addr <<= shift;
516 }
517 }
518 }
519
memory_error(struct mce * m)520 static bool memory_error(struct mce *m)
521 {
522 struct cpuinfo_x86 *c = &boot_cpu_data;
523
524 if (c->x86_vendor == X86_VENDOR_AMD) {
525 /*
526 * coming soon
527 */
528 return false;
529 } else if (c->x86_vendor == X86_VENDOR_INTEL) {
530 /*
531 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
532 *
533 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
534 * indicating a memory error. Bit 8 is used for indicating a
535 * cache hierarchy error. The combination of bit 2 and bit 3
536 * is used for indicating a `generic' cache hierarchy error
537 * But we can't just blindly check the above bits, because if
538 * bit 11 is set, then it is a bus/interconnect error - and
539 * either way the above bits just gives more detail on what
540 * bus/interconnect error happened. Note that bit 12 can be
541 * ignored, as it's the "filter" bit.
542 */
543 return (m->status & 0xef80) == BIT(7) ||
544 (m->status & 0xef00) == BIT(8) ||
545 (m->status & 0xeffc) == 0xc;
546 }
547
548 return false;
549 }
550
551 DEFINE_PER_CPU(unsigned, mce_poll_count);
552
553 /*
554 * Poll for corrected events or events that happened before reset.
555 * Those are just logged through /dev/mcelog.
556 *
557 * This is executed in standard interrupt context.
558 *
559 * Note: spec recommends to panic for fatal unsignalled
560 * errors here. However this would be quite problematic --
561 * we would need to reimplement the Monarch handling and
562 * it would mess up the exclusion between exception handler
563 * and poll hander -- * so we skip this for now.
564 * These cases should not happen anyways, or only when the CPU
565 * is already totally * confused. In this case it's likely it will
566 * not fully execute the machine check handler either.
567 */
machine_check_poll(enum mcp_flags flags,mce_banks_t * b)568 bool machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
569 {
570 bool error_logged = false;
571 struct mce m;
572 int severity;
573 int i;
574
575 this_cpu_inc(mce_poll_count);
576
577 mce_gather_info(&m, NULL);
578
579 for (i = 0; i < mca_cfg.banks; i++) {
580 if (!mce_banks[i].ctl || !test_bit(i, *b))
581 continue;
582
583 m.misc = 0;
584 m.addr = 0;
585 m.bank = i;
586 m.tsc = 0;
587
588 barrier();
589 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
590 if (!(m.status & MCI_STATUS_VAL))
591 continue;
592
593
594 /*
595 * Uncorrected or signalled events are handled by the exception
596 * handler when it is enabled, so don't process those here.
597 *
598 * TBD do the same check for MCI_STATUS_EN here?
599 */
600 if (!(flags & MCP_UC) &&
601 (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
602 continue;
603
604 mce_read_aux(&m, i);
605
606 if (!(flags & MCP_TIMESTAMP))
607 m.tsc = 0;
608
609 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
610
611 /*
612 * In the cases where we don't have a valid address after all,
613 * do not add it into the ring buffer.
614 */
615 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m)) {
616 if (m.status & MCI_STATUS_ADDRV) {
617 m.severity = severity;
618 m.usable_addr = mce_usable_address(&m);
619
620 if (!mce_gen_pool_add(&m))
621 mce_schedule_work();
622 }
623 }
624
625 /*
626 * Don't get the IP here because it's unlikely to
627 * have anything to do with the actual error location.
628 */
629 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce) {
630 error_logged = true;
631 mce_log(&m);
632 }
633
634 /*
635 * Clear state for this bank.
636 */
637 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
638 }
639
640 /*
641 * Don't clear MCG_STATUS here because it's only defined for
642 * exceptions.
643 */
644
645 sync_core();
646
647 return error_logged;
648 }
649 EXPORT_SYMBOL_GPL(machine_check_poll);
650
651 /*
652 * Do a quick check if any of the events requires a panic.
653 * This decides if we keep the events around or clear them.
654 */
mce_no_way_out(struct mce * m,char ** msg,unsigned long * validp,struct pt_regs * regs)655 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
656 struct pt_regs *regs)
657 {
658 int i, ret = 0;
659 char *tmp;
660
661 for (i = 0; i < mca_cfg.banks; i++) {
662 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
663 if (m->status & MCI_STATUS_VAL) {
664 __set_bit(i, validp);
665 if (quirk_no_way_out)
666 quirk_no_way_out(i, m, regs);
667 }
668
669 if (mce_severity(m, mca_cfg.tolerant, &tmp, true) >= MCE_PANIC_SEVERITY) {
670 *msg = tmp;
671 ret = 1;
672 }
673 }
674 return ret;
675 }
676
677 /*
678 * Variable to establish order between CPUs while scanning.
679 * Each CPU spins initially until executing is equal its number.
680 */
681 static atomic_t mce_executing;
682
683 /*
684 * Defines order of CPUs on entry. First CPU becomes Monarch.
685 */
686 static atomic_t mce_callin;
687
688 /*
689 * Check if a timeout waiting for other CPUs happened.
690 */
mce_timed_out(u64 * t,const char * msg)691 static int mce_timed_out(u64 *t, const char *msg)
692 {
693 /*
694 * The others already did panic for some reason.
695 * Bail out like in a timeout.
696 * rmb() to tell the compiler that system_state
697 * might have been modified by someone else.
698 */
699 rmb();
700 if (atomic_read(&mce_panicked))
701 wait_for_panic();
702 if (!mca_cfg.monarch_timeout)
703 goto out;
704 if ((s64)*t < SPINUNIT) {
705 if (mca_cfg.tolerant <= 1)
706 mce_panic(msg, NULL, NULL);
707 cpu_missing = 1;
708 return 1;
709 }
710 *t -= SPINUNIT;
711 out:
712 touch_nmi_watchdog();
713 return 0;
714 }
715
716 /*
717 * The Monarch's reign. The Monarch is the CPU who entered
718 * the machine check handler first. It waits for the others to
719 * raise the exception too and then grades them. When any
720 * error is fatal panic. Only then let the others continue.
721 *
722 * The other CPUs entering the MCE handler will be controlled by the
723 * Monarch. They are called Subjects.
724 *
725 * This way we prevent any potential data corruption in a unrecoverable case
726 * and also makes sure always all CPU's errors are examined.
727 *
728 * Also this detects the case of a machine check event coming from outer
729 * space (not detected by any CPUs) In this case some external agent wants
730 * us to shut down, so panic too.
731 *
732 * The other CPUs might still decide to panic if the handler happens
733 * in a unrecoverable place, but in this case the system is in a semi-stable
734 * state and won't corrupt anything by itself. It's ok to let the others
735 * continue for a bit first.
736 *
737 * All the spin loops have timeouts; when a timeout happens a CPU
738 * typically elects itself to be Monarch.
739 */
mce_reign(void)740 static void mce_reign(void)
741 {
742 int cpu;
743 struct mce *m = NULL;
744 int global_worst = 0;
745 char *msg = NULL;
746 char *nmsg = NULL;
747
748 /*
749 * This CPU is the Monarch and the other CPUs have run
750 * through their handlers.
751 * Grade the severity of the errors of all the CPUs.
752 */
753 for_each_possible_cpu(cpu) {
754 int severity = mce_severity(&per_cpu(mces_seen, cpu),
755 mca_cfg.tolerant,
756 &nmsg, true);
757 if (severity > global_worst) {
758 msg = nmsg;
759 global_worst = severity;
760 m = &per_cpu(mces_seen, cpu);
761 }
762 }
763
764 /*
765 * Cannot recover? Panic here then.
766 * This dumps all the mces in the log buffer and stops the
767 * other CPUs.
768 */
769 if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
770 mce_panic("Fatal machine check", m, msg);
771
772 /*
773 * For UC somewhere we let the CPU who detects it handle it.
774 * Also must let continue the others, otherwise the handling
775 * CPU could deadlock on a lock.
776 */
777
778 /*
779 * No machine check event found. Must be some external
780 * source or one CPU is hung. Panic.
781 */
782 if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
783 mce_panic("Fatal machine check from unknown source", NULL, NULL);
784
785 /*
786 * Now clear all the mces_seen so that they don't reappear on
787 * the next mce.
788 */
789 for_each_possible_cpu(cpu)
790 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
791 }
792
793 static atomic_t global_nwo;
794
795 /*
796 * Start of Monarch synchronization. This waits until all CPUs have
797 * entered the exception handler and then determines if any of them
798 * saw a fatal event that requires panic. Then it executes them
799 * in the entry order.
800 * TBD double check parallel CPU hotunplug
801 */
mce_start(int * no_way_out)802 static int mce_start(int *no_way_out)
803 {
804 int order;
805 int cpus = num_online_cpus();
806 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
807
808 if (!timeout)
809 return -1;
810
811 atomic_add(*no_way_out, &global_nwo);
812 /*
813 * global_nwo should be updated before mce_callin
814 */
815 smp_wmb();
816 order = atomic_inc_return(&mce_callin);
817
818 /*
819 * Wait for everyone.
820 */
821 while (atomic_read(&mce_callin) != cpus) {
822 if (mce_timed_out(&timeout,
823 "Timeout: Not all CPUs entered broadcast exception handler")) {
824 atomic_set(&global_nwo, 0);
825 return -1;
826 }
827 ndelay(SPINUNIT);
828 }
829
830 /*
831 * mce_callin should be read before global_nwo
832 */
833 smp_rmb();
834
835 if (order == 1) {
836 /*
837 * Monarch: Starts executing now, the others wait.
838 */
839 atomic_set(&mce_executing, 1);
840 } else {
841 /*
842 * Subject: Now start the scanning loop one by one in
843 * the original callin order.
844 * This way when there are any shared banks it will be
845 * only seen by one CPU before cleared, avoiding duplicates.
846 */
847 while (atomic_read(&mce_executing) < order) {
848 if (mce_timed_out(&timeout,
849 "Timeout: Subject CPUs unable to finish machine check processing")) {
850 atomic_set(&global_nwo, 0);
851 return -1;
852 }
853 ndelay(SPINUNIT);
854 }
855 }
856
857 /*
858 * Cache the global no_way_out state.
859 */
860 *no_way_out = atomic_read(&global_nwo);
861
862 return order;
863 }
864
865 /*
866 * Synchronize between CPUs after main scanning loop.
867 * This invokes the bulk of the Monarch processing.
868 */
mce_end(int order)869 static int mce_end(int order)
870 {
871 int ret = -1;
872 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
873
874 if (!timeout)
875 goto reset;
876 if (order < 0)
877 goto reset;
878
879 /*
880 * Allow others to run.
881 */
882 atomic_inc(&mce_executing);
883
884 if (order == 1) {
885 /* CHECKME: Can this race with a parallel hotplug? */
886 int cpus = num_online_cpus();
887
888 /*
889 * Monarch: Wait for everyone to go through their scanning
890 * loops.
891 */
892 while (atomic_read(&mce_executing) <= cpus) {
893 if (mce_timed_out(&timeout,
894 "Timeout: Monarch CPU unable to finish machine check processing"))
895 goto reset;
896 ndelay(SPINUNIT);
897 }
898
899 mce_reign();
900 barrier();
901 ret = 0;
902 } else {
903 /*
904 * Subject: Wait for Monarch to finish.
905 */
906 while (atomic_read(&mce_executing) != 0) {
907 if (mce_timed_out(&timeout,
908 "Timeout: Monarch CPU did not finish machine check processing"))
909 goto reset;
910 ndelay(SPINUNIT);
911 }
912
913 /*
914 * Don't reset anything. That's done by the Monarch.
915 */
916 return 0;
917 }
918
919 /*
920 * Reset all global state.
921 */
922 reset:
923 atomic_set(&global_nwo, 0);
924 atomic_set(&mce_callin, 0);
925 barrier();
926
927 /*
928 * Let others run again.
929 */
930 atomic_set(&mce_executing, 0);
931 return ret;
932 }
933
934 /*
935 * Check if the address reported by the CPU is in a format we can parse.
936 * It would be possible to add code for most other cases, but all would
937 * be somewhat complicated (e.g. segment offset would require an instruction
938 * parser). So only support physical addresses up to page granuality for now.
939 */
mce_usable_address(struct mce * m)940 static int mce_usable_address(struct mce *m)
941 {
942 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
943 return 0;
944 if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
945 return 0;
946 if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
947 return 0;
948 return 1;
949 }
950
mce_clear_state(unsigned long * toclear)951 static void mce_clear_state(unsigned long *toclear)
952 {
953 int i;
954
955 for (i = 0; i < mca_cfg.banks; i++) {
956 if (test_bit(i, toclear))
957 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
958 }
959 }
960
961 /*
962 * The actual machine check handler. This only handles real
963 * exceptions when something got corrupted coming in through int 18.
964 *
965 * This is executed in NMI context not subject to normal locking rules. This
966 * implies that most kernel services cannot be safely used. Don't even
967 * think about putting a printk in there!
968 *
969 * On Intel systems this is entered on all CPUs in parallel through
970 * MCE broadcast. However some CPUs might be broken beyond repair,
971 * so be always careful when synchronizing with others.
972 */
do_machine_check(struct pt_regs * regs,long error_code)973 void do_machine_check(struct pt_regs *regs, long error_code)
974 {
975 struct mca_config *cfg = &mca_cfg;
976 struct mce m, *final;
977 int i;
978 int worst = 0;
979 int severity;
980 /*
981 * Establish sequential order between the CPUs entering the machine
982 * check handler.
983 */
984 int order;
985 /*
986 * If no_way_out gets set, there is no safe way to recover from this
987 * MCE. If mca_cfg.tolerant is cranked up, we'll try anyway.
988 */
989 int no_way_out = 0;
990 /*
991 * If kill_it gets set, there might be a way to recover from this
992 * error.
993 */
994 int kill_it = 0;
995 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
996 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
997 char *msg = "Unknown";
998 u64 recover_paddr = ~0ull;
999 int flags = MF_ACTION_REQUIRED;
1000 int lmce = 0;
1001
1002 /* If this CPU is offline, just bail out. */
1003 if (cpu_is_offline(smp_processor_id())) {
1004 u64 mcgstatus;
1005
1006 mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
1007 if (mcgstatus & MCG_STATUS_RIPV) {
1008 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1009 return;
1010 }
1011 }
1012
1013 ist_enter(regs);
1014
1015 this_cpu_inc(mce_exception_count);
1016
1017 if (!cfg->banks)
1018 goto out;
1019
1020 mce_gather_info(&m, regs);
1021
1022 final = this_cpu_ptr(&mces_seen);
1023 *final = m;
1024
1025 memset(valid_banks, 0, sizeof(valid_banks));
1026 no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1027
1028 barrier();
1029
1030 /*
1031 * When no restart IP might need to kill or panic.
1032 * Assume the worst for now, but if we find the
1033 * severity is MCE_AR_SEVERITY we have other options.
1034 */
1035 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1036 kill_it = 1;
1037
1038 /*
1039 * Check if this MCE is signaled to only this logical processor
1040 */
1041 if (m.mcgstatus & MCG_STATUS_LMCES)
1042 lmce = 1;
1043 else {
1044 /*
1045 * Go through all the banks in exclusion of the other CPUs.
1046 * This way we don't report duplicated events on shared banks
1047 * because the first one to see it will clear it.
1048 * If this is a Local MCE, then no need to perform rendezvous.
1049 */
1050 order = mce_start(&no_way_out);
1051 }
1052
1053 for (i = 0; i < cfg->banks; i++) {
1054 __clear_bit(i, toclear);
1055 if (!test_bit(i, valid_banks))
1056 continue;
1057 if (!mce_banks[i].ctl)
1058 continue;
1059
1060 m.misc = 0;
1061 m.addr = 0;
1062 m.bank = i;
1063
1064 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1065 if ((m.status & MCI_STATUS_VAL) == 0)
1066 continue;
1067
1068 /*
1069 * Non uncorrected or non signaled errors are handled by
1070 * machine_check_poll. Leave them alone, unless this panics.
1071 */
1072 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1073 !no_way_out)
1074 continue;
1075
1076 /*
1077 * Set taint even when machine check was not enabled.
1078 */
1079 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1080
1081 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1082
1083 /*
1084 * When machine check was for corrected/deferred handler don't
1085 * touch, unless we're panicing.
1086 */
1087 if ((severity == MCE_KEEP_SEVERITY ||
1088 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1089 continue;
1090 __set_bit(i, toclear);
1091 if (severity == MCE_NO_SEVERITY) {
1092 /*
1093 * Machine check event was not enabled. Clear, but
1094 * ignore.
1095 */
1096 continue;
1097 }
1098
1099 mce_read_aux(&m, i);
1100
1101 /* assuming valid severity level != 0 */
1102 m.severity = severity;
1103 m.usable_addr = mce_usable_address(&m);
1104
1105 mce_log(&m);
1106
1107 if (severity > worst) {
1108 *final = m;
1109 worst = severity;
1110 }
1111 }
1112
1113 /* mce_clear_state will clear *final, save locally for use later */
1114 m = *final;
1115
1116 if (!no_way_out)
1117 mce_clear_state(toclear);
1118
1119 /*
1120 * Do most of the synchronization with other CPUs.
1121 * When there's any problem use only local no_way_out state.
1122 */
1123 if (!lmce) {
1124 if (mce_end(order) < 0)
1125 no_way_out = worst >= MCE_PANIC_SEVERITY;
1126 } else {
1127 /*
1128 * Local MCE skipped calling mce_reign()
1129 * If we found a fatal error, we need to panic here.
1130 */
1131 if (worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
1132 mce_panic("Machine check from unknown source",
1133 NULL, NULL);
1134 }
1135
1136 /*
1137 * At insane "tolerant" levels we take no action. Otherwise
1138 * we only die if we have no other choice. For less serious
1139 * issues we try to recover, or limit damage to the current
1140 * process.
1141 */
1142 if (cfg->tolerant < 3) {
1143 if (no_way_out)
1144 mce_panic("Fatal machine check on current CPU", &m, msg);
1145 if (worst == MCE_AR_SEVERITY) {
1146 recover_paddr = m.addr;
1147 if (!(m.mcgstatus & MCG_STATUS_RIPV))
1148 flags |= MF_MUST_KILL;
1149 } else if (kill_it) {
1150 force_sig(SIGBUS, current);
1151 }
1152 }
1153
1154 if (worst > 0)
1155 mce_report_event(regs);
1156 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1157 out:
1158 sync_core();
1159
1160 if (recover_paddr == ~0ull)
1161 goto done;
1162
1163 pr_err("Uncorrected hardware memory error in user-access at %llx",
1164 recover_paddr);
1165 /*
1166 * We must call memory_failure() here even if the current process is
1167 * doomed. We still need to mark the page as poisoned and alert any
1168 * other users of the page.
1169 */
1170 ist_begin_non_atomic(regs);
1171 local_irq_enable();
1172 if (memory_failure(recover_paddr >> PAGE_SHIFT, MCE_VECTOR, flags) < 0) {
1173 pr_err("Memory error not recovered");
1174 force_sig(SIGBUS, current);
1175 }
1176 local_irq_disable();
1177 ist_end_non_atomic();
1178 done:
1179 ist_exit(regs);
1180 }
1181 EXPORT_SYMBOL_GPL(do_machine_check);
1182
1183 #ifndef CONFIG_MEMORY_FAILURE
memory_failure(unsigned long pfn,int vector,int flags)1184 int memory_failure(unsigned long pfn, int vector, int flags)
1185 {
1186 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1187 BUG_ON(flags & MF_ACTION_REQUIRED);
1188 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1189 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1190 pfn);
1191
1192 return 0;
1193 }
1194 #endif
1195
1196 /*
1197 * Action optional processing happens here (picking up
1198 * from the list of faulting pages that do_machine_check()
1199 * placed into the genpool).
1200 */
mce_process_work(struct work_struct * dummy)1201 static void mce_process_work(struct work_struct *dummy)
1202 {
1203 mce_gen_pool_process();
1204 }
1205
1206 #ifdef CONFIG_X86_MCE_INTEL
1207 /***
1208 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1209 * @cpu: The CPU on which the event occurred.
1210 * @status: Event status information
1211 *
1212 * This function should be called by the thermal interrupt after the
1213 * event has been processed and the decision was made to log the event
1214 * further.
1215 *
1216 * The status parameter will be saved to the 'status' field of 'struct mce'
1217 * and historically has been the register value of the
1218 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1219 */
mce_log_therm_throt_event(__u64 status)1220 void mce_log_therm_throt_event(__u64 status)
1221 {
1222 struct mce m;
1223
1224 mce_setup(&m);
1225 m.bank = MCE_THERMAL_BANK;
1226 m.status = status;
1227 mce_log(&m);
1228 }
1229 #endif /* CONFIG_X86_MCE_INTEL */
1230
1231 /*
1232 * Periodic polling timer for "silent" machine check errors. If the
1233 * poller finds an MCE, poll 2x faster. When the poller finds no more
1234 * errors, poll 2x slower (up to check_interval seconds).
1235 */
1236 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1237
1238 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1239 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1240
mce_adjust_timer_default(unsigned long interval)1241 static unsigned long mce_adjust_timer_default(unsigned long interval)
1242 {
1243 return interval;
1244 }
1245
1246 static unsigned long (*mce_adjust_timer)(unsigned long interval) = mce_adjust_timer_default;
1247
__restart_timer(struct timer_list * t,unsigned long interval)1248 static void __restart_timer(struct timer_list *t, unsigned long interval)
1249 {
1250 unsigned long when = jiffies + interval;
1251 unsigned long flags;
1252
1253 local_irq_save(flags);
1254
1255 if (timer_pending(t)) {
1256 if (time_before(when, t->expires))
1257 mod_timer_pinned(t, when);
1258 } else {
1259 t->expires = round_jiffies(when);
1260 add_timer_on(t, smp_processor_id());
1261 }
1262
1263 local_irq_restore(flags);
1264 }
1265
mce_timer_fn(unsigned long data)1266 static void mce_timer_fn(unsigned long data)
1267 {
1268 struct timer_list *t = this_cpu_ptr(&mce_timer);
1269 int cpu = smp_processor_id();
1270 unsigned long iv;
1271
1272 WARN_ON(cpu != data);
1273
1274 iv = __this_cpu_read(mce_next_interval);
1275
1276 if (mce_available(this_cpu_ptr(&cpu_info))) {
1277 machine_check_poll(MCP_TIMESTAMP, this_cpu_ptr(&mce_poll_banks));
1278
1279 if (mce_intel_cmci_poll()) {
1280 iv = mce_adjust_timer(iv);
1281 goto done;
1282 }
1283 }
1284
1285 /*
1286 * Alert userspace if needed. If we logged an MCE, reduce the polling
1287 * interval, otherwise increase the polling interval.
1288 */
1289 if (mce_notify_irq())
1290 iv = max(iv / 2, (unsigned long) HZ/100);
1291 else
1292 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1293
1294 done:
1295 __this_cpu_write(mce_next_interval, iv);
1296 __restart_timer(t, iv);
1297 }
1298
1299 /*
1300 * Ensure that the timer is firing in @interval from now.
1301 */
mce_timer_kick(unsigned long interval)1302 void mce_timer_kick(unsigned long interval)
1303 {
1304 struct timer_list *t = this_cpu_ptr(&mce_timer);
1305 unsigned long iv = __this_cpu_read(mce_next_interval);
1306
1307 __restart_timer(t, interval);
1308
1309 if (interval < iv)
1310 __this_cpu_write(mce_next_interval, interval);
1311 }
1312
1313 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
mce_timer_delete_all(void)1314 static void mce_timer_delete_all(void)
1315 {
1316 int cpu;
1317
1318 for_each_online_cpu(cpu)
1319 del_timer_sync(&per_cpu(mce_timer, cpu));
1320 }
1321
mce_do_trigger(struct work_struct * work)1322 static void mce_do_trigger(struct work_struct *work)
1323 {
1324 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1325 }
1326
1327 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1328
1329 /*
1330 * Notify the user(s) about new machine check events.
1331 * Can be called from interrupt context, but not from machine check/NMI
1332 * context.
1333 */
mce_notify_irq(void)1334 int mce_notify_irq(void)
1335 {
1336 /* Not more than two messages every minute */
1337 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1338
1339 if (test_and_clear_bit(0, &mce_need_notify)) {
1340 /* wake processes polling /dev/mcelog */
1341 wake_up_interruptible(&mce_chrdev_wait);
1342
1343 if (mce_helper[0])
1344 schedule_work(&mce_trigger_work);
1345
1346 if (__ratelimit(&ratelimit))
1347 pr_info(HW_ERR "Machine check events logged\n");
1348
1349 return 1;
1350 }
1351 return 0;
1352 }
1353 EXPORT_SYMBOL_GPL(mce_notify_irq);
1354
__mcheck_cpu_mce_banks_init(void)1355 static int __mcheck_cpu_mce_banks_init(void)
1356 {
1357 int i;
1358 u8 num_banks = mca_cfg.banks;
1359
1360 mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1361 if (!mce_banks)
1362 return -ENOMEM;
1363
1364 for (i = 0; i < num_banks; i++) {
1365 struct mce_bank *b = &mce_banks[i];
1366
1367 b->ctl = -1ULL;
1368 b->init = 1;
1369 }
1370 return 0;
1371 }
1372
1373 /*
1374 * Initialize Machine Checks for a CPU.
1375 */
__mcheck_cpu_cap_init(void)1376 static int __mcheck_cpu_cap_init(void)
1377 {
1378 unsigned b;
1379 u64 cap;
1380
1381 rdmsrl(MSR_IA32_MCG_CAP, cap);
1382
1383 b = cap & MCG_BANKCNT_MASK;
1384 if (!mca_cfg.banks)
1385 pr_info("CPU supports %d MCE banks\n", b);
1386
1387 if (b > MAX_NR_BANKS) {
1388 pr_warn("Using only %u machine check banks out of %u\n",
1389 MAX_NR_BANKS, b);
1390 b = MAX_NR_BANKS;
1391 }
1392
1393 /* Don't support asymmetric configurations today */
1394 WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1395 mca_cfg.banks = b;
1396
1397 if (!mce_banks) {
1398 int err = __mcheck_cpu_mce_banks_init();
1399
1400 if (err)
1401 return err;
1402 }
1403
1404 /* Use accurate RIP reporting if available. */
1405 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1406 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1407
1408 if (cap & MCG_SER_P)
1409 mca_cfg.ser = true;
1410
1411 return 0;
1412 }
1413
__mcheck_cpu_init_generic(void)1414 static void __mcheck_cpu_init_generic(void)
1415 {
1416 enum mcp_flags m_fl = 0;
1417 mce_banks_t all_banks;
1418 u64 cap;
1419 int i;
1420
1421 if (!mca_cfg.bootlog)
1422 m_fl = MCP_DONTLOG;
1423
1424 /*
1425 * Log the machine checks left over from the previous reset.
1426 */
1427 bitmap_fill(all_banks, MAX_NR_BANKS);
1428 machine_check_poll(MCP_UC | m_fl, &all_banks);
1429
1430 cr4_set_bits(X86_CR4_MCE);
1431
1432 rdmsrl(MSR_IA32_MCG_CAP, cap);
1433 if (cap & MCG_CTL_P)
1434 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1435
1436 for (i = 0; i < mca_cfg.banks; i++) {
1437 struct mce_bank *b = &mce_banks[i];
1438
1439 if (!b->init)
1440 continue;
1441 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1442 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1443 }
1444 }
1445
1446 /*
1447 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1448 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1449 * Vol 3B Table 15-20). But this confuses both the code that determines
1450 * whether the machine check occurred in kernel or user mode, and also
1451 * the severity assessment code. Pretend that EIPV was set, and take the
1452 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1453 */
quirk_sandybridge_ifu(int bank,struct mce * m,struct pt_regs * regs)1454 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1455 {
1456 if (bank != 0)
1457 return;
1458 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1459 return;
1460 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1461 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1462 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1463 MCACOD)) !=
1464 (MCI_STATUS_UC|MCI_STATUS_EN|
1465 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1466 MCI_STATUS_AR|MCACOD_INSTR))
1467 return;
1468
1469 m->mcgstatus |= MCG_STATUS_EIPV;
1470 m->ip = regs->ip;
1471 m->cs = regs->cs;
1472 }
1473
1474 /* Add per CPU specific workarounds here */
__mcheck_cpu_apply_quirks(struct cpuinfo_x86 * c)1475 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1476 {
1477 struct mca_config *cfg = &mca_cfg;
1478
1479 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1480 pr_info("unknown CPU type - not enabling MCE support\n");
1481 return -EOPNOTSUPP;
1482 }
1483
1484 /* This should be disabled by the BIOS, but isn't always */
1485 if (c->x86_vendor == X86_VENDOR_AMD) {
1486 if (c->x86 == 15 && cfg->banks > 4) {
1487 /*
1488 * disable GART TBL walk error reporting, which
1489 * trips off incorrectly with the IOMMU & 3ware
1490 * & Cerberus:
1491 */
1492 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1493 }
1494 if (c->x86 <= 17 && cfg->bootlog < 0) {
1495 /*
1496 * Lots of broken BIOS around that don't clear them
1497 * by default and leave crap in there. Don't log:
1498 */
1499 cfg->bootlog = 0;
1500 }
1501 /*
1502 * Various K7s with broken bank 0 around. Always disable
1503 * by default.
1504 */
1505 if (c->x86 == 6 && cfg->banks > 0)
1506 mce_banks[0].ctl = 0;
1507
1508 /*
1509 * overflow_recov is supported for F15h Models 00h-0fh
1510 * even though we don't have a CPUID bit for it.
1511 */
1512 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1513 mce_flags.overflow_recov = 1;
1514
1515 /*
1516 * Turn off MC4_MISC thresholding banks on those models since
1517 * they're not supported there.
1518 */
1519 if (c->x86 == 0x15 &&
1520 (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1521 int i;
1522 u64 hwcr;
1523 bool need_toggle;
1524 u32 msrs[] = {
1525 0x00000413, /* MC4_MISC0 */
1526 0xc0000408, /* MC4_MISC1 */
1527 };
1528
1529 rdmsrl(MSR_K7_HWCR, hwcr);
1530
1531 /* McStatusWrEn has to be set */
1532 need_toggle = !(hwcr & BIT(18));
1533
1534 if (need_toggle)
1535 wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1536
1537 /* Clear CntP bit safely */
1538 for (i = 0; i < ARRAY_SIZE(msrs); i++)
1539 msr_clear_bit(msrs[i], 62);
1540
1541 /* restore old settings */
1542 if (need_toggle)
1543 wrmsrl(MSR_K7_HWCR, hwcr);
1544 }
1545 }
1546
1547 if (c->x86_vendor == X86_VENDOR_INTEL) {
1548 /*
1549 * SDM documents that on family 6 bank 0 should not be written
1550 * because it aliases to another special BIOS controlled
1551 * register.
1552 * But it's not aliased anymore on model 0x1a+
1553 * Don't ignore bank 0 completely because there could be a
1554 * valid event later, merely don't write CTL0.
1555 */
1556
1557 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1558 mce_banks[0].init = 0;
1559
1560 /*
1561 * All newer Intel systems support MCE broadcasting. Enable
1562 * synchronization with a one second timeout.
1563 */
1564 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1565 cfg->monarch_timeout < 0)
1566 cfg->monarch_timeout = USEC_PER_SEC;
1567
1568 /*
1569 * There are also broken BIOSes on some Pentium M and
1570 * earlier systems:
1571 */
1572 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1573 cfg->bootlog = 0;
1574
1575 if (c->x86 == 6 && c->x86_model == 45)
1576 quirk_no_way_out = quirk_sandybridge_ifu;
1577 }
1578 if (cfg->monarch_timeout < 0)
1579 cfg->monarch_timeout = 0;
1580 if (cfg->bootlog != 0)
1581 cfg->panic_timeout = 30;
1582
1583 return 0;
1584 }
1585
__mcheck_cpu_ancient_init(struct cpuinfo_x86 * c)1586 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1587 {
1588 if (c->x86 != 5)
1589 return 0;
1590
1591 switch (c->x86_vendor) {
1592 case X86_VENDOR_INTEL:
1593 intel_p5_mcheck_init(c);
1594 return 1;
1595 break;
1596 case X86_VENDOR_CENTAUR:
1597 winchip_mcheck_init(c);
1598 return 1;
1599 break;
1600 default:
1601 return 0;
1602 }
1603
1604 return 0;
1605 }
1606
__mcheck_cpu_init_vendor(struct cpuinfo_x86 * c)1607 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1608 {
1609 switch (c->x86_vendor) {
1610 case X86_VENDOR_INTEL:
1611 mce_intel_feature_init(c);
1612 mce_adjust_timer = cmci_intel_adjust_timer;
1613 break;
1614
1615 case X86_VENDOR_AMD: {
1616 u32 ebx = cpuid_ebx(0x80000007);
1617
1618 mce_amd_feature_init(c);
1619 mce_flags.overflow_recov = !!(ebx & BIT(0));
1620 mce_flags.succor = !!(ebx & BIT(1));
1621 mce_flags.smca = !!(ebx & BIT(3));
1622
1623 break;
1624 }
1625
1626 default:
1627 break;
1628 }
1629 }
1630
__mcheck_cpu_clear_vendor(struct cpuinfo_x86 * c)1631 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
1632 {
1633 switch (c->x86_vendor) {
1634 case X86_VENDOR_INTEL:
1635 mce_intel_feature_clear(c);
1636 break;
1637 default:
1638 break;
1639 }
1640 }
1641
mce_start_timer(unsigned int cpu,struct timer_list * t)1642 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1643 {
1644 unsigned long iv = check_interval * HZ;
1645
1646 if (mca_cfg.ignore_ce || !iv)
1647 return;
1648
1649 per_cpu(mce_next_interval, cpu) = iv;
1650
1651 t->expires = round_jiffies(jiffies + iv);
1652 add_timer_on(t, cpu);
1653 }
1654
__mcheck_cpu_init_timer(void)1655 static void __mcheck_cpu_init_timer(void)
1656 {
1657 struct timer_list *t = this_cpu_ptr(&mce_timer);
1658 unsigned int cpu = smp_processor_id();
1659
1660 setup_timer(t, mce_timer_fn, cpu);
1661 mce_start_timer(cpu, t);
1662 }
1663
1664 /* Handle unconfigured int18 (should never happen) */
unexpected_machine_check(struct pt_regs * regs,long error_code)1665 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1666 {
1667 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1668 smp_processor_id());
1669 }
1670
1671 /* Call the installed machine check handler for this CPU setup. */
1672 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1673 unexpected_machine_check;
1674
1675 /*
1676 * Called for each booted CPU to set up machine checks.
1677 * Must be called with preempt off:
1678 */
mcheck_cpu_init(struct cpuinfo_x86 * c)1679 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1680 {
1681 if (mca_cfg.disabled)
1682 return;
1683
1684 if (__mcheck_cpu_ancient_init(c))
1685 return;
1686
1687 if (!mce_available(c))
1688 return;
1689
1690 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1691 mca_cfg.disabled = true;
1692 return;
1693 }
1694
1695 if (mce_gen_pool_init()) {
1696 mca_cfg.disabled = true;
1697 pr_emerg("Couldn't allocate MCE records pool!\n");
1698 return;
1699 }
1700
1701 machine_check_vector = do_machine_check;
1702
1703 __mcheck_cpu_init_generic();
1704 __mcheck_cpu_init_vendor(c);
1705 __mcheck_cpu_init_timer();
1706 }
1707
1708 /*
1709 * Called for each booted CPU to clear some machine checks opt-ins
1710 */
mcheck_cpu_clear(struct cpuinfo_x86 * c)1711 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
1712 {
1713 if (mca_cfg.disabled)
1714 return;
1715
1716 if (!mce_available(c))
1717 return;
1718
1719 /*
1720 * Possibly to clear general settings generic to x86
1721 * __mcheck_cpu_clear_generic(c);
1722 */
1723 __mcheck_cpu_clear_vendor(c);
1724
1725 }
1726
1727 /*
1728 * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1729 */
1730
1731 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1732 static int mce_chrdev_open_count; /* #times opened */
1733 static int mce_chrdev_open_exclu; /* already open exclusive? */
1734
mce_chrdev_open(struct inode * inode,struct file * file)1735 static int mce_chrdev_open(struct inode *inode, struct file *file)
1736 {
1737 spin_lock(&mce_chrdev_state_lock);
1738
1739 if (mce_chrdev_open_exclu ||
1740 (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1741 spin_unlock(&mce_chrdev_state_lock);
1742
1743 return -EBUSY;
1744 }
1745
1746 if (file->f_flags & O_EXCL)
1747 mce_chrdev_open_exclu = 1;
1748 mce_chrdev_open_count++;
1749
1750 spin_unlock(&mce_chrdev_state_lock);
1751
1752 return nonseekable_open(inode, file);
1753 }
1754
mce_chrdev_release(struct inode * inode,struct file * file)1755 static int mce_chrdev_release(struct inode *inode, struct file *file)
1756 {
1757 spin_lock(&mce_chrdev_state_lock);
1758
1759 mce_chrdev_open_count--;
1760 mce_chrdev_open_exclu = 0;
1761
1762 spin_unlock(&mce_chrdev_state_lock);
1763
1764 return 0;
1765 }
1766
collect_tscs(void * data)1767 static void collect_tscs(void *data)
1768 {
1769 unsigned long *cpu_tsc = (unsigned long *)data;
1770
1771 cpu_tsc[smp_processor_id()] = rdtsc();
1772 }
1773
1774 static int mce_apei_read_done;
1775
1776 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
__mce_read_apei(char __user ** ubuf,size_t usize)1777 static int __mce_read_apei(char __user **ubuf, size_t usize)
1778 {
1779 int rc;
1780 u64 record_id;
1781 struct mce m;
1782
1783 if (usize < sizeof(struct mce))
1784 return -EINVAL;
1785
1786 rc = apei_read_mce(&m, &record_id);
1787 /* Error or no more MCE record */
1788 if (rc <= 0) {
1789 mce_apei_read_done = 1;
1790 /*
1791 * When ERST is disabled, mce_chrdev_read() should return
1792 * "no record" instead of "no device."
1793 */
1794 if (rc == -ENODEV)
1795 return 0;
1796 return rc;
1797 }
1798 rc = -EFAULT;
1799 if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1800 return rc;
1801 /*
1802 * In fact, we should have cleared the record after that has
1803 * been flushed to the disk or sent to network in
1804 * /sbin/mcelog, but we have no interface to support that now,
1805 * so just clear it to avoid duplication.
1806 */
1807 rc = apei_clear_mce(record_id);
1808 if (rc) {
1809 mce_apei_read_done = 1;
1810 return rc;
1811 }
1812 *ubuf += sizeof(struct mce);
1813
1814 return 0;
1815 }
1816
mce_chrdev_read(struct file * filp,char __user * ubuf,size_t usize,loff_t * off)1817 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1818 size_t usize, loff_t *off)
1819 {
1820 char __user *buf = ubuf;
1821 unsigned long *cpu_tsc;
1822 unsigned prev, next;
1823 int i, err;
1824
1825 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1826 if (!cpu_tsc)
1827 return -ENOMEM;
1828
1829 mutex_lock(&mce_chrdev_read_mutex);
1830
1831 if (!mce_apei_read_done) {
1832 err = __mce_read_apei(&buf, usize);
1833 if (err || buf != ubuf)
1834 goto out;
1835 }
1836
1837 next = mce_log_get_idx_check(mcelog.next);
1838
1839 /* Only supports full reads right now */
1840 err = -EINVAL;
1841 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1842 goto out;
1843
1844 err = 0;
1845 prev = 0;
1846 do {
1847 for (i = prev; i < next; i++) {
1848 unsigned long start = jiffies;
1849 struct mce *m = &mcelog.entry[i];
1850
1851 while (!m->finished) {
1852 if (time_after_eq(jiffies, start + 2)) {
1853 memset(m, 0, sizeof(*m));
1854 goto timeout;
1855 }
1856 cpu_relax();
1857 }
1858 smp_rmb();
1859 err |= copy_to_user(buf, m, sizeof(*m));
1860 buf += sizeof(*m);
1861 timeout:
1862 ;
1863 }
1864
1865 memset(mcelog.entry + prev, 0,
1866 (next - prev) * sizeof(struct mce));
1867 prev = next;
1868 next = cmpxchg(&mcelog.next, prev, 0);
1869 } while (next != prev);
1870
1871 synchronize_sched();
1872
1873 /*
1874 * Collect entries that were still getting written before the
1875 * synchronize.
1876 */
1877 on_each_cpu(collect_tscs, cpu_tsc, 1);
1878
1879 for (i = next; i < MCE_LOG_LEN; i++) {
1880 struct mce *m = &mcelog.entry[i];
1881
1882 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1883 err |= copy_to_user(buf, m, sizeof(*m));
1884 smp_rmb();
1885 buf += sizeof(*m);
1886 memset(m, 0, sizeof(*m));
1887 }
1888 }
1889
1890 if (err)
1891 err = -EFAULT;
1892
1893 out:
1894 mutex_unlock(&mce_chrdev_read_mutex);
1895 kfree(cpu_tsc);
1896
1897 return err ? err : buf - ubuf;
1898 }
1899
mce_chrdev_poll(struct file * file,poll_table * wait)1900 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1901 {
1902 poll_wait(file, &mce_chrdev_wait, wait);
1903 if (READ_ONCE(mcelog.next))
1904 return POLLIN | POLLRDNORM;
1905 if (!mce_apei_read_done && apei_check_mce())
1906 return POLLIN | POLLRDNORM;
1907 return 0;
1908 }
1909
mce_chrdev_ioctl(struct file * f,unsigned int cmd,unsigned long arg)1910 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1911 unsigned long arg)
1912 {
1913 int __user *p = (int __user *)arg;
1914
1915 if (!capable(CAP_SYS_ADMIN))
1916 return -EPERM;
1917
1918 switch (cmd) {
1919 case MCE_GET_RECORD_LEN:
1920 return put_user(sizeof(struct mce), p);
1921 case MCE_GET_LOG_LEN:
1922 return put_user(MCE_LOG_LEN, p);
1923 case MCE_GETCLEAR_FLAGS: {
1924 unsigned flags;
1925
1926 do {
1927 flags = mcelog.flags;
1928 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1929
1930 return put_user(flags, p);
1931 }
1932 default:
1933 return -ENOTTY;
1934 }
1935 }
1936
1937 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1938 size_t usize, loff_t *off);
1939
register_mce_write_callback(ssize_t (* fn)(struct file * filp,const char __user * ubuf,size_t usize,loff_t * off))1940 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1941 const char __user *ubuf,
1942 size_t usize, loff_t *off))
1943 {
1944 mce_write = fn;
1945 }
1946 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1947
mce_chrdev_write(struct file * filp,const char __user * ubuf,size_t usize,loff_t * off)1948 static ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1949 size_t usize, loff_t *off)
1950 {
1951 if (mce_write)
1952 return mce_write(filp, ubuf, usize, off);
1953 else
1954 return -EINVAL;
1955 }
1956
1957 static const struct file_operations mce_chrdev_ops = {
1958 .open = mce_chrdev_open,
1959 .release = mce_chrdev_release,
1960 .read = mce_chrdev_read,
1961 .write = mce_chrdev_write,
1962 .poll = mce_chrdev_poll,
1963 .unlocked_ioctl = mce_chrdev_ioctl,
1964 .llseek = no_llseek,
1965 };
1966
1967 static struct miscdevice mce_chrdev_device = {
1968 MISC_MCELOG_MINOR,
1969 "mcelog",
1970 &mce_chrdev_ops,
1971 };
1972
__mce_disable_bank(void * arg)1973 static void __mce_disable_bank(void *arg)
1974 {
1975 int bank = *((int *)arg);
1976 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1977 cmci_disable_bank(bank);
1978 }
1979
mce_disable_bank(int bank)1980 void mce_disable_bank(int bank)
1981 {
1982 if (bank >= mca_cfg.banks) {
1983 pr_warn(FW_BUG
1984 "Ignoring request to disable invalid MCA bank %d.\n",
1985 bank);
1986 return;
1987 }
1988 set_bit(bank, mce_banks_ce_disabled);
1989 on_each_cpu(__mce_disable_bank, &bank, 1);
1990 }
1991
1992 /*
1993 * mce=off Disables machine check
1994 * mce=no_cmci Disables CMCI
1995 * mce=no_lmce Disables LMCE
1996 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1997 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1998 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1999 * monarchtimeout is how long to wait for other CPUs on machine
2000 * check, or 0 to not wait
2001 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
2002 * mce=nobootlog Don't log MCEs from before booting.
2003 * mce=bios_cmci_threshold Don't program the CMCI threshold
2004 */
mcheck_enable(char * str)2005 static int __init mcheck_enable(char *str)
2006 {
2007 struct mca_config *cfg = &mca_cfg;
2008
2009 if (*str == 0) {
2010 enable_p5_mce();
2011 return 1;
2012 }
2013 if (*str == '=')
2014 str++;
2015 if (!strcmp(str, "off"))
2016 cfg->disabled = true;
2017 else if (!strcmp(str, "no_cmci"))
2018 cfg->cmci_disabled = true;
2019 else if (!strcmp(str, "no_lmce"))
2020 cfg->lmce_disabled = true;
2021 else if (!strcmp(str, "dont_log_ce"))
2022 cfg->dont_log_ce = true;
2023 else if (!strcmp(str, "ignore_ce"))
2024 cfg->ignore_ce = true;
2025 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2026 cfg->bootlog = (str[0] == 'b');
2027 else if (!strcmp(str, "bios_cmci_threshold"))
2028 cfg->bios_cmci_threshold = true;
2029 else if (isdigit(str[0])) {
2030 if (get_option(&str, &cfg->tolerant) == 2)
2031 get_option(&str, &(cfg->monarch_timeout));
2032 } else {
2033 pr_info("mce argument %s ignored. Please use /sys\n", str);
2034 return 0;
2035 }
2036 return 1;
2037 }
2038 __setup("mce", mcheck_enable);
2039
mcheck_init(void)2040 int __init mcheck_init(void)
2041 {
2042 mcheck_intel_therm_init();
2043 mce_register_decode_chain(&mce_srao_nb);
2044 mcheck_vendor_init_severity();
2045
2046 INIT_WORK(&mce_work, mce_process_work);
2047 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2048
2049 return 0;
2050 }
2051
2052 /*
2053 * mce_syscore: PM support
2054 */
2055
2056 /*
2057 * Disable machine checks on suspend and shutdown. We can't really handle
2058 * them later.
2059 */
mce_disable_error_reporting(void)2060 static void mce_disable_error_reporting(void)
2061 {
2062 int i;
2063
2064 for (i = 0; i < mca_cfg.banks; i++) {
2065 struct mce_bank *b = &mce_banks[i];
2066
2067 if (b->init)
2068 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2069 }
2070 return;
2071 }
2072
vendor_disable_error_reporting(void)2073 static void vendor_disable_error_reporting(void)
2074 {
2075 /*
2076 * Don't clear on Intel CPUs. Some of these MSRs are socket-wide.
2077 * Disabling them for just a single offlined CPU is bad, since it will
2078 * inhibit reporting for all shared resources on the socket like the
2079 * last level cache (LLC), the integrated memory controller (iMC), etc.
2080 */
2081 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2082 return;
2083
2084 mce_disable_error_reporting();
2085 }
2086
mce_syscore_suspend(void)2087 static int mce_syscore_suspend(void)
2088 {
2089 vendor_disable_error_reporting();
2090 return 0;
2091 }
2092
mce_syscore_shutdown(void)2093 static void mce_syscore_shutdown(void)
2094 {
2095 vendor_disable_error_reporting();
2096 }
2097
2098 /*
2099 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2100 * Only one CPU is active at this time, the others get re-added later using
2101 * CPU hotplug:
2102 */
mce_syscore_resume(void)2103 static void mce_syscore_resume(void)
2104 {
2105 __mcheck_cpu_init_generic();
2106 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2107 }
2108
2109 static struct syscore_ops mce_syscore_ops = {
2110 .suspend = mce_syscore_suspend,
2111 .shutdown = mce_syscore_shutdown,
2112 .resume = mce_syscore_resume,
2113 };
2114
2115 /*
2116 * mce_device: Sysfs support
2117 */
2118
mce_cpu_restart(void * data)2119 static void mce_cpu_restart(void *data)
2120 {
2121 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2122 return;
2123 __mcheck_cpu_init_generic();
2124 __mcheck_cpu_init_timer();
2125 }
2126
2127 /* Reinit MCEs after user configuration changes */
mce_restart(void)2128 static void mce_restart(void)
2129 {
2130 mce_timer_delete_all();
2131 on_each_cpu(mce_cpu_restart, NULL, 1);
2132 }
2133
2134 /* Toggle features for corrected errors */
mce_disable_cmci(void * data)2135 static void mce_disable_cmci(void *data)
2136 {
2137 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2138 return;
2139 cmci_clear();
2140 }
2141
mce_enable_ce(void * all)2142 static void mce_enable_ce(void *all)
2143 {
2144 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2145 return;
2146 cmci_reenable();
2147 cmci_recheck();
2148 if (all)
2149 __mcheck_cpu_init_timer();
2150 }
2151
2152 static struct bus_type mce_subsys = {
2153 .name = "machinecheck",
2154 .dev_name = "machinecheck",
2155 };
2156
2157 DEFINE_PER_CPU(struct device *, mce_device);
2158
2159 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2160
attr_to_bank(struct device_attribute * attr)2161 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2162 {
2163 return container_of(attr, struct mce_bank, attr);
2164 }
2165
show_bank(struct device * s,struct device_attribute * attr,char * buf)2166 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2167 char *buf)
2168 {
2169 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2170 }
2171
set_bank(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2172 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2173 const char *buf, size_t size)
2174 {
2175 u64 new;
2176
2177 if (kstrtou64(buf, 0, &new) < 0)
2178 return -EINVAL;
2179
2180 attr_to_bank(attr)->ctl = new;
2181 mce_restart();
2182
2183 return size;
2184 }
2185
2186 static ssize_t
show_trigger(struct device * s,struct device_attribute * attr,char * buf)2187 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2188 {
2189 strcpy(buf, mce_helper);
2190 strcat(buf, "\n");
2191 return strlen(mce_helper) + 1;
2192 }
2193
set_trigger(struct device * s,struct device_attribute * attr,const char * buf,size_t siz)2194 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2195 const char *buf, size_t siz)
2196 {
2197 char *p;
2198
2199 strncpy(mce_helper, buf, sizeof(mce_helper));
2200 mce_helper[sizeof(mce_helper)-1] = 0;
2201 p = strchr(mce_helper, '\n');
2202
2203 if (p)
2204 *p = 0;
2205
2206 return strlen(mce_helper) + !!p;
2207 }
2208
set_ignore_ce(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2209 static ssize_t set_ignore_ce(struct device *s,
2210 struct device_attribute *attr,
2211 const char *buf, size_t size)
2212 {
2213 u64 new;
2214
2215 if (kstrtou64(buf, 0, &new) < 0)
2216 return -EINVAL;
2217
2218 if (mca_cfg.ignore_ce ^ !!new) {
2219 if (new) {
2220 /* disable ce features */
2221 mce_timer_delete_all();
2222 on_each_cpu(mce_disable_cmci, NULL, 1);
2223 mca_cfg.ignore_ce = true;
2224 } else {
2225 /* enable ce features */
2226 mca_cfg.ignore_ce = false;
2227 on_each_cpu(mce_enable_ce, (void *)1, 1);
2228 }
2229 }
2230 return size;
2231 }
2232
set_cmci_disabled(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2233 static ssize_t set_cmci_disabled(struct device *s,
2234 struct device_attribute *attr,
2235 const char *buf, size_t size)
2236 {
2237 u64 new;
2238
2239 if (kstrtou64(buf, 0, &new) < 0)
2240 return -EINVAL;
2241
2242 if (mca_cfg.cmci_disabled ^ !!new) {
2243 if (new) {
2244 /* disable cmci */
2245 on_each_cpu(mce_disable_cmci, NULL, 1);
2246 mca_cfg.cmci_disabled = true;
2247 } else {
2248 /* enable cmci */
2249 mca_cfg.cmci_disabled = false;
2250 on_each_cpu(mce_enable_ce, NULL, 1);
2251 }
2252 }
2253 return size;
2254 }
2255
store_int_with_restart(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2256 static ssize_t store_int_with_restart(struct device *s,
2257 struct device_attribute *attr,
2258 const char *buf, size_t size)
2259 {
2260 ssize_t ret = device_store_int(s, attr, buf, size);
2261 mce_restart();
2262 return ret;
2263 }
2264
2265 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2266 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2267 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2268 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2269
2270 static struct dev_ext_attribute dev_attr_check_interval = {
2271 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2272 &check_interval
2273 };
2274
2275 static struct dev_ext_attribute dev_attr_ignore_ce = {
2276 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2277 &mca_cfg.ignore_ce
2278 };
2279
2280 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2281 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2282 &mca_cfg.cmci_disabled
2283 };
2284
2285 static struct device_attribute *mce_device_attrs[] = {
2286 &dev_attr_tolerant.attr,
2287 &dev_attr_check_interval.attr,
2288 &dev_attr_trigger,
2289 &dev_attr_monarch_timeout.attr,
2290 &dev_attr_dont_log_ce.attr,
2291 &dev_attr_ignore_ce.attr,
2292 &dev_attr_cmci_disabled.attr,
2293 NULL
2294 };
2295
2296 static cpumask_var_t mce_device_initialized;
2297
mce_device_release(struct device * dev)2298 static void mce_device_release(struct device *dev)
2299 {
2300 kfree(dev);
2301 }
2302
2303 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
mce_device_create(unsigned int cpu)2304 static int mce_device_create(unsigned int cpu)
2305 {
2306 struct device *dev;
2307 int err;
2308 int i, j;
2309
2310 if (!mce_available(&boot_cpu_data))
2311 return -EIO;
2312
2313 dev = kzalloc(sizeof *dev, GFP_KERNEL);
2314 if (!dev)
2315 return -ENOMEM;
2316 dev->id = cpu;
2317 dev->bus = &mce_subsys;
2318 dev->release = &mce_device_release;
2319
2320 err = device_register(dev);
2321 if (err) {
2322 put_device(dev);
2323 return err;
2324 }
2325
2326 for (i = 0; mce_device_attrs[i]; i++) {
2327 err = device_create_file(dev, mce_device_attrs[i]);
2328 if (err)
2329 goto error;
2330 }
2331 for (j = 0; j < mca_cfg.banks; j++) {
2332 err = device_create_file(dev, &mce_banks[j].attr);
2333 if (err)
2334 goto error2;
2335 }
2336 cpumask_set_cpu(cpu, mce_device_initialized);
2337 per_cpu(mce_device, cpu) = dev;
2338
2339 return 0;
2340 error2:
2341 while (--j >= 0)
2342 device_remove_file(dev, &mce_banks[j].attr);
2343 error:
2344 while (--i >= 0)
2345 device_remove_file(dev, mce_device_attrs[i]);
2346
2347 device_unregister(dev);
2348
2349 return err;
2350 }
2351
mce_device_remove(unsigned int cpu)2352 static void mce_device_remove(unsigned int cpu)
2353 {
2354 struct device *dev = per_cpu(mce_device, cpu);
2355 int i;
2356
2357 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2358 return;
2359
2360 for (i = 0; mce_device_attrs[i]; i++)
2361 device_remove_file(dev, mce_device_attrs[i]);
2362
2363 for (i = 0; i < mca_cfg.banks; i++)
2364 device_remove_file(dev, &mce_banks[i].attr);
2365
2366 device_unregister(dev);
2367 cpumask_clear_cpu(cpu, mce_device_initialized);
2368 per_cpu(mce_device, cpu) = NULL;
2369 }
2370
2371 /* Make sure there are no machine checks on offlined CPUs. */
mce_disable_cpu(void * h)2372 static void mce_disable_cpu(void *h)
2373 {
2374 unsigned long action = *(unsigned long *)h;
2375
2376 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2377 return;
2378
2379 if (!(action & CPU_TASKS_FROZEN))
2380 cmci_clear();
2381
2382 vendor_disable_error_reporting();
2383 }
2384
mce_reenable_cpu(void * h)2385 static void mce_reenable_cpu(void *h)
2386 {
2387 unsigned long action = *(unsigned long *)h;
2388 int i;
2389
2390 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2391 return;
2392
2393 if (!(action & CPU_TASKS_FROZEN))
2394 cmci_reenable();
2395 for (i = 0; i < mca_cfg.banks; i++) {
2396 struct mce_bank *b = &mce_banks[i];
2397
2398 if (b->init)
2399 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2400 }
2401 }
2402
2403 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2404 static int
mce_cpu_callback(struct notifier_block * nfb,unsigned long action,void * hcpu)2405 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2406 {
2407 unsigned int cpu = (unsigned long)hcpu;
2408 struct timer_list *t = &per_cpu(mce_timer, cpu);
2409
2410 switch (action & ~CPU_TASKS_FROZEN) {
2411 case CPU_ONLINE:
2412 mce_device_create(cpu);
2413 if (threshold_cpu_callback)
2414 threshold_cpu_callback(action, cpu);
2415 break;
2416 case CPU_DEAD:
2417 if (threshold_cpu_callback)
2418 threshold_cpu_callback(action, cpu);
2419 mce_device_remove(cpu);
2420 mce_intel_hcpu_update(cpu);
2421
2422 /* intentionally ignoring frozen here */
2423 if (!(action & CPU_TASKS_FROZEN))
2424 cmci_rediscover();
2425 break;
2426 case CPU_DOWN_PREPARE:
2427 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2428 del_timer_sync(t);
2429 break;
2430 case CPU_DOWN_FAILED:
2431 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2432 mce_start_timer(cpu, t);
2433 break;
2434 }
2435
2436 return NOTIFY_OK;
2437 }
2438
2439 static struct notifier_block mce_cpu_notifier = {
2440 .notifier_call = mce_cpu_callback,
2441 };
2442
mce_init_banks(void)2443 static __init void mce_init_banks(void)
2444 {
2445 int i;
2446
2447 for (i = 0; i < mca_cfg.banks; i++) {
2448 struct mce_bank *b = &mce_banks[i];
2449 struct device_attribute *a = &b->attr;
2450
2451 sysfs_attr_init(&a->attr);
2452 a->attr.name = b->attrname;
2453 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2454
2455 a->attr.mode = 0644;
2456 a->show = show_bank;
2457 a->store = set_bank;
2458 }
2459 }
2460
mcheck_init_device(void)2461 static __init int mcheck_init_device(void)
2462 {
2463 int err;
2464 int i = 0;
2465
2466 if (!mce_available(&boot_cpu_data)) {
2467 err = -EIO;
2468 goto err_out;
2469 }
2470
2471 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2472 err = -ENOMEM;
2473 goto err_out;
2474 }
2475
2476 mce_init_banks();
2477
2478 err = subsys_system_register(&mce_subsys, NULL);
2479 if (err)
2480 goto err_out_mem;
2481
2482 cpu_notifier_register_begin();
2483 for_each_online_cpu(i) {
2484 err = mce_device_create(i);
2485 if (err) {
2486 /*
2487 * Register notifier anyway (and do not unreg it) so
2488 * that we don't leave undeleted timers, see notifier
2489 * callback above.
2490 */
2491 __register_hotcpu_notifier(&mce_cpu_notifier);
2492 cpu_notifier_register_done();
2493 goto err_device_create;
2494 }
2495 }
2496
2497 __register_hotcpu_notifier(&mce_cpu_notifier);
2498 cpu_notifier_register_done();
2499
2500 register_syscore_ops(&mce_syscore_ops);
2501
2502 /* register character device /dev/mcelog */
2503 err = misc_register(&mce_chrdev_device);
2504 if (err)
2505 goto err_register;
2506
2507 return 0;
2508
2509 err_register:
2510 unregister_syscore_ops(&mce_syscore_ops);
2511
2512 err_device_create:
2513 /*
2514 * We didn't keep track of which devices were created above, but
2515 * even if we had, the set of online cpus might have changed.
2516 * Play safe and remove for every possible cpu, since
2517 * mce_device_remove() will do the right thing.
2518 */
2519 for_each_possible_cpu(i)
2520 mce_device_remove(i);
2521
2522 err_out_mem:
2523 free_cpumask_var(mce_device_initialized);
2524
2525 err_out:
2526 pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2527
2528 return err;
2529 }
2530 device_initcall_sync(mcheck_init_device);
2531
2532 /*
2533 * Old style boot options parsing. Only for compatibility.
2534 */
mcheck_disable(char * str)2535 static int __init mcheck_disable(char *str)
2536 {
2537 mca_cfg.disabled = true;
2538 return 1;
2539 }
2540 __setup("nomce", mcheck_disable);
2541
2542 #ifdef CONFIG_DEBUG_FS
mce_get_debugfs_dir(void)2543 struct dentry *mce_get_debugfs_dir(void)
2544 {
2545 static struct dentry *dmce;
2546
2547 if (!dmce)
2548 dmce = debugfs_create_dir("mce", NULL);
2549
2550 return dmce;
2551 }
2552
mce_reset(void)2553 static void mce_reset(void)
2554 {
2555 cpu_missing = 0;
2556 atomic_set(&mce_fake_panicked, 0);
2557 atomic_set(&mce_executing, 0);
2558 atomic_set(&mce_callin, 0);
2559 atomic_set(&global_nwo, 0);
2560 }
2561
fake_panic_get(void * data,u64 * val)2562 static int fake_panic_get(void *data, u64 *val)
2563 {
2564 *val = fake_panic;
2565 return 0;
2566 }
2567
fake_panic_set(void * data,u64 val)2568 static int fake_panic_set(void *data, u64 val)
2569 {
2570 mce_reset();
2571 fake_panic = val;
2572 return 0;
2573 }
2574
2575 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2576 fake_panic_set, "%llu\n");
2577
mcheck_debugfs_init(void)2578 static int __init mcheck_debugfs_init(void)
2579 {
2580 struct dentry *dmce, *ffake_panic;
2581
2582 dmce = mce_get_debugfs_dir();
2583 if (!dmce)
2584 return -ENOMEM;
2585 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2586 &fake_panic_fops);
2587 if (!ffake_panic)
2588 return -ENOMEM;
2589
2590 return 0;
2591 }
2592 #else
mcheck_debugfs_init(void)2593 static int __init mcheck_debugfs_init(void) { return -EINVAL; }
2594 #endif
2595
mcheck_late_init(void)2596 static int __init mcheck_late_init(void)
2597 {
2598 mcheck_debugfs_init();
2599
2600 /*
2601 * Flush out everything that has been logged during early boot, now that
2602 * everything has been initialized (workqueues, decoders, ...).
2603 */
2604 mce_schedule_work();
2605
2606 return 0;
2607 }
2608 late_initcall(mcheck_late_init);
2609