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