1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Machine check handler.
4 *
5 * K8 parts Copyright 2002,2003 Andi Kleen, SuSE Labs.
6 * Rest from unknown author(s).
7 * 2004 Andi Kleen. Rewrote most of it.
8 * Copyright 2008 Intel Corporation
9 * Author: Andi Kleen
10 */
11
12 #include <linux/thread_info.h>
13 #include <linux/capability.h>
14 #include <linux/miscdevice.h>
15 #include <linux/ratelimit.h>
16 #include <linux/rcupdate.h>
17 #include <linux/kobject.h>
18 #include <linux/uaccess.h>
19 #include <linux/kdebug.h>
20 #include <linux/kernel.h>
21 #include <linux/percpu.h>
22 #include <linux/string.h>
23 #include <linux/device.h>
24 #include <linux/syscore_ops.h>
25 #include <linux/delay.h>
26 #include <linux/ctype.h>
27 #include <linux/sched.h>
28 #include <linux/sysfs.h>
29 #include <linux/types.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/kmod.h>
33 #include <linux/poll.h>
34 #include <linux/nmi.h>
35 #include <linux/cpu.h>
36 #include <linux/ras.h>
37 #include <linux/smp.h>
38 #include <linux/fs.h>
39 #include <linux/mm.h>
40 #include <linux/debugfs.h>
41 #include <linux/irq_work.h>
42 #include <linux/export.h>
43 #include <linux/set_memory.h>
44 #include <linux/sync_core.h>
45 #include <linux/task_work.h>
46 #include <linux/hardirq.h>
47 #include <linux/kexec.h>
48 #include <linux/vmcore_info.h>
49
50 #include <asm/fred.h>
51 #include <asm/cpu_device_id.h>
52 #include <asm/processor.h>
53 #include <asm/traps.h>
54 #include <asm/tlbflush.h>
55 #include <asm/mce.h>
56 #include <asm/msr.h>
57 #include <asm/reboot.h>
58 #include <asm/tdx.h>
59
60 #include "internal.h"
61
62 /* sysfs synchronization */
63 static DEFINE_MUTEX(mce_sysfs_mutex);
64
65 #define CREATE_TRACE_POINTS
66 #include <trace/events/mce.h>
67
68 #define SPINUNIT 100 /* 100ns */
69
70 DEFINE_PER_CPU(unsigned, mce_exception_count);
71
72 DEFINE_PER_CPU_READ_MOSTLY(unsigned int, mce_num_banks);
73
74 DEFINE_PER_CPU_READ_MOSTLY(struct mce_bank[MAX_NR_BANKS], mce_banks_array);
75
76 #define ATTR_LEN 16
77 /* One object for each MCE bank, shared by all CPUs */
78 struct mce_bank_dev {
79 struct device_attribute attr; /* device attribute */
80 char attrname[ATTR_LEN]; /* attribute name */
81 u8 bank; /* bank number */
82 };
83 static struct mce_bank_dev mce_bank_devs[MAX_NR_BANKS];
84
85 struct mce_vendor_flags mce_flags __read_mostly;
86
87 struct mca_config mca_cfg __read_mostly = {
88 .bootlog = -1,
89 .monarch_timeout = -1
90 };
91
92 static DEFINE_PER_CPU(struct mce_hw_err, hw_errs_seen);
93
94 /*
95 * MCA banks polled by the period polling timer for corrected events.
96 * With Intel CMCI, this only has MCA banks which do not support CMCI (if any).
97 */
98 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
99 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
100 };
101
102 /*
103 * MCA banks controlled through firmware first for corrected errors.
104 * This is a global list of banks for which we won't enable CMCI and we
105 * won't poll. Firmware controls these banks and is responsible for
106 * reporting corrected errors through GHES. Uncorrected/recoverable
107 * errors are still notified through a machine check.
108 */
109 mce_banks_t mce_banks_ce_disabled;
110
111 static struct work_struct mce_work;
112 static struct irq_work mce_irq_work;
113
114 /*
115 * CPU/chipset specific EDAC code can register a notifier call here to print
116 * MCE errors in a human-readable form.
117 */
118 BLOCKING_NOTIFIER_HEAD(x86_mce_decoder_chain);
119
mce_prep_record_common(struct mce * m)120 void mce_prep_record_common(struct mce *m)
121 {
122 m->cpuid = cpuid_eax(1);
123 m->cpuvendor = boot_cpu_data.x86_vendor;
124 m->mcgcap = native_rdmsrq(MSR_IA32_MCG_CAP);
125 /* need the internal __ version to avoid deadlocks */
126 m->time = __ktime_get_real_seconds();
127 }
128
mce_prep_record_per_cpu(unsigned int cpu,struct mce * m)129 void mce_prep_record_per_cpu(unsigned int cpu, struct mce *m)
130 {
131 m->cpu = cpu;
132 m->extcpu = cpu;
133 m->apicid = cpu_data(cpu).topo.initial_apicid;
134 m->microcode = cpu_data(cpu).microcode;
135 m->ppin = topology_ppin(cpu);
136 m->socketid = topology_physical_package_id(cpu);
137 }
138
139 /* Do initial initialization of struct mce_hw_err */
mce_prep_record(struct mce_hw_err * err)140 void mce_prep_record(struct mce_hw_err *err)
141 {
142 struct mce *m = &err->m;
143
144 memset(err, 0, sizeof(struct mce_hw_err));
145 mce_prep_record_common(m);
146 mce_prep_record_per_cpu(smp_processor_id(), m);
147 }
148
149 DEFINE_PER_CPU(struct mce, injectm);
150 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
151
mce_log(struct mce_hw_err * err)152 void mce_log(struct mce_hw_err *err)
153 {
154 if (mce_gen_pool_add(err)) {
155 pr_info(HW_ERR "Machine check events logged\n");
156 irq_work_queue(&mce_irq_work);
157 }
158 }
159 EXPORT_SYMBOL_GPL(mce_log);
160
mce_register_decode_chain(struct notifier_block * nb)161 void mce_register_decode_chain(struct notifier_block *nb)
162 {
163 if (WARN_ON(nb->priority < MCE_PRIO_LOWEST ||
164 nb->priority > MCE_PRIO_HIGHEST))
165 return;
166
167 blocking_notifier_chain_register(&x86_mce_decoder_chain, nb);
168 }
169 EXPORT_SYMBOL_GPL(mce_register_decode_chain);
170
mce_unregister_decode_chain(struct notifier_block * nb)171 void mce_unregister_decode_chain(struct notifier_block *nb)
172 {
173 blocking_notifier_chain_unregister(&x86_mce_decoder_chain, nb);
174 }
175 EXPORT_SYMBOL_GPL(mce_unregister_decode_chain);
176
__print_mce(struct mce_hw_err * err)177 static void __print_mce(struct mce_hw_err *err)
178 {
179 struct mce *m = &err->m;
180
181 pr_emerg(HW_ERR "CPU %d: Machine Check%s: %Lx Bank %d: %016Lx\n",
182 m->extcpu,
183 (m->mcgstatus & MCG_STATUS_MCIP ? " Exception" : ""),
184 m->mcgstatus, m->bank, m->status);
185
186 if (m->ip) {
187 pr_emerg(HW_ERR "RIP%s %02x:<%016Lx> ",
188 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
189 m->cs, m->ip);
190
191 if (m->cs == __KERNEL_CS)
192 pr_cont("{%pS}", (void *)(unsigned long)m->ip);
193 pr_cont("\n");
194 }
195
196 pr_emerg(HW_ERR "TSC %llx ", m->tsc);
197 if (m->addr)
198 pr_cont("ADDR %llx ", m->addr);
199 if (m->misc)
200 pr_cont("MISC %llx ", m->misc);
201 if (m->ppin)
202 pr_cont("PPIN %llx ", m->ppin);
203
204 if (mce_flags.smca) {
205 if (m->synd)
206 pr_cont("SYND %llx ", m->synd);
207 if (err->vendor.amd.synd1)
208 pr_cont("SYND1 %llx ", err->vendor.amd.synd1);
209 if (err->vendor.amd.synd2)
210 pr_cont("SYND2 %llx ", err->vendor.amd.synd2);
211 if (m->ipid)
212 pr_cont("IPID %llx ", m->ipid);
213 }
214
215 pr_cont("\n");
216
217 /*
218 * Note this output is parsed by external tools and old fields
219 * should not be changed.
220 */
221 pr_emerg(HW_ERR "PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x microcode %x\n",
222 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid,
223 m->microcode);
224 }
225
print_mce(struct mce_hw_err * err)226 static void print_mce(struct mce_hw_err *err)
227 {
228 struct mce *m = &err->m;
229
230 __print_mce(err);
231
232 if (m->cpuvendor != X86_VENDOR_AMD && m->cpuvendor != X86_VENDOR_HYGON)
233 pr_emerg_ratelimited(HW_ERR "Run the above through 'mcelog --ascii'\n");
234 }
235
236 #define PANIC_TIMEOUT 5 /* 5 seconds */
237
238 static atomic_t mce_panicked;
239
240 static int fake_panic;
241 static atomic_t mce_fake_panicked;
242
243 /* Panic in progress. Enable interrupts and wait for final IPI */
wait_for_panic(void)244 static void wait_for_panic(void)
245 {
246 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
247
248 preempt_disable();
249 local_irq_enable();
250 while (timeout-- > 0)
251 udelay(1);
252 if (panic_timeout == 0)
253 panic_timeout = mca_cfg.panic_timeout;
254 panic("Panicing machine check CPU died");
255 }
256
mce_dump_aux_info(struct mce * m)257 static const char *mce_dump_aux_info(struct mce *m)
258 {
259 if (boot_cpu_has_bug(X86_BUG_TDX_PW_MCE))
260 return tdx_dump_mce_info(m);
261
262 return NULL;
263 }
264
mce_panic(const char * msg,struct mce_hw_err * final,char * exp)265 static noinstr void mce_panic(const char *msg, struct mce_hw_err *final, char *exp)
266 {
267 struct llist_node *pending;
268 struct mce_evt_llist *l;
269 int apei_err = 0;
270 const char *memmsg;
271
272 /*
273 * Allow instrumentation around external facilities usage. Not that it
274 * matters a whole lot since the machine is going to panic anyway.
275 */
276 instrumentation_begin();
277
278 if (!fake_panic) {
279 /*
280 * Make sure only one CPU runs in machine check panic
281 */
282 if (atomic_inc_return(&mce_panicked) > 1)
283 wait_for_panic();
284 barrier();
285
286 bust_spinlocks(1);
287 console_verbose();
288 } else {
289 /* Don't log too much for fake panic */
290 if (atomic_inc_return(&mce_fake_panicked) > 1)
291 goto out;
292 }
293 pending = mce_gen_pool_prepare_records();
294 /* First print corrected ones that are still unlogged */
295 llist_for_each_entry(l, pending, llnode) {
296 struct mce_hw_err *err = &l->err;
297 struct mce *m = &err->m;
298 if (!(m->status & MCI_STATUS_UC)) {
299 print_mce(err);
300 if (!apei_err)
301 apei_err = apei_write_mce(m);
302 }
303 }
304 /* Now print uncorrected but with the final one last */
305 llist_for_each_entry(l, pending, llnode) {
306 struct mce_hw_err *err = &l->err;
307 struct mce *m = &err->m;
308 if (!(m->status & MCI_STATUS_UC))
309 continue;
310 if (!final || mce_cmp(m, &final->m)) {
311 print_mce(err);
312 if (!apei_err)
313 apei_err = apei_write_mce(m);
314 }
315 }
316 if (final) {
317 print_mce(final);
318 if (!apei_err)
319 apei_err = apei_write_mce(&final->m);
320 }
321 if (exp)
322 pr_emerg(HW_ERR "Machine check: %s\n", exp);
323
324 memmsg = mce_dump_aux_info(&final->m);
325 if (memmsg)
326 pr_emerg(HW_ERR "Machine check: %s\n", memmsg);
327
328 if (!fake_panic) {
329 if (panic_timeout == 0)
330 panic_timeout = mca_cfg.panic_timeout;
331
332 /*
333 * Kdump skips the poisoned page in order to avoid
334 * touching the error bits again. Poison the page even
335 * if the error is fatal and the machine is about to
336 * panic.
337 */
338 if (kexec_crash_loaded()) {
339 if (final && (final->m.status & MCI_STATUS_ADDRV)) {
340 struct page *p;
341 p = pfn_to_online_page(final->m.addr >> PAGE_SHIFT);
342 if (p)
343 SetPageHWPoison(p);
344 }
345 }
346 panic(msg);
347 } else
348 pr_emerg(HW_ERR "Fake kernel panic: %s\n", msg);
349
350 out:
351 instrumentation_end();
352 }
353
354 /* Support code for software error injection */
355
msr_to_offset(u32 msr)356 static int msr_to_offset(u32 msr)
357 {
358 unsigned bank = __this_cpu_read(injectm.bank);
359
360 if (msr == mca_cfg.rip_msr)
361 return offsetof(struct mce, ip);
362 if (msr == mca_msr_reg(bank, MCA_STATUS))
363 return offsetof(struct mce, status);
364 if (msr == mca_msr_reg(bank, MCA_ADDR))
365 return offsetof(struct mce, addr);
366 if (msr == mca_msr_reg(bank, MCA_MISC))
367 return offsetof(struct mce, misc);
368 if (msr == MSR_IA32_MCG_STATUS)
369 return offsetof(struct mce, mcgstatus);
370 return -1;
371 }
372
ex_handler_msr_mce(struct pt_regs * regs,bool wrmsr)373 void ex_handler_msr_mce(struct pt_regs *regs, bool wrmsr)
374 {
375 if (wrmsr) {
376 pr_emerg("MSR access error: WRMSR to 0x%x (tried to write 0x%08x%08x) at rIP: 0x%lx (%pS)\n",
377 (unsigned int)regs->cx, (unsigned int)regs->dx, (unsigned int)regs->ax,
378 regs->ip, (void *)regs->ip);
379 } else {
380 pr_emerg("MSR access error: RDMSR from 0x%x at rIP: 0x%lx (%pS)\n",
381 (unsigned int)regs->cx, regs->ip, (void *)regs->ip);
382 }
383
384 show_stack_regs(regs);
385
386 panic("MCA architectural violation!\n");
387
388 while (true)
389 cpu_relax();
390 }
391
392 /* MSR access wrappers used for error injection */
mce_rdmsrq(u32 msr)393 noinstr u64 mce_rdmsrq(u32 msr)
394 {
395 EAX_EDX_DECLARE_ARGS(val, low, high);
396
397 if (__this_cpu_read(injectm.finished)) {
398 int offset;
399 u64 ret;
400
401 instrumentation_begin();
402
403 offset = msr_to_offset(msr);
404 if (offset < 0)
405 ret = 0;
406 else
407 ret = *(u64 *)((char *)this_cpu_ptr(&injectm) + offset);
408
409 instrumentation_end();
410
411 return ret;
412 }
413
414 /*
415 * RDMSR on MCA MSRs should not fault. If they do, this is very much an
416 * architectural violation and needs to be reported to hw vendor. Panic
417 * the box to not allow any further progress.
418 */
419 asm volatile("1: rdmsr\n"
420 "2:\n"
421 _ASM_EXTABLE_TYPE(1b, 2b, EX_TYPE_RDMSR_IN_MCE)
422 : EAX_EDX_RET(val, low, high) : "c" (msr));
423
424
425 return EAX_EDX_VAL(val, low, high);
426 }
427
mce_wrmsrq(u32 msr,u64 v)428 noinstr void mce_wrmsrq(u32 msr, u64 v)
429 {
430 u32 low, high;
431
432 if (__this_cpu_read(injectm.finished)) {
433 int offset;
434
435 instrumentation_begin();
436
437 offset = msr_to_offset(msr);
438 if (offset >= 0)
439 *(u64 *)((char *)this_cpu_ptr(&injectm) + offset) = v;
440
441 instrumentation_end();
442
443 return;
444 }
445
446 low = (u32)v;
447 high = (u32)(v >> 32);
448
449 /* See comment in mce_rdmsrq() */
450 asm volatile("1: wrmsr\n"
451 "2:\n"
452 _ASM_EXTABLE_TYPE(1b, 2b, EX_TYPE_WRMSR_IN_MCE)
453 : : "c" (msr), "a"(low), "d" (high) : "memory");
454 }
455
456 /*
457 * Collect all global (w.r.t. this processor) status about this machine
458 * check into our "mce" struct so that we can use it later to assess
459 * the severity of the problem as we read per-bank specific details.
460 */
mce_gather_info(struct mce_hw_err * err,struct pt_regs * regs)461 static noinstr void mce_gather_info(struct mce_hw_err *err, struct pt_regs *regs)
462 {
463 struct mce *m;
464 /*
465 * Enable instrumentation around mce_prep_record() which calls external
466 * facilities.
467 */
468 instrumentation_begin();
469 mce_prep_record(err);
470 instrumentation_end();
471
472 m = &err->m;
473 m->mcgstatus = mce_rdmsrq(MSR_IA32_MCG_STATUS);
474 if (regs) {
475 /*
476 * Get the address of the instruction at the time of
477 * the machine check error.
478 */
479 if (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV)) {
480 m->ip = regs->ip;
481 m->cs = regs->cs;
482
483 /*
484 * When in VM86 mode make the cs look like ring 3
485 * always. This is a lie, but it's better than passing
486 * the additional vm86 bit around everywhere.
487 */
488 if (v8086_mode(regs))
489 m->cs |= 3;
490 }
491 /* Use accurate RIP reporting if available. */
492 if (mca_cfg.rip_msr)
493 m->ip = mce_rdmsrq(mca_cfg.rip_msr);
494 }
495 }
496
mce_available(struct cpuinfo_x86 * c)497 bool mce_available(struct cpuinfo_x86 *c)
498 {
499 if (mca_cfg.disabled)
500 return false;
501 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
502 }
503
mce_schedule_work(void)504 static void mce_schedule_work(void)
505 {
506 if (!mce_gen_pool_empty())
507 schedule_work(&mce_work);
508 }
509
mce_irq_work_cb(struct irq_work * entry)510 static void mce_irq_work_cb(struct irq_work *entry)
511 {
512 mce_schedule_work();
513 }
514
mce_usable_address(struct mce * m)515 bool mce_usable_address(struct mce *m)
516 {
517 if (!(m->status & MCI_STATUS_ADDRV))
518 return false;
519
520 switch (m->cpuvendor) {
521 case X86_VENDOR_AMD:
522 return amd_mce_usable_address(m);
523
524 case X86_VENDOR_INTEL:
525 case X86_VENDOR_ZHAOXIN:
526 return intel_mce_usable_address(m);
527
528 default:
529 return true;
530 }
531 }
532 EXPORT_SYMBOL_GPL(mce_usable_address);
533
mce_is_memory_error(struct mce * m)534 bool mce_is_memory_error(struct mce *m)
535 {
536 switch (m->cpuvendor) {
537 case X86_VENDOR_AMD:
538 case X86_VENDOR_HYGON:
539 return amd_mce_is_memory_error(m);
540
541 case X86_VENDOR_INTEL:
542 case X86_VENDOR_ZHAOXIN:
543 /*
544 * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
545 *
546 * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
547 * indicating a memory error. Bit 8 is used for indicating a
548 * cache hierarchy error. The combination of bit 2 and bit 3
549 * is used for indicating a `generic' cache hierarchy error
550 * But we can't just blindly check the above bits, because if
551 * bit 11 is set, then it is a bus/interconnect error - and
552 * either way the above bits just gives more detail on what
553 * bus/interconnect error happened. Note that bit 12 can be
554 * ignored, as it's the "filter" bit.
555 */
556 return (m->status & 0xef80) == BIT(7) ||
557 (m->status & 0xef00) == BIT(8) ||
558 (m->status & 0xeffc) == 0xc;
559
560 default:
561 return false;
562 }
563 }
564 EXPORT_SYMBOL_GPL(mce_is_memory_error);
565
whole_page(struct mce * m)566 static bool whole_page(struct mce *m)
567 {
568 if (!mca_cfg.ser || !(m->status & MCI_STATUS_MISCV))
569 return true;
570
571 return MCI_MISC_ADDR_LSB(m->misc) >= PAGE_SHIFT;
572 }
573
mce_is_correctable(struct mce * m)574 bool mce_is_correctable(struct mce *m)
575 {
576 if (m->cpuvendor == X86_VENDOR_AMD && m->status & MCI_STATUS_DEFERRED)
577 return false;
578
579 if (m->cpuvendor == X86_VENDOR_HYGON && m->status & MCI_STATUS_DEFERRED)
580 return false;
581
582 if (m->status & MCI_STATUS_UC)
583 return false;
584
585 return true;
586 }
587 EXPORT_SYMBOL_GPL(mce_is_correctable);
588
mce_early_notifier(struct notifier_block * nb,unsigned long val,void * data)589 static int mce_early_notifier(struct notifier_block *nb, unsigned long val,
590 void *data)
591 {
592 struct mce_hw_err *err = to_mce_hw_err(data);
593
594 if (!err)
595 return NOTIFY_DONE;
596
597 /* Emit the trace record: */
598 trace_mce_record(err);
599
600 mce_work_trigger();
601
602 return NOTIFY_DONE;
603 }
604
605 static struct notifier_block early_nb = {
606 .notifier_call = mce_early_notifier,
607 .priority = MCE_PRIO_EARLY,
608 };
609
uc_decode_notifier(struct notifier_block * nb,unsigned long val,void * data)610 static int uc_decode_notifier(struct notifier_block *nb, unsigned long val,
611 void *data)
612 {
613 struct mce *mce = (struct mce *)data;
614 unsigned long pfn;
615
616 if (!mce || !mce_usable_address(mce))
617 return NOTIFY_DONE;
618
619 if (mce->severity != MCE_AO_SEVERITY &&
620 mce->severity != MCE_DEFERRED_SEVERITY)
621 return NOTIFY_DONE;
622
623 pfn = (mce->addr & MCI_ADDR_PHYSADDR) >> PAGE_SHIFT;
624 if (!memory_failure(pfn, 0)) {
625 set_mce_nospec(pfn);
626 mce->kflags |= MCE_HANDLED_UC;
627 }
628
629 return NOTIFY_OK;
630 }
631
632 static struct notifier_block mce_uc_nb = {
633 .notifier_call = uc_decode_notifier,
634 .priority = MCE_PRIO_UC,
635 };
636
mce_default_notifier(struct notifier_block * nb,unsigned long val,void * data)637 static int mce_default_notifier(struct notifier_block *nb, unsigned long val,
638 void *data)
639 {
640 struct mce_hw_err *err = to_mce_hw_err(data);
641
642 if (!err)
643 return NOTIFY_DONE;
644
645 if (mca_cfg.print_all || !(err->m.kflags))
646 __print_mce(err);
647
648 return NOTIFY_DONE;
649 }
650
651 static struct notifier_block mce_default_nb = {
652 .notifier_call = mce_default_notifier,
653 /* lowest prio, we want it to run last. */
654 .priority = MCE_PRIO_LOWEST,
655 };
656
657 /*
658 * Read ADDR and MISC registers.
659 */
mce_read_aux(struct mce_hw_err * err,int i)660 static noinstr void mce_read_aux(struct mce_hw_err *err, int i)
661 {
662 struct mce *m = &err->m;
663
664 if (m->status & MCI_STATUS_MISCV)
665 m->misc = mce_rdmsrq(mca_msr_reg(i, MCA_MISC));
666
667 if (m->status & MCI_STATUS_ADDRV) {
668 if (m->kflags & MCE_CHECK_DFR_REGS)
669 m->addr = mce_rdmsrq(MSR_AMD64_SMCA_MCx_DEADDR(i));
670 else
671 m->addr = mce_rdmsrq(mca_msr_reg(i, MCA_ADDR));
672
673 /*
674 * Mask the reported address by the reported granularity.
675 */
676 if (mca_cfg.ser && (m->status & MCI_STATUS_MISCV)) {
677 u8 shift = MCI_MISC_ADDR_LSB(m->misc);
678 m->addr >>= shift;
679 m->addr <<= shift;
680 }
681
682 smca_extract_err_addr(m);
683 }
684
685 if (mce_flags.smca) {
686 m->ipid = mce_rdmsrq(MSR_AMD64_SMCA_MCx_IPID(i));
687
688 if (m->status & MCI_STATUS_SYNDV) {
689 m->synd = mce_rdmsrq(MSR_AMD64_SMCA_MCx_SYND(i));
690 err->vendor.amd.synd1 = mce_rdmsrq(MSR_AMD64_SMCA_MCx_SYND1(i));
691 err->vendor.amd.synd2 = mce_rdmsrq(MSR_AMD64_SMCA_MCx_SYND2(i));
692 }
693 }
694 }
695
696 DEFINE_PER_CPU(unsigned, mce_poll_count);
697
698 /*
699 * We have three scenarios for checking for Deferred errors:
700 *
701 * 1) Non-SMCA systems check MCA_STATUS and log error if found.
702 * 2) SMCA systems check MCA_STATUS. If error is found then log it and also
703 * clear MCA_DESTAT.
704 * 3) SMCA systems check MCA_DESTAT, if error was not found in MCA_STATUS, and
705 * log it.
706 */
smca_should_log_poll_error(struct mce * m)707 static bool smca_should_log_poll_error(struct mce *m)
708 {
709 if (m->status & MCI_STATUS_VAL)
710 return true;
711
712 m->status = mce_rdmsrq(MSR_AMD64_SMCA_MCx_DESTAT(m->bank));
713 if ((m->status & MCI_STATUS_VAL) && (m->status & MCI_STATUS_DEFERRED)) {
714 m->kflags |= MCE_CHECK_DFR_REGS;
715 return true;
716 }
717
718 return false;
719 }
720
721 /*
722 * Newer Intel systems that support software error
723 * recovery need to make additional checks. Other
724 * CPUs should skip over uncorrected errors, but log
725 * everything else.
726 */
ser_should_log_poll_error(struct mce * m)727 static bool ser_should_log_poll_error(struct mce *m)
728 {
729 /* Log "not enabled" (speculative) errors */
730 if (!(m->status & MCI_STATUS_EN))
731 return true;
732
733 /*
734 * Log UCNA (SDM: 15.6.3 "UCR Error Classification")
735 * UC == 1 && PCC == 0 && S == 0
736 */
737 if (!(m->status & MCI_STATUS_PCC) && !(m->status & MCI_STATUS_S))
738 return true;
739
740 return false;
741 }
742
should_log_poll_error(enum mcp_flags flags,struct mce_hw_err * err)743 static bool should_log_poll_error(enum mcp_flags flags, struct mce_hw_err *err)
744 {
745 struct mce *m = &err->m;
746
747 if (mce_flags.smca)
748 return smca_should_log_poll_error(m);
749
750 /* If this entry is not valid, ignore it. */
751 if (!(m->status & MCI_STATUS_VAL))
752 return false;
753
754 /*
755 * If we are logging everything (at CPU online) or this
756 * is a corrected error, then we must log it.
757 */
758 if ((flags & MCP_UC) || !(m->status & MCI_STATUS_UC))
759 return true;
760
761 if (mca_cfg.ser)
762 return ser_should_log_poll_error(m);
763
764 if (m->status & MCI_STATUS_UC)
765 return false;
766
767 return true;
768 }
769
clear_bank(struct mce * m)770 static void clear_bank(struct mce *m)
771 {
772 if (m->cpuvendor == X86_VENDOR_AMD)
773 return amd_clear_bank(m);
774
775 mce_wrmsrq(mca_msr_reg(m->bank, MCA_STATUS), 0);
776 }
777
778 /*
779 * Poll for corrected events or events that happened before reset.
780 * Those are just logged through /dev/mcelog.
781 *
782 * This is executed in standard interrupt context.
783 *
784 * Note: spec recommends to panic for fatal unsignalled
785 * errors here. However this would be quite problematic --
786 * we would need to reimplement the Monarch handling and
787 * it would mess up the exclusion between exception handler
788 * and poll handler -- * so we skip this for now.
789 * These cases should not happen anyways, or only when the CPU
790 * is already totally * confused. In this case it's likely it will
791 * not fully execute the machine check handler either.
792 */
machine_check_poll(enum mcp_flags flags,mce_banks_t * b)793 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
794 {
795 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
796 struct mce_hw_err err;
797 struct mce *m;
798 int i;
799
800 this_cpu_inc(mce_poll_count);
801
802 mce_gather_info(&err, NULL);
803 m = &err.m;
804
805 if (flags & MCP_TIMESTAMP)
806 m->tsc = rdtsc();
807
808 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
809 if (!mce_banks[i].ctl || !test_bit(i, *b))
810 continue;
811
812 m->misc = 0;
813 m->addr = 0;
814 m->bank = i;
815
816 barrier();
817 m->status = mce_rdmsrq(mca_msr_reg(i, MCA_STATUS));
818
819 /*
820 * Update storm tracking here, before checking for the
821 * MCI_STATUS_VAL bit. Valid corrected errors count
822 * towards declaring, or maintaining, storm status. No
823 * error in a bank counts towards avoiding, or ending,
824 * storm status.
825 */
826 if (!mca_cfg.cmci_disabled)
827 mce_track_storm(m);
828
829 /* Verify that the error should be logged based on hardware conditions. */
830 if (!should_log_poll_error(flags, &err))
831 continue;
832
833 mce_read_aux(&err, i);
834 m->severity = mce_severity(m, NULL, NULL, false);
835 /*
836 * Don't get the IP here because it's unlikely to
837 * have anything to do with the actual error location.
838 */
839
840 if (mca_cfg.dont_log_ce && !mce_usable_address(m))
841 goto clear_it;
842
843 if (flags & MCP_QUEUE_LOG)
844 mce_gen_pool_add(&err);
845 else
846 mce_log(&err);
847
848 clear_it:
849 clear_bank(m);
850 }
851
852 /*
853 * Don't clear MCG_STATUS here because it's only defined for
854 * exceptions.
855 */
856
857 sync_core();
858 }
859 EXPORT_SYMBOL_GPL(machine_check_poll);
860
861 /*
862 * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
863 * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
864 * Vol 3B Table 15-20). But this confuses both the code that determines
865 * whether the machine check occurred in kernel or user mode, and also
866 * the severity assessment code. Pretend that EIPV was set, and take the
867 * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
868 */
869 static __always_inline void
quirk_sandybridge_ifu(int bank,struct mce * m,struct pt_regs * regs)870 quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
871 {
872 if (bank != 0)
873 return;
874 if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
875 return;
876 if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
877 MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
878 MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
879 MCACOD)) !=
880 (MCI_STATUS_UC|MCI_STATUS_EN|
881 MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
882 MCI_STATUS_AR|MCACOD_INSTR))
883 return;
884
885 m->mcgstatus |= MCG_STATUS_EIPV;
886 m->ip = regs->ip;
887 m->cs = regs->cs;
888 }
889
890 /*
891 * Disable fast string copy and return from the MCE handler upon the first SRAR
892 * MCE on bank 1 due to a CPU erratum on Intel Skylake/Cascade Lake/Cooper Lake
893 * CPUs.
894 * The fast string copy instructions ("REP; MOVS*") could consume an
895 * uncorrectable memory error in the cache line _right after_ the desired region
896 * to copy and raise an MCE with RIP pointing to the instruction _after_ the
897 * "REP; MOVS*".
898 * This mitigation addresses the issue completely with the caveat of performance
899 * degradation on the CPU affected. This is still better than the OS crashing on
900 * MCEs raised on an irrelevant process due to "REP; MOVS*" accesses from a
901 * kernel context (e.g., copy_page).
902 *
903 * Returns true when fast string copy on CPU has been disabled.
904 */
quirk_skylake_repmov(void)905 static noinstr bool quirk_skylake_repmov(void)
906 {
907 u64 mcgstatus = mce_rdmsrq(MSR_IA32_MCG_STATUS);
908 u64 misc_enable = mce_rdmsrq(MSR_IA32_MISC_ENABLE);
909 u64 mc1_status;
910
911 /*
912 * Apply the quirk only to local machine checks, i.e., no broadcast
913 * sync is needed.
914 */
915 if (!(mcgstatus & MCG_STATUS_LMCES) ||
916 !(misc_enable & MSR_IA32_MISC_ENABLE_FAST_STRING))
917 return false;
918
919 mc1_status = mce_rdmsrq(MSR_IA32_MCx_STATUS(1));
920
921 /* Check for a software-recoverable data fetch error. */
922 if ((mc1_status &
923 (MCI_STATUS_VAL | MCI_STATUS_OVER | MCI_STATUS_UC | MCI_STATUS_EN |
924 MCI_STATUS_ADDRV | MCI_STATUS_MISCV | MCI_STATUS_PCC |
925 MCI_STATUS_AR | MCI_STATUS_S)) ==
926 (MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN |
927 MCI_STATUS_ADDRV | MCI_STATUS_MISCV |
928 MCI_STATUS_AR | MCI_STATUS_S)) {
929 misc_enable &= ~MSR_IA32_MISC_ENABLE_FAST_STRING;
930 mce_wrmsrq(MSR_IA32_MISC_ENABLE, misc_enable);
931 mce_wrmsrq(MSR_IA32_MCx_STATUS(1), 0);
932
933 instrumentation_begin();
934 pr_err_once("Erratum detected, disable fast string copy instructions.\n");
935 instrumentation_end();
936
937 return true;
938 }
939
940 return false;
941 }
942
943 /*
944 * Some Zen-based Instruction Fetch Units set EIPV=RIPV=0 on poison consumption
945 * errors. This means mce_gather_info() will not save the "ip" and "cs" registers.
946 *
947 * However, the context is still valid, so save the "cs" register for later use.
948 *
949 * The "ip" register is truly unknown, so don't save it or fixup EIPV/RIPV.
950 *
951 * The Instruction Fetch Unit is at MCA bank 1 for all affected systems.
952 */
quirk_zen_ifu(int bank,struct mce * m,struct pt_regs * regs)953 static __always_inline void quirk_zen_ifu(int bank, struct mce *m, struct pt_regs *regs)
954 {
955 if (bank != 1)
956 return;
957 if (!(m->status & MCI_STATUS_POISON))
958 return;
959
960 m->cs = regs->cs;
961 }
962
963 /*
964 * Do a quick check if any of the events requires a panic.
965 * This decides if we keep the events around or clear them.
966 */
mce_no_way_out(struct mce_hw_err * err,char ** msg,unsigned long * validp,struct pt_regs * regs)967 static __always_inline int mce_no_way_out(struct mce_hw_err *err, char **msg, unsigned long *validp,
968 struct pt_regs *regs)
969 {
970 struct mce *m = &err->m;
971 char *tmp = *msg;
972 int i;
973
974 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
975 m->status = mce_rdmsrq(mca_msr_reg(i, MCA_STATUS));
976 if (!(m->status & MCI_STATUS_VAL))
977 continue;
978
979 arch___set_bit(i, validp);
980 if (mce_flags.snb_ifu_quirk)
981 quirk_sandybridge_ifu(i, m, regs);
982
983 if (mce_flags.zen_ifu_quirk)
984 quirk_zen_ifu(i, m, regs);
985
986 m->bank = i;
987 if (mce_severity(m, regs, &tmp, true) >= MCE_PANIC_SEVERITY) {
988 mce_read_aux(err, i);
989 *msg = tmp;
990 return 1;
991 }
992 }
993 return 0;
994 }
995
996 /*
997 * Variable to establish order between CPUs while scanning.
998 * Each CPU spins initially until executing is equal its number.
999 */
1000 static atomic_t mce_executing;
1001
1002 /*
1003 * Defines order of CPUs on entry. First CPU becomes Monarch.
1004 */
1005 static atomic_t mce_callin;
1006
1007 /*
1008 * Track which CPUs entered the MCA broadcast synchronization and which not in
1009 * order to print holdouts.
1010 */
1011 static cpumask_t mce_missing_cpus = CPU_MASK_ALL;
1012
1013 /*
1014 * Check if a timeout waiting for other CPUs happened.
1015 */
mce_timed_out(u64 * t,const char * msg)1016 static noinstr int mce_timed_out(u64 *t, const char *msg)
1017 {
1018 int ret = 0;
1019
1020 /* Enable instrumentation around calls to external facilities */
1021 instrumentation_begin();
1022
1023 /*
1024 * The others already did panic for some reason.
1025 * Bail out like in a timeout.
1026 * rmb() to tell the compiler that system_state
1027 * might have been modified by someone else.
1028 */
1029 rmb();
1030 if (atomic_read(&mce_panicked))
1031 wait_for_panic();
1032 if (!mca_cfg.monarch_timeout)
1033 goto out;
1034 if ((s64)*t < SPINUNIT) {
1035 if (cpumask_and(&mce_missing_cpus, cpu_online_mask, &mce_missing_cpus))
1036 pr_emerg("CPUs not responding to MCE broadcast (may include false positives): %*pbl\n",
1037 cpumask_pr_args(&mce_missing_cpus));
1038 mce_panic(msg, NULL, NULL);
1039
1040 ret = 1;
1041 goto out;
1042 }
1043 *t -= SPINUNIT;
1044
1045 out:
1046 touch_nmi_watchdog();
1047
1048 instrumentation_end();
1049
1050 return ret;
1051 }
1052
1053 /*
1054 * The Monarch's reign. The Monarch is the CPU who entered
1055 * the machine check handler first. It waits for the others to
1056 * raise the exception too and then grades them. When any
1057 * error is fatal panic. Only then let the others continue.
1058 *
1059 * The other CPUs entering the MCE handler will be controlled by the
1060 * Monarch. They are called Subjects.
1061 *
1062 * This way we prevent any potential data corruption in a unrecoverable case
1063 * and also makes sure always all CPU's errors are examined.
1064 *
1065 * Also this detects the case of a machine check event coming from outer
1066 * space (not detected by any CPUs) In this case some external agent wants
1067 * us to shut down, so panic too.
1068 *
1069 * The other CPUs might still decide to panic if the handler happens
1070 * in a unrecoverable place, but in this case the system is in a semi-stable
1071 * state and won't corrupt anything by itself. It's ok to let the others
1072 * continue for a bit first.
1073 *
1074 * All the spin loops have timeouts; when a timeout happens a CPU
1075 * typically elects itself to be Monarch.
1076 */
mce_reign(void)1077 static void mce_reign(void)
1078 {
1079 struct mce_hw_err *err = NULL;
1080 struct mce *m = NULL;
1081 int global_worst = 0;
1082 char *msg = NULL;
1083 int cpu;
1084
1085 /*
1086 * This CPU is the Monarch and the other CPUs have run
1087 * through their handlers.
1088 * Grade the severity of the errors of all the CPUs.
1089 */
1090 for_each_possible_cpu(cpu) {
1091 struct mce_hw_err *etmp = &per_cpu(hw_errs_seen, cpu);
1092 struct mce *mtmp = &etmp->m;
1093
1094 if (mtmp->severity > global_worst) {
1095 global_worst = mtmp->severity;
1096 err = &per_cpu(hw_errs_seen, cpu);
1097 m = &err->m;
1098 }
1099 }
1100
1101 /*
1102 * Cannot recover? Panic here then.
1103 * This dumps all the mces in the log buffer and stops the
1104 * other CPUs.
1105 */
1106 if (m && global_worst >= MCE_PANIC_SEVERITY) {
1107 /* call mce_severity() to get "msg" for panic */
1108 mce_severity(m, NULL, &msg, true);
1109 mce_panic("Fatal machine check", err, msg);
1110 }
1111
1112 /*
1113 * For UC somewhere we let the CPU who detects it handle it.
1114 * Also must let continue the others, otherwise the handling
1115 * CPU could deadlock on a lock.
1116 */
1117
1118 /*
1119 * No machine check event found. Must be some external
1120 * source or one CPU is hung. Panic.
1121 */
1122 if (global_worst <= MCE_KEEP_SEVERITY)
1123 mce_panic("Fatal machine check from unknown source", NULL, NULL);
1124
1125 /*
1126 * Now clear all the hw_errs_seen so that they don't reappear on
1127 * the next mce.
1128 */
1129 for_each_possible_cpu(cpu)
1130 memset(&per_cpu(hw_errs_seen, cpu), 0, sizeof(struct mce_hw_err));
1131 }
1132
1133 static atomic_t global_nwo;
1134
1135 /*
1136 * Start of Monarch synchronization. This waits until all CPUs have
1137 * entered the exception handler and then determines if any of them
1138 * saw a fatal event that requires panic. Then it executes them
1139 * in the entry order.
1140 * TBD double check parallel CPU hotunplug
1141 */
mce_start(int * no_way_out)1142 static noinstr int mce_start(int *no_way_out)
1143 {
1144 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
1145 int order, ret = -1;
1146
1147 if (!timeout)
1148 return ret;
1149
1150 raw_atomic_add(*no_way_out, &global_nwo);
1151 /*
1152 * Rely on the implied barrier below, such that global_nwo
1153 * is updated before mce_callin.
1154 */
1155 order = raw_atomic_inc_return(&mce_callin);
1156 arch_cpumask_clear_cpu(smp_processor_id(), &mce_missing_cpus);
1157
1158 /* Enable instrumentation around calls to external facilities */
1159 instrumentation_begin();
1160
1161 /*
1162 * Wait for everyone.
1163 */
1164 while (raw_atomic_read(&mce_callin) != num_online_cpus()) {
1165 if (mce_timed_out(&timeout,
1166 "Timeout: Not all CPUs entered broadcast exception handler")) {
1167 raw_atomic_set(&global_nwo, 0);
1168 goto out;
1169 }
1170 ndelay(SPINUNIT);
1171 }
1172
1173 /*
1174 * mce_callin should be read before global_nwo
1175 */
1176 smp_rmb();
1177
1178 if (order == 1) {
1179 /*
1180 * Monarch: Starts executing now, the others wait.
1181 */
1182 raw_atomic_set(&mce_executing, 1);
1183 } else {
1184 /*
1185 * Subject: Now start the scanning loop one by one in
1186 * the original callin order.
1187 * This way when there are any shared banks it will be
1188 * only seen by one CPU before cleared, avoiding duplicates.
1189 */
1190 while (raw_atomic_read(&mce_executing) < order) {
1191 if (mce_timed_out(&timeout,
1192 "Timeout: Subject CPUs unable to finish machine check processing")) {
1193 raw_atomic_set(&global_nwo, 0);
1194 goto out;
1195 }
1196 ndelay(SPINUNIT);
1197 }
1198 }
1199
1200 /*
1201 * Cache the global no_way_out state.
1202 */
1203 *no_way_out = raw_atomic_read(&global_nwo);
1204
1205 ret = order;
1206
1207 out:
1208 instrumentation_end();
1209
1210 return ret;
1211 }
1212
1213 /*
1214 * Synchronize between CPUs after main scanning loop.
1215 * This invokes the bulk of the Monarch processing.
1216 */
mce_end(int order)1217 static noinstr int mce_end(int order)
1218 {
1219 u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
1220 int ret = -1;
1221
1222 /* Allow instrumentation around external facilities. */
1223 instrumentation_begin();
1224
1225 if (!timeout)
1226 goto reset;
1227 if (order < 0)
1228 goto reset;
1229
1230 /*
1231 * Allow others to run.
1232 */
1233 atomic_inc(&mce_executing);
1234
1235 if (order == 1) {
1236 /*
1237 * Monarch: Wait for everyone to go through their scanning
1238 * loops.
1239 */
1240 while (atomic_read(&mce_executing) <= num_online_cpus()) {
1241 if (mce_timed_out(&timeout,
1242 "Timeout: Monarch CPU unable to finish machine check processing"))
1243 goto reset;
1244 ndelay(SPINUNIT);
1245 }
1246
1247 mce_reign();
1248 barrier();
1249 ret = 0;
1250 } else {
1251 /*
1252 * Subject: Wait for Monarch to finish.
1253 */
1254 while (atomic_read(&mce_executing) != 0) {
1255 if (mce_timed_out(&timeout,
1256 "Timeout: Monarch CPU did not finish machine check processing"))
1257 goto reset;
1258 ndelay(SPINUNIT);
1259 }
1260
1261 /*
1262 * Don't reset anything. That's done by the Monarch.
1263 */
1264 ret = 0;
1265 goto out;
1266 }
1267
1268 /*
1269 * Reset all global state.
1270 */
1271 reset:
1272 atomic_set(&global_nwo, 0);
1273 atomic_set(&mce_callin, 0);
1274 cpumask_setall(&mce_missing_cpus);
1275 barrier();
1276
1277 /*
1278 * Let others run again.
1279 */
1280 atomic_set(&mce_executing, 0);
1281
1282 out:
1283 instrumentation_end();
1284
1285 return ret;
1286 }
1287
mce_clear_state(unsigned long * toclear)1288 static __always_inline void mce_clear_state(unsigned long *toclear)
1289 {
1290 int i;
1291
1292 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1293 if (arch_test_bit(i, toclear))
1294 mce_wrmsrq(mca_msr_reg(i, MCA_STATUS), 0);
1295 }
1296 }
1297
1298 /*
1299 * Cases where we avoid rendezvous handler timeout:
1300 * 1) If this CPU is offline.
1301 *
1302 * 2) If crashing_cpu was set, e.g. we're entering kdump and we need to
1303 * skip those CPUs which remain looping in the 1st kernel - see
1304 * crash_nmi_callback().
1305 *
1306 * Note: there still is a small window between kexec-ing and the new,
1307 * kdump kernel establishing a new #MC handler where a broadcasted MCE
1308 * might not get handled properly.
1309 */
mce_check_crashing_cpu(void)1310 static noinstr bool mce_check_crashing_cpu(void)
1311 {
1312 unsigned int cpu = smp_processor_id();
1313
1314 if (arch_cpu_is_offline(cpu) ||
1315 (crashing_cpu != -1 && crashing_cpu != cpu)) {
1316 u64 mcgstatus;
1317
1318 mcgstatus = native_rdmsrq(MSR_IA32_MCG_STATUS);
1319
1320 if (boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN) {
1321 if (mcgstatus & MCG_STATUS_LMCES)
1322 return false;
1323 }
1324
1325 if (mcgstatus & MCG_STATUS_RIPV) {
1326 native_wrmsrq(MSR_IA32_MCG_STATUS, 0);
1327 return true;
1328 }
1329 }
1330 return false;
1331 }
1332
1333 static __always_inline int
__mc_scan_banks(struct mce_hw_err * err,struct pt_regs * regs,struct mce_hw_err * final,unsigned long * toclear,unsigned long * valid_banks,int no_way_out,int * worst)1334 __mc_scan_banks(struct mce_hw_err *err, struct pt_regs *regs,
1335 struct mce_hw_err *final, unsigned long *toclear,
1336 unsigned long *valid_banks, int no_way_out, int *worst)
1337 {
1338 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1339 struct mca_config *cfg = &mca_cfg;
1340 int severity, i, taint = 0;
1341 struct mce *m = &err->m;
1342
1343 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1344 arch___clear_bit(i, toclear);
1345 if (!arch_test_bit(i, valid_banks))
1346 continue;
1347
1348 if (!mce_banks[i].ctl)
1349 continue;
1350
1351 m->misc = 0;
1352 m->addr = 0;
1353 m->bank = i;
1354
1355 m->status = mce_rdmsrq(mca_msr_reg(i, MCA_STATUS));
1356 if (!(m->status & MCI_STATUS_VAL))
1357 continue;
1358
1359 /*
1360 * Corrected or non-signaled errors are handled by
1361 * machine_check_poll(). Leave them alone, unless this panics.
1362 */
1363 if (!(m->status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1364 !no_way_out)
1365 continue;
1366
1367 /* Set taint even when machine check was not enabled. */
1368 taint++;
1369
1370 severity = mce_severity(m, regs, NULL, true);
1371
1372 /*
1373 * When machine check was for corrected/deferred handler don't
1374 * touch, unless we're panicking.
1375 */
1376 if ((severity == MCE_KEEP_SEVERITY ||
1377 severity == MCE_UCNA_SEVERITY) && !no_way_out)
1378 continue;
1379
1380 arch___set_bit(i, toclear);
1381
1382 /* Machine check event was not enabled. Clear, but ignore. */
1383 if (severity == MCE_NO_SEVERITY)
1384 continue;
1385
1386 mce_read_aux(err, i);
1387
1388 /* assuming valid severity level != 0 */
1389 m->severity = severity;
1390
1391 /*
1392 * Enable instrumentation around the mce_log() call which is
1393 * done in #MC context, where instrumentation is disabled.
1394 */
1395 instrumentation_begin();
1396 mce_log(err);
1397 instrumentation_end();
1398
1399 if (severity > *worst) {
1400 *final = *err;
1401 *worst = severity;
1402 }
1403 }
1404
1405 /* mce_clear_state will clear *final, save locally for use later */
1406 *err = *final;
1407
1408 return taint;
1409 }
1410
kill_me_now(struct callback_head * ch)1411 static void kill_me_now(struct callback_head *ch)
1412 {
1413 struct task_struct *p = container_of(ch, struct task_struct, mce_kill_me);
1414
1415 p->mce_count = 0;
1416 force_sig(SIGBUS);
1417 }
1418
kill_me_maybe(struct callback_head * cb)1419 static void kill_me_maybe(struct callback_head *cb)
1420 {
1421 struct task_struct *p = container_of(cb, struct task_struct, mce_kill_me);
1422 int flags = MF_ACTION_REQUIRED;
1423 unsigned long pfn;
1424 int ret;
1425
1426 p->mce_count = 0;
1427 pr_err("Uncorrected hardware memory error in user-access at %llx", p->mce_addr);
1428
1429 if (!p->mce_ripv)
1430 flags |= MF_MUST_KILL;
1431
1432 pfn = (p->mce_addr & MCI_ADDR_PHYSADDR) >> PAGE_SHIFT;
1433 ret = memory_failure(pfn, flags);
1434 if (!ret) {
1435 set_mce_nospec(pfn);
1436 sync_core();
1437 return;
1438 }
1439
1440 /*
1441 * -EHWPOISON from memory_failure() means that it already sent SIGBUS
1442 * to the current process with the proper error info,
1443 * -EOPNOTSUPP means hwpoison_filter() filtered the error event,
1444 *
1445 * In both cases, no further processing is required.
1446 */
1447 if (ret == -EHWPOISON || ret == -EOPNOTSUPP)
1448 return;
1449
1450 pr_err("Memory error not recovered");
1451 kill_me_now(cb);
1452 }
1453
kill_me_never(struct callback_head * cb)1454 static void kill_me_never(struct callback_head *cb)
1455 {
1456 struct task_struct *p = container_of(cb, struct task_struct, mce_kill_me);
1457 unsigned long pfn;
1458
1459 p->mce_count = 0;
1460 pr_err("Kernel accessed poison in user space at %llx\n", p->mce_addr);
1461 pfn = (p->mce_addr & MCI_ADDR_PHYSADDR) >> PAGE_SHIFT;
1462 if (!memory_failure(pfn, 0))
1463 set_mce_nospec(pfn);
1464 }
1465
queue_task_work(struct mce_hw_err * err,char * msg,void (* func)(struct callback_head *))1466 static void queue_task_work(struct mce_hw_err *err, char *msg, void (*func)(struct callback_head *))
1467 {
1468 int count = ++current->mce_count;
1469 struct mce *m = &err->m;
1470
1471 /* First call, save all the details */
1472 if (count == 1) {
1473 current->mce_addr = m->addr;
1474 current->mce_kflags = m->kflags;
1475 current->mce_ripv = !!(m->mcgstatus & MCG_STATUS_RIPV);
1476 current->mce_whole_page = whole_page(m);
1477 current->mce_kill_me.func = func;
1478 }
1479
1480 /* Ten is likely overkill. Don't expect more than two faults before task_work() */
1481 if (count > 10)
1482 mce_panic("Too many consecutive machine checks while accessing user data",
1483 err, msg);
1484
1485 /* Second or later call, make sure page address matches the one from first call */
1486 if (count > 1 && (current->mce_addr >> PAGE_SHIFT) != (m->addr >> PAGE_SHIFT))
1487 mce_panic("Consecutive machine checks to different user pages", err, msg);
1488
1489 /* Do not call task_work_add() more than once */
1490 if (count > 1)
1491 return;
1492
1493 task_work_add(current, ¤t->mce_kill_me, TWA_RESUME);
1494 }
1495
1496 /* Handle unconfigured int18 (should never happen) */
unexpected_machine_check(struct pt_regs * regs)1497 static noinstr void unexpected_machine_check(struct pt_regs *regs)
1498 {
1499 instrumentation_begin();
1500 pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1501 smp_processor_id());
1502 instrumentation_end();
1503 }
1504
1505 /*
1506 * The actual machine check handler. This only handles real exceptions when
1507 * something got corrupted coming in through int 18.
1508 *
1509 * This is executed in #MC context not subject to normal locking rules.
1510 * This implies that most kernel services cannot be safely used. Don't even
1511 * think about putting a printk in there!
1512 *
1513 * On Intel systems this is entered on all CPUs in parallel through
1514 * MCE broadcast. However some CPUs might be broken beyond repair,
1515 * so be always careful when synchronizing with others.
1516 *
1517 * Tracing and kprobes are disabled: if we interrupted a kernel context
1518 * with IF=1, we need to minimize stack usage. There are also recursion
1519 * issues: if the machine check was due to a failure of the memory
1520 * backing the user stack, tracing that reads the user stack will cause
1521 * potentially infinite recursion.
1522 *
1523 * Currently, the #MC handler calls out to a number of external facilities
1524 * and, therefore, allows instrumentation around them. The optimal thing to
1525 * have would be to do the absolutely minimal work required in #MC context
1526 * and have instrumentation disabled only around that. Further processing can
1527 * then happen in process context where instrumentation is allowed. Achieving
1528 * that requires careful auditing and modifications. Until then, the code
1529 * allows instrumentation temporarily, where required. *
1530 */
do_machine_check(struct pt_regs * regs)1531 noinstr void do_machine_check(struct pt_regs *regs)
1532 {
1533 int worst = 0, order, no_way_out, kill_current_task, lmce, taint = 0;
1534 DECLARE_BITMAP(valid_banks, MAX_NR_BANKS) = { 0 };
1535 DECLARE_BITMAP(toclear, MAX_NR_BANKS) = { 0 };
1536 struct mce_hw_err *final;
1537 struct mce_hw_err err;
1538 char *msg = NULL;
1539 struct mce *m;
1540
1541 if (unlikely(mce_flags.p5))
1542 return pentium_machine_check(regs);
1543 else if (unlikely(mce_flags.winchip))
1544 return winchip_machine_check(regs);
1545 else if (unlikely(!mca_cfg.initialized))
1546 return unexpected_machine_check(regs);
1547
1548 if (mce_flags.skx_repmov_quirk && quirk_skylake_repmov())
1549 goto clear;
1550
1551 /*
1552 * Establish sequential order between the CPUs entering the machine
1553 * check handler.
1554 */
1555 order = -1;
1556
1557 /*
1558 * If no_way_out gets set, there is no safe way to recover from this
1559 * MCE.
1560 */
1561 no_way_out = 0;
1562
1563 /*
1564 * If kill_current_task is not set, there might be a way to recover from this
1565 * error.
1566 */
1567 kill_current_task = 0;
1568
1569 /*
1570 * MCEs are always local on AMD. Same is determined by MCG_STATUS_LMCES
1571 * on Intel.
1572 */
1573 lmce = 1;
1574
1575 this_cpu_inc(mce_exception_count);
1576
1577 mce_gather_info(&err, regs);
1578 m = &err.m;
1579 m->tsc = rdtsc();
1580
1581 final = this_cpu_ptr(&hw_errs_seen);
1582 *final = err;
1583
1584 no_way_out = mce_no_way_out(&err, &msg, valid_banks, regs);
1585
1586 barrier();
1587
1588 /*
1589 * When no restart IP might need to kill or panic.
1590 * Assume the worst for now, but if we find the
1591 * severity is MCE_AR_SEVERITY we have other options.
1592 */
1593 if (!(m->mcgstatus & MCG_STATUS_RIPV))
1594 kill_current_task = 1;
1595 /*
1596 * Check if this MCE is signaled to only this logical processor,
1597 * on Intel, Zhaoxin only.
1598 */
1599 if (m->cpuvendor == X86_VENDOR_INTEL ||
1600 m->cpuvendor == X86_VENDOR_ZHAOXIN)
1601 lmce = m->mcgstatus & MCG_STATUS_LMCES;
1602
1603 /*
1604 * Local machine check may already know that we have to panic.
1605 * Broadcast machine check begins rendezvous in mce_start()
1606 * Go through all banks in exclusion of the other CPUs. This way we
1607 * don't report duplicated events on shared banks because the first one
1608 * to see it will clear it.
1609 */
1610 if (lmce) {
1611 if (no_way_out)
1612 mce_panic("Fatal local machine check", &err, msg);
1613 } else {
1614 order = mce_start(&no_way_out);
1615 }
1616
1617 taint = __mc_scan_banks(&err, regs, final, toclear, valid_banks, no_way_out, &worst);
1618
1619 if (!no_way_out)
1620 mce_clear_state(toclear);
1621
1622 /*
1623 * Do most of the synchronization with other CPUs.
1624 * When there's any problem use only local no_way_out state.
1625 */
1626 if (!lmce) {
1627 if (mce_end(order) < 0) {
1628 if (!no_way_out)
1629 no_way_out = worst >= MCE_PANIC_SEVERITY;
1630
1631 if (no_way_out)
1632 mce_panic("Fatal machine check on current CPU", &err, msg);
1633 }
1634 } else {
1635 /*
1636 * If there was a fatal machine check we should have
1637 * already called mce_panic earlier in this function.
1638 * Since we re-read the banks, we might have found
1639 * something new. Check again to see if we found a
1640 * fatal error. We call "mce_severity()" again to
1641 * make sure we have the right "msg".
1642 */
1643 if (worst >= MCE_PANIC_SEVERITY) {
1644 mce_severity(m, regs, &msg, true);
1645 mce_panic("Local fatal machine check!", &err, msg);
1646 }
1647 }
1648
1649 /*
1650 * Enable instrumentation around the external facilities like task_work_add()
1651 * (via queue_task_work()), fixup_exception() etc. For now, that is. Fixing this
1652 * properly would need a lot more involved reorganization.
1653 */
1654 instrumentation_begin();
1655
1656 if (taint)
1657 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1658
1659 if (worst != MCE_AR_SEVERITY && !kill_current_task)
1660 goto out;
1661
1662 /* Fault was in user mode and we need to take some action */
1663 if ((m->cs & 3) == 3) {
1664 /* If this triggers there is no way to recover. Die hard. */
1665 BUG_ON(!on_thread_stack() || !user_mode(regs));
1666
1667 if (!mce_usable_address(m))
1668 queue_task_work(&err, msg, kill_me_now);
1669 else
1670 queue_task_work(&err, msg, kill_me_maybe);
1671
1672 } else if (m->mcgstatus & MCG_STATUS_SEAM_NR) {
1673 /*
1674 * Saved RIP on stack makes it look like the machine check
1675 * was taken in the kernel on the instruction following
1676 * the entry to SEAM mode. But MCG_STATUS_SEAM_NR indicates
1677 * that the machine check was taken inside SEAM non-root
1678 * mode. CPU core has already marked that guest as dead.
1679 * It is OK for the kernel to resume execution at the
1680 * apparent point of the machine check as the fault did
1681 * not occur there. Mark the page as poisoned so it won't
1682 * be added to free list when the guest is terminated.
1683 */
1684 if (mce_usable_address(m)) {
1685 struct page *p = pfn_to_online_page(m->addr >> PAGE_SHIFT);
1686
1687 if (p)
1688 SetPageHWPoison(p);
1689 }
1690 } else {
1691 /*
1692 * Handle an MCE which has happened in kernel space but from
1693 * which the kernel can recover: ex_has_fault_handler() has
1694 * already verified that the rIP at which the error happened is
1695 * a rIP from which the kernel can recover (by jumping to
1696 * recovery code specified in _ASM_EXTABLE_FAULT()) and the
1697 * corresponding exception handler which would do that is the
1698 * proper one.
1699 */
1700 if (m->kflags & MCE_IN_KERNEL_RECOV) {
1701 if (!fixup_exception(regs, X86_TRAP_MC, 0, 0))
1702 mce_panic("Failed kernel mode recovery", &err, msg);
1703 }
1704
1705 if (m->kflags & MCE_IN_KERNEL_COPYIN)
1706 queue_task_work(&err, msg, kill_me_never);
1707 }
1708
1709 out:
1710 /* Given it didn't panic, mark it as recoverable */
1711 hwerr_log_error_type(HWERR_RECOV_OTHERS);
1712
1713 instrumentation_end();
1714
1715 clear:
1716 mce_wrmsrq(MSR_IA32_MCG_STATUS, 0);
1717 }
1718 EXPORT_SYMBOL_GPL(do_machine_check);
1719
1720 #ifndef CONFIG_MEMORY_FAILURE
memory_failure(unsigned long pfn,int flags)1721 int memory_failure(unsigned long pfn, int flags)
1722 {
1723 /* mce_severity() should not hand us an ACTION_REQUIRED error */
1724 BUG_ON(flags & MF_ACTION_REQUIRED);
1725 pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1726 "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1727 pfn);
1728
1729 return 0;
1730 }
1731 #endif
1732
1733 /*
1734 * Periodic polling timer for "silent" machine check errors. If the
1735 * poller finds an MCE, poll 2x faster. When the poller finds no more
1736 * errors, poll 2x slower (up to check_interval seconds).
1737 */
1738 static unsigned long check_interval = INITIAL_CHECK_INTERVAL;
1739
1740 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1741 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1742
__start_timer(struct timer_list * t,unsigned long interval)1743 static void __start_timer(struct timer_list *t, unsigned long interval)
1744 {
1745 unsigned long when = jiffies + interval;
1746 unsigned long flags;
1747
1748 local_irq_save(flags);
1749
1750 if (!timer_pending(t) || time_before(when, t->expires))
1751 mod_timer(t, round_jiffies(when));
1752
1753 local_irq_restore(flags);
1754 }
1755
mc_poll_banks_default(void)1756 static void mc_poll_banks_default(void)
1757 {
1758 machine_check_poll(0, this_cpu_ptr(&mce_poll_banks));
1759 }
1760
1761 void (*mc_poll_banks)(void) = mc_poll_banks_default;
1762
should_enable_timer(unsigned long iv)1763 static bool should_enable_timer(unsigned long iv)
1764 {
1765 return !mca_cfg.ignore_ce && iv;
1766 }
1767
mce_timer_fn(struct timer_list * t)1768 static void mce_timer_fn(struct timer_list *t)
1769 {
1770 struct timer_list *cpu_t = this_cpu_ptr(&mce_timer);
1771 unsigned long iv;
1772
1773 WARN_ON(cpu_t != t);
1774
1775 iv = __this_cpu_read(mce_next_interval);
1776
1777 if (mce_available(this_cpu_ptr(&cpu_info)))
1778 mc_poll_banks();
1779
1780 /*
1781 * Alert userspace if needed. If we logged an MCE, reduce the polling
1782 * interval, otherwise increase the polling interval.
1783 */
1784 if (!mce_gen_pool_empty())
1785 iv = max(iv / 2, (unsigned long) HZ/100);
1786 else
1787 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1788
1789 if (mce_get_storm_mode()) {
1790 __start_timer(t, HZ);
1791 } else if (should_enable_timer(iv)) {
1792 __this_cpu_write(mce_next_interval, iv);
1793 __start_timer(t, iv);
1794 }
1795 }
1796
1797 /*
1798 * When a storm starts on any bank on this CPU, switch to polling
1799 * once per second. When the storm ends, revert to the default
1800 * polling interval.
1801 */
mce_timer_kick(bool storm)1802 void mce_timer_kick(bool storm)
1803 {
1804 struct timer_list *t = this_cpu_ptr(&mce_timer);
1805
1806 mce_set_storm_mode(storm);
1807
1808 if (storm)
1809 __start_timer(t, HZ);
1810 else
1811 __this_cpu_write(mce_next_interval, check_interval * HZ);
1812 }
1813
1814 /* Must not be called in IRQ context where timer_delete_sync() can deadlock */
mce_timer_delete_all(void)1815 static void mce_timer_delete_all(void)
1816 {
1817 int cpu;
1818
1819 for_each_online_cpu(cpu)
1820 timer_delete_sync(&per_cpu(mce_timer, cpu));
1821 }
1822
__mcheck_cpu_mce_banks_init(void)1823 static void __mcheck_cpu_mce_banks_init(void)
1824 {
1825 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1826 u8 n_banks = this_cpu_read(mce_num_banks);
1827 int i;
1828
1829 for (i = 0; i < n_banks; i++) {
1830 struct mce_bank *b = &mce_banks[i];
1831
1832 /*
1833 * Init them all by default.
1834 *
1835 * The required vendor quirks will be applied before
1836 * __mcheck_cpu_init_prepare_banks() does the final bank setup.
1837 */
1838 b->ctl = -1ULL;
1839 b->init = true;
1840 }
1841 }
1842
1843 /*
1844 * Initialize Machine Checks for a CPU.
1845 */
__mcheck_cpu_cap_init(void)1846 static void __mcheck_cpu_cap_init(void)
1847 {
1848 u64 cap;
1849 u8 b;
1850
1851 rdmsrq(MSR_IA32_MCG_CAP, cap);
1852
1853 b = cap & MCG_BANKCNT_MASK;
1854
1855 if (b > MAX_NR_BANKS) {
1856 pr_warn("CPU%d: Using only %u machine check banks out of %u\n",
1857 smp_processor_id(), MAX_NR_BANKS, b);
1858 b = MAX_NR_BANKS;
1859 }
1860
1861 this_cpu_write(mce_num_banks, b);
1862
1863 __mcheck_cpu_mce_banks_init();
1864 }
1865
__mcheck_cpu_init_generic(void)1866 static void __mcheck_cpu_init_generic(void)
1867 {
1868 u64 cap;
1869
1870 rdmsrq(MSR_IA32_MCG_CAP, cap);
1871 if (cap & MCG_CTL_P)
1872 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1873 }
1874
__mcheck_cpu_init_prepare_banks(void)1875 static void __mcheck_cpu_init_prepare_banks(void)
1876 {
1877 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1878 u64 msrval;
1879 int i;
1880
1881 /*
1882 * Log the machine checks left over from the previous reset. Log them
1883 * only, do not start processing them. That will happen in mcheck_late_init()
1884 * when all consumers have been registered on the notifier chain.
1885 */
1886 if (mca_cfg.bootlog) {
1887 mce_banks_t all_banks;
1888
1889 bitmap_fill(all_banks, MAX_NR_BANKS);
1890 machine_check_poll(MCP_UC | MCP_QUEUE_LOG, &all_banks);
1891 }
1892
1893 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1894 struct mce_bank *b = &mce_banks[i];
1895
1896 if (!b->init)
1897 continue;
1898
1899 wrmsrq(mca_msr_reg(i, MCA_CTL), b->ctl);
1900 wrmsrq(mca_msr_reg(i, MCA_STATUS), 0);
1901
1902 rdmsrq(mca_msr_reg(i, MCA_CTL), msrval);
1903 b->init = !!msrval;
1904 }
1905 }
1906
amd_apply_global_quirks(struct cpuinfo_x86 * c)1907 static void amd_apply_global_quirks(struct cpuinfo_x86 *c)
1908 {
1909 if (c->x86 < 0x11 && mca_cfg.bootlog < 0) {
1910 /*
1911 * Lots of broken BIOS around that don't clear them
1912 * by default and leave crap in there. Don't log:
1913 */
1914 mca_cfg.bootlog = 0;
1915 }
1916
1917 /*
1918 * overflow_recov is supported for F15h Models 00h-0fh
1919 * even though we don't have a CPUID bit for it.
1920 */
1921 if (c->x86 == 0x15 && c->x86_model <= 0xf)
1922 mce_flags.overflow_recov = 1;
1923
1924 if (c->x86 >= 0x17 && c->x86 <= 0x1A)
1925 mce_flags.zen_ifu_quirk = 1;
1926 }
1927
intel_apply_global_quirks(struct cpuinfo_x86 * c)1928 static void intel_apply_global_quirks(struct cpuinfo_x86 *c)
1929 {
1930 /* Older CPUs (prior to family 6) don't need quirks. */
1931 if (c->x86_vfm < INTEL_PENTIUM_PRO)
1932 return;
1933
1934 /*
1935 * All newer Intel systems support MCE broadcasting. Enable
1936 * synchronization with a one second timeout.
1937 */
1938 if (c->x86_vfm >= INTEL_CORE_YONAH && mca_cfg.monarch_timeout < 0)
1939 mca_cfg.monarch_timeout = USEC_PER_SEC;
1940
1941 /*
1942 * There are also broken BIOSes on some Pentium M and
1943 * earlier systems:
1944 */
1945 if (c->x86_vfm < INTEL_CORE_YONAH && mca_cfg.bootlog < 0)
1946 mca_cfg.bootlog = 0;
1947
1948 if (c->x86_vfm == INTEL_SANDYBRIDGE_X)
1949 mce_flags.snb_ifu_quirk = 1;
1950
1951 /*
1952 * Skylake, Cascacde Lake and Cooper Lake require a quirk on
1953 * rep movs.
1954 */
1955 if (c->x86_vfm == INTEL_SKYLAKE_X)
1956 mce_flags.skx_repmov_quirk = 1;
1957 }
1958
zhaoxin_apply_global_quirks(struct cpuinfo_x86 * c)1959 static void zhaoxin_apply_global_quirks(struct cpuinfo_x86 *c)
1960 {
1961 /*
1962 * All newer Zhaoxin CPUs support MCE broadcasting. Enable
1963 * synchronization with a one second timeout.
1964 */
1965 if (c->x86 > 6 || (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1966 if (mca_cfg.monarch_timeout < 0)
1967 mca_cfg.monarch_timeout = USEC_PER_SEC;
1968 }
1969 }
1970
__mcheck_cpu_ancient_init(struct cpuinfo_x86 * c)1971 static bool __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1972 {
1973 if (c->x86 != 5)
1974 return false;
1975
1976 switch (c->x86_vendor) {
1977 case X86_VENDOR_INTEL:
1978 intel_p5_mcheck_init(c);
1979 mce_flags.p5 = 1;
1980 return true;
1981 case X86_VENDOR_CENTAUR:
1982 winchip_mcheck_init(c);
1983 mce_flags.winchip = 1;
1984 return true;
1985 default:
1986 return false;
1987 }
1988
1989 return false;
1990 }
1991
mce_centaur_feature_init(struct cpuinfo_x86 * c)1992 static void mce_centaur_feature_init(struct cpuinfo_x86 *c)
1993 {
1994 struct mca_config *cfg = &mca_cfg;
1995
1996 /*
1997 * All newer Centaur CPUs support MCE broadcasting. Enable
1998 * synchronization with a one second timeout.
1999 */
2000 if ((c->x86 == 6 && c->x86_model == 0xf && c->x86_stepping >= 0xe) ||
2001 c->x86 > 6) {
2002 if (cfg->monarch_timeout < 0)
2003 cfg->monarch_timeout = USEC_PER_SEC;
2004 }
2005 }
2006
mce_zhaoxin_feature_init(struct cpuinfo_x86 * c)2007 static void mce_zhaoxin_feature_init(struct cpuinfo_x86 *c)
2008 {
2009 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2010
2011 /*
2012 * These CPUs have MCA bank 8 which reports only one error type called
2013 * SVAD (System View Address Decoder). The reporting of that error is
2014 * controlled by IA32_MC8.CTL.0.
2015 *
2016 * If enabled, prefetching on these CPUs will cause SVAD MCE when
2017 * virtual machines start and result in a system panic. Always disable
2018 * bank 8 SVAD error by default.
2019 */
2020 if ((c->x86 == 7 && c->x86_model == 0x1b) ||
2021 (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
2022 if (this_cpu_read(mce_num_banks) > 8)
2023 mce_banks[8].ctl = 0;
2024 }
2025
2026 intel_init_cmci();
2027 intel_init_lmce();
2028 }
2029
mce_zhaoxin_feature_clear(struct cpuinfo_x86 * c)2030 static void mce_zhaoxin_feature_clear(struct cpuinfo_x86 *c)
2031 {
2032 intel_clear_lmce();
2033 }
2034
__mcheck_cpu_init_vendor(struct cpuinfo_x86 * c)2035 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
2036 {
2037 switch (c->x86_vendor) {
2038 case X86_VENDOR_INTEL:
2039 mce_intel_feature_init(c);
2040 break;
2041
2042 case X86_VENDOR_AMD:
2043 case X86_VENDOR_HYGON:
2044 mce_amd_feature_init(c);
2045 break;
2046
2047 case X86_VENDOR_CENTAUR:
2048 mce_centaur_feature_init(c);
2049 break;
2050
2051 case X86_VENDOR_ZHAOXIN:
2052 mce_zhaoxin_feature_init(c);
2053 break;
2054
2055 default:
2056 break;
2057 }
2058 }
2059
__mcheck_cpu_clear_vendor(struct cpuinfo_x86 * c)2060 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
2061 {
2062 switch (c->x86_vendor) {
2063 case X86_VENDOR_INTEL:
2064 mce_intel_feature_clear(c);
2065 break;
2066
2067 case X86_VENDOR_ZHAOXIN:
2068 mce_zhaoxin_feature_clear(c);
2069 break;
2070
2071 default:
2072 break;
2073 }
2074 }
2075
mce_start_timer(struct timer_list * t)2076 static void mce_start_timer(struct timer_list *t)
2077 {
2078 unsigned long iv = check_interval * HZ;
2079
2080 if (should_enable_timer(iv)) {
2081 this_cpu_write(mce_next_interval, iv);
2082 __start_timer(t, iv);
2083 }
2084 }
2085
__mcheck_cpu_setup_timer(void)2086 static void __mcheck_cpu_setup_timer(void)
2087 {
2088 struct timer_list *t = this_cpu_ptr(&mce_timer);
2089
2090 timer_setup(t, mce_timer_fn, TIMER_PINNED);
2091 }
2092
__mcheck_cpu_init_timer(void)2093 static void __mcheck_cpu_init_timer(void)
2094 {
2095 struct timer_list *t = this_cpu_ptr(&mce_timer);
2096
2097 timer_setup(t, mce_timer_fn, TIMER_PINNED);
2098 mce_start_timer(t);
2099 }
2100
filter_mce(struct mce * m)2101 bool filter_mce(struct mce *m)
2102 {
2103 if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
2104 return amd_filter_mce(m);
2105 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2106 return intel_filter_mce(m);
2107
2108 return false;
2109 }
2110
exc_machine_check_kernel(struct pt_regs * regs)2111 static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)
2112 {
2113 irqentry_state_t irq_state;
2114
2115 WARN_ON_ONCE(user_mode(regs));
2116
2117 /*
2118 * Only required when from kernel mode. See
2119 * mce_check_crashing_cpu() for details.
2120 */
2121 if (mca_cfg.initialized && mce_check_crashing_cpu())
2122 return;
2123
2124 irq_state = irqentry_nmi_enter(regs);
2125
2126 do_machine_check(regs);
2127
2128 irqentry_nmi_exit(regs, irq_state);
2129 }
2130
exc_machine_check_user(struct pt_regs * regs)2131 static __always_inline void exc_machine_check_user(struct pt_regs *regs)
2132 {
2133 irqentry_enter_from_user_mode(regs);
2134
2135 do_machine_check(regs);
2136
2137 irqentry_exit_to_user_mode(regs);
2138 }
2139
2140 #ifdef CONFIG_X86_64
2141 /* MCE hit kernel mode */
DEFINE_IDTENTRY_MCE(exc_machine_check)2142 DEFINE_IDTENTRY_MCE(exc_machine_check)
2143 {
2144 unsigned long dr7;
2145
2146 dr7 = local_db_save();
2147 exc_machine_check_kernel(regs);
2148 local_db_restore(dr7);
2149 }
2150
2151 /* The user mode variant. */
DEFINE_IDTENTRY_MCE_USER(exc_machine_check)2152 DEFINE_IDTENTRY_MCE_USER(exc_machine_check)
2153 {
2154 unsigned long dr7;
2155
2156 dr7 = local_db_save();
2157 exc_machine_check_user(regs);
2158 local_db_restore(dr7);
2159 }
2160
2161 #ifdef CONFIG_X86_FRED
2162 /*
2163 * When occurred on different ring level, i.e., from user or kernel
2164 * context, #MCE needs to be handled on different stack: User #MCE
2165 * on current task stack, while kernel #MCE on a dedicated stack.
2166 *
2167 * This is exactly how FRED event delivery invokes an exception
2168 * handler: ring 3 event on level 0 stack, i.e., current task stack;
2169 * ring 0 event on the #MCE dedicated stack specified in the
2170 * IA32_FRED_STKLVLS MSR. So unlike IDT, the FRED machine check entry
2171 * stub doesn't do stack switch.
2172 */
DEFINE_FREDENTRY_MCE(exc_machine_check)2173 DEFINE_FREDENTRY_MCE(exc_machine_check)
2174 {
2175 unsigned long dr7;
2176
2177 dr7 = local_db_save();
2178 if (user_mode(regs))
2179 exc_machine_check_user(regs);
2180 else
2181 exc_machine_check_kernel(regs);
2182 local_db_restore(dr7);
2183 }
2184 #endif
2185 #else
2186 /* 32bit unified entry point */
DEFINE_IDTENTRY_RAW(exc_machine_check)2187 DEFINE_IDTENTRY_RAW(exc_machine_check)
2188 {
2189 unsigned long dr7;
2190
2191 dr7 = local_db_save();
2192 if (user_mode(regs))
2193 exc_machine_check_user(regs);
2194 else
2195 exc_machine_check_kernel(regs);
2196 local_db_restore(dr7);
2197 }
2198 #endif
2199
mca_bsp_init(struct cpuinfo_x86 * c)2200 void mca_bsp_init(struct cpuinfo_x86 *c)
2201 {
2202 u64 cap;
2203
2204 if (!mce_available(c))
2205 return;
2206
2207 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
2208 mca_cfg.disabled = 1;
2209 pr_info("unknown CPU type - not enabling MCE support\n");
2210 return;
2211 }
2212
2213 mce_flags.overflow_recov = cpu_feature_enabled(X86_FEATURE_OVERFLOW_RECOV);
2214 mce_flags.succor = cpu_feature_enabled(X86_FEATURE_SUCCOR);
2215 mce_flags.smca = cpu_feature_enabled(X86_FEATURE_SMCA);
2216
2217 if (mce_flags.smca)
2218 smca_bsp_init();
2219
2220 rdmsrq(MSR_IA32_MCG_CAP, cap);
2221
2222 /* Use accurate RIP reporting if available. */
2223 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
2224 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
2225
2226 if (cap & MCG_SER_P)
2227 mca_cfg.ser = 1;
2228
2229 switch (c->x86_vendor) {
2230 case X86_VENDOR_AMD:
2231 amd_apply_global_quirks(c);
2232 break;
2233 case X86_VENDOR_INTEL:
2234 intel_apply_global_quirks(c);
2235 break;
2236 case X86_VENDOR_ZHAOXIN:
2237 zhaoxin_apply_global_quirks(c);
2238 break;
2239 }
2240
2241 if (mca_cfg.monarch_timeout < 0)
2242 mca_cfg.monarch_timeout = 0;
2243 if (mca_cfg.bootlog != 0)
2244 mca_cfg.panic_timeout = 30;
2245 }
2246
2247 /*
2248 * Called for each booted CPU to set up machine checks.
2249 * Must be called with preempt off:
2250 */
mcheck_cpu_init(struct cpuinfo_x86 * c)2251 void mcheck_cpu_init(struct cpuinfo_x86 *c)
2252 {
2253 if (mca_cfg.disabled)
2254 return;
2255
2256 if (__mcheck_cpu_ancient_init(c))
2257 return;
2258
2259 if (!mce_available(c))
2260 return;
2261
2262 __mcheck_cpu_cap_init();
2263
2264 if (!mce_gen_pool_init()) {
2265 mca_cfg.disabled = 1;
2266 pr_emerg("Couldn't allocate MCE records pool!\n");
2267 return;
2268 }
2269
2270 mca_cfg.initialized = 1;
2271
2272 __mcheck_cpu_init_generic();
2273 __mcheck_cpu_init_vendor(c);
2274 __mcheck_cpu_init_prepare_banks();
2275 __mcheck_cpu_setup_timer();
2276 cr4_set_bits(X86_CR4_MCE);
2277 }
2278
2279 /*
2280 * Called for each booted CPU to clear some machine checks opt-ins
2281 */
mcheck_cpu_clear(struct cpuinfo_x86 * c)2282 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
2283 {
2284 if (mca_cfg.disabled)
2285 return;
2286
2287 if (!mce_available(c))
2288 return;
2289
2290 /*
2291 * Possibly to clear general settings generic to x86
2292 * __mcheck_cpu_clear_generic(c);
2293 */
2294 __mcheck_cpu_clear_vendor(c);
2295
2296 }
2297
__mce_disable_bank(void * arg)2298 static void __mce_disable_bank(void *arg)
2299 {
2300 int bank = *((int *)arg);
2301 __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2302 cmci_disable_bank(bank);
2303 }
2304
mce_disable_bank(int bank)2305 void mce_disable_bank(int bank)
2306 {
2307 if (bank >= this_cpu_read(mce_num_banks)) {
2308 pr_warn(FW_BUG
2309 "Ignoring request to disable invalid MCA bank %d.\n",
2310 bank);
2311 return;
2312 }
2313 set_bit(bank, mce_banks_ce_disabled);
2314 on_each_cpu(__mce_disable_bank, &bank, 1);
2315 }
2316
2317 /*
2318 * mce=off Disables machine check
2319 * mce=no_cmci Disables CMCI
2320 * mce=no_lmce Disables LMCE
2321 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2322 * mce=print_all Print all machine check logs to console
2323 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2324 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2325 * monarchtimeout is how long to wait for other CPUs on machine
2326 * check, or 0 to not wait
2327 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD Fam10h
2328 and older.
2329 * mce=nobootlog Don't log MCEs from before booting.
2330 * mce=bios_cmci_threshold Don't program the CMCI threshold
2331 * mce=recovery force enable copy_mc_fragile()
2332 */
mcheck_enable(char * str)2333 static int __init mcheck_enable(char *str)
2334 {
2335 struct mca_config *cfg = &mca_cfg;
2336
2337 if (*str == 0) {
2338 enable_p5_mce();
2339 return 1;
2340 }
2341 if (*str == '=')
2342 str++;
2343 if (!strcmp(str, "off"))
2344 cfg->disabled = 1;
2345 else if (!strcmp(str, "no_cmci"))
2346 cfg->cmci_disabled = true;
2347 else if (!strcmp(str, "no_lmce"))
2348 cfg->lmce_disabled = 1;
2349 else if (!strcmp(str, "dont_log_ce"))
2350 cfg->dont_log_ce = true;
2351 else if (!strcmp(str, "print_all"))
2352 cfg->print_all = true;
2353 else if (!strcmp(str, "ignore_ce"))
2354 cfg->ignore_ce = true;
2355 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2356 cfg->bootlog = (str[0] == 'b');
2357 else if (!strcmp(str, "bios_cmci_threshold"))
2358 cfg->bios_cmci_threshold = 1;
2359 else if (!strcmp(str, "recovery"))
2360 cfg->recovery = 1;
2361 else if (isdigit(str[0]))
2362 get_option(&str, &(cfg->monarch_timeout));
2363 else {
2364 pr_info("mce argument %s ignored. Please use /sys\n", str);
2365 return 0;
2366 }
2367 return 1;
2368 }
2369 __setup("mce", mcheck_enable);
2370
mcheck_init(void)2371 int __init mcheck_init(void)
2372 {
2373 mce_register_decode_chain(&early_nb);
2374 mce_register_decode_chain(&mce_uc_nb);
2375 mce_register_decode_chain(&mce_default_nb);
2376
2377 INIT_WORK(&mce_work, mce_gen_pool_process);
2378 init_irq_work(&mce_irq_work, mce_irq_work_cb);
2379
2380 return 0;
2381 }
2382
2383 /*
2384 * mce_syscore: PM support
2385 */
2386
2387 /*
2388 * Disable machine checks on suspend and shutdown. We can't really handle
2389 * them later.
2390 */
mce_disable_error_reporting(void)2391 static void mce_disable_error_reporting(void)
2392 {
2393 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2394 int i;
2395
2396 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2397 struct mce_bank *b = &mce_banks[i];
2398
2399 if (b->init)
2400 wrmsrq(mca_msr_reg(i, MCA_CTL), 0);
2401 }
2402 return;
2403 }
2404
vendor_disable_error_reporting(void)2405 static void vendor_disable_error_reporting(void)
2406 {
2407 /*
2408 * Don't clear on Intel or AMD or Hygon or Zhaoxin CPUs. Some of these
2409 * MSRs are socket-wide. Disabling them for just a single offlined CPU
2410 * is bad, since it will inhibit reporting for all shared resources on
2411 * the socket like the last level cache (LLC), the integrated memory
2412 * controller (iMC), etc.
2413 */
2414 if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL ||
2415 boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ||
2416 boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
2417 boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN)
2418 return;
2419
2420 mce_disable_error_reporting();
2421 }
2422
mce_syscore_suspend(void * data)2423 static int mce_syscore_suspend(void *data)
2424 {
2425 vendor_disable_error_reporting();
2426 return 0;
2427 }
2428
mce_syscore_shutdown(void * data)2429 static void mce_syscore_shutdown(void *data)
2430 {
2431 vendor_disable_error_reporting();
2432 }
2433
2434 /*
2435 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2436 * Only one CPU is active at this time, the others get re-added later using
2437 * CPU hotplug:
2438 */
mce_syscore_resume(void * data)2439 static void mce_syscore_resume(void *data)
2440 {
2441 __mcheck_cpu_init_generic();
2442 __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2443 __mcheck_cpu_init_prepare_banks();
2444 cr4_set_bits(X86_CR4_MCE);
2445 }
2446
2447 static const struct syscore_ops mce_syscore_ops = {
2448 .suspend = mce_syscore_suspend,
2449 .shutdown = mce_syscore_shutdown,
2450 .resume = mce_syscore_resume,
2451 };
2452
2453 static struct syscore mce_syscore = {
2454 .ops = &mce_syscore_ops,
2455 };
2456
2457 /*
2458 * mce_device: Sysfs support
2459 */
2460
mce_cpu_restart(void * data)2461 static void mce_cpu_restart(void *data)
2462 {
2463 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2464 return;
2465 __mcheck_cpu_init_generic();
2466 __mcheck_cpu_init_prepare_banks();
2467 __mcheck_cpu_init_timer();
2468 cr4_set_bits(X86_CR4_MCE);
2469 }
2470
2471 /* Reinit MCEs after user configuration changes */
mce_restart(void)2472 static void mce_restart(void)
2473 {
2474 mce_timer_delete_all();
2475 on_each_cpu(mce_cpu_restart, NULL, 1);
2476 mce_schedule_work();
2477 }
2478
2479 /* Toggle features for corrected errors */
mce_disable_cmci(void * data)2480 static void mce_disable_cmci(void *data)
2481 {
2482 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2483 return;
2484 cmci_clear();
2485 }
2486
mce_enable_ce(void * all)2487 static void mce_enable_ce(void *all)
2488 {
2489 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2490 return;
2491 cmci_reenable();
2492 cmci_recheck();
2493 if (all)
2494 __mcheck_cpu_init_timer();
2495 }
2496
2497 static const struct bus_type mce_subsys = {
2498 .name = "machinecheck",
2499 .dev_name = "machinecheck",
2500 };
2501
2502 DEFINE_PER_CPU(struct device *, mce_device);
2503
attr_to_bank(struct device_attribute * attr)2504 static inline struct mce_bank_dev *attr_to_bank(struct device_attribute *attr)
2505 {
2506 return container_of(attr, struct mce_bank_dev, attr);
2507 }
2508
show_bank(struct device * s,struct device_attribute * attr,char * buf)2509 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2510 char *buf)
2511 {
2512 u8 bank = attr_to_bank(attr)->bank;
2513 struct mce_bank *b;
2514
2515 if (bank >= per_cpu(mce_num_banks, s->id))
2516 return -EINVAL;
2517
2518 b = &per_cpu(mce_banks_array, s->id)[bank];
2519
2520 if (!b->init)
2521 return -ENODEV;
2522
2523 return sprintf(buf, "%llx\n", b->ctl);
2524 }
2525
set_bank(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2526 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2527 const char *buf, size_t size)
2528 {
2529 u8 bank = attr_to_bank(attr)->bank;
2530 struct mce_bank *b;
2531 u64 new;
2532
2533 if (kstrtou64(buf, 0, &new) < 0)
2534 return -EINVAL;
2535
2536 if (bank >= per_cpu(mce_num_banks, s->id))
2537 return -EINVAL;
2538
2539 b = &per_cpu(mce_banks_array, s->id)[bank];
2540 if (!b->init)
2541 return -ENODEV;
2542
2543 b->ctl = new;
2544
2545 mutex_lock(&mce_sysfs_mutex);
2546 mce_restart();
2547 mutex_unlock(&mce_sysfs_mutex);
2548
2549 return size;
2550 }
2551
set_ignore_ce(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2552 static ssize_t set_ignore_ce(struct device *s,
2553 struct device_attribute *attr,
2554 const char *buf, size_t size)
2555 {
2556 u64 new;
2557
2558 if (kstrtou64(buf, 0, &new) < 0)
2559 return -EINVAL;
2560
2561 mutex_lock(&mce_sysfs_mutex);
2562 if (mca_cfg.ignore_ce ^ !!new) {
2563 if (new) {
2564 /* disable ce features */
2565 mce_timer_delete_all();
2566 on_each_cpu(mce_disable_cmci, NULL, 1);
2567 mca_cfg.ignore_ce = true;
2568 } else {
2569 /* enable ce features */
2570 mca_cfg.ignore_ce = false;
2571 on_each_cpu(mce_enable_ce, (void *)1, 1);
2572 }
2573 }
2574 mutex_unlock(&mce_sysfs_mutex);
2575
2576 return size;
2577 }
2578
set_cmci_disabled(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2579 static ssize_t set_cmci_disabled(struct device *s,
2580 struct device_attribute *attr,
2581 const char *buf, size_t size)
2582 {
2583 u64 new;
2584
2585 if (kstrtou64(buf, 0, &new) < 0)
2586 return -EINVAL;
2587
2588 mutex_lock(&mce_sysfs_mutex);
2589 if (mca_cfg.cmci_disabled ^ !!new) {
2590 if (new) {
2591 /* disable cmci */
2592 on_each_cpu(mce_disable_cmci, NULL, 1);
2593 mca_cfg.cmci_disabled = true;
2594 } else {
2595 /* enable cmci */
2596 mca_cfg.cmci_disabled = false;
2597 on_each_cpu(mce_enable_ce, NULL, 1);
2598 }
2599 }
2600 mutex_unlock(&mce_sysfs_mutex);
2601
2602 return size;
2603 }
2604
store_int_with_restart(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2605 static ssize_t store_int_with_restart(struct device *s,
2606 struct device_attribute *attr,
2607 const char *buf, size_t size)
2608 {
2609 unsigned long old_check_interval = check_interval;
2610 ssize_t ret = device_store_ulong(s, attr, buf, size);
2611
2612 if (check_interval == old_check_interval)
2613 return ret;
2614
2615 mutex_lock(&mce_sysfs_mutex);
2616 mce_restart();
2617 mutex_unlock(&mce_sysfs_mutex);
2618
2619 return ret;
2620 }
2621
2622 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2623 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2624 static DEVICE_BOOL_ATTR(print_all, 0644, mca_cfg.print_all);
2625
2626 static struct dev_ext_attribute dev_attr_check_interval = {
2627 __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2628 &check_interval
2629 };
2630
2631 static struct dev_ext_attribute dev_attr_ignore_ce = {
2632 __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2633 &mca_cfg.ignore_ce
2634 };
2635
2636 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2637 __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2638 &mca_cfg.cmci_disabled
2639 };
2640
2641 static struct device_attribute *mce_device_attrs[] = {
2642 &dev_attr_check_interval.attr,
2643 #ifdef CONFIG_X86_MCELOG_LEGACY
2644 &dev_attr_trigger,
2645 #endif
2646 &dev_attr_monarch_timeout.attr,
2647 &dev_attr_dont_log_ce.attr,
2648 &dev_attr_print_all.attr,
2649 &dev_attr_ignore_ce.attr,
2650 &dev_attr_cmci_disabled.attr,
2651 NULL
2652 };
2653
2654 static cpumask_var_t mce_device_initialized;
2655
mce_device_release(struct device * dev)2656 static void mce_device_release(struct device *dev)
2657 {
2658 kfree(dev);
2659 }
2660
2661 /* Per CPU device init. All of the CPUs still share the same bank device: */
mce_device_create(unsigned int cpu)2662 static int mce_device_create(unsigned int cpu)
2663 {
2664 struct device *dev;
2665 int err;
2666 int i, j;
2667
2668 dev = per_cpu(mce_device, cpu);
2669 if (dev)
2670 return 0;
2671
2672 dev = kzalloc_obj(*dev);
2673 if (!dev)
2674 return -ENOMEM;
2675 dev->id = cpu;
2676 dev->bus = &mce_subsys;
2677 dev->release = &mce_device_release;
2678
2679 err = device_register(dev);
2680 if (err) {
2681 put_device(dev);
2682 return err;
2683 }
2684
2685 for (i = 0; mce_device_attrs[i]; i++) {
2686 err = device_create_file(dev, mce_device_attrs[i]);
2687 if (err)
2688 goto error;
2689 }
2690 for (j = 0; j < per_cpu(mce_num_banks, cpu); j++) {
2691 err = device_create_file(dev, &mce_bank_devs[j].attr);
2692 if (err)
2693 goto error2;
2694 }
2695 cpumask_set_cpu(cpu, mce_device_initialized);
2696 per_cpu(mce_device, cpu) = dev;
2697
2698 return 0;
2699 error2:
2700 while (--j >= 0)
2701 device_remove_file(dev, &mce_bank_devs[j].attr);
2702 error:
2703 while (--i >= 0)
2704 device_remove_file(dev, mce_device_attrs[i]);
2705
2706 device_unregister(dev);
2707
2708 return err;
2709 }
2710
mce_device_remove(unsigned int cpu)2711 static void mce_device_remove(unsigned int cpu)
2712 {
2713 struct device *dev = per_cpu(mce_device, cpu);
2714 int i;
2715
2716 if (!cpumask_test_cpu(cpu, mce_device_initialized))
2717 return;
2718
2719 for (i = 0; mce_device_attrs[i]; i++)
2720 device_remove_file(dev, mce_device_attrs[i]);
2721
2722 for (i = 0; i < per_cpu(mce_num_banks, cpu); i++)
2723 device_remove_file(dev, &mce_bank_devs[i].attr);
2724
2725 device_unregister(dev);
2726 cpumask_clear_cpu(cpu, mce_device_initialized);
2727 per_cpu(mce_device, cpu) = NULL;
2728 }
2729
2730 /* Make sure there are no machine checks on offlined CPUs. */
mce_disable_cpu(void)2731 static void mce_disable_cpu(void)
2732 {
2733 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2734 return;
2735
2736 if (!cpuhp_tasks_frozen)
2737 cmci_clear();
2738
2739 vendor_disable_error_reporting();
2740 }
2741
mce_reenable_cpu(void)2742 static void mce_reenable_cpu(void)
2743 {
2744 struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2745 int i;
2746
2747 if (!mce_available(raw_cpu_ptr(&cpu_info)))
2748 return;
2749
2750 if (!cpuhp_tasks_frozen)
2751 cmci_reenable();
2752 for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2753 struct mce_bank *b = &mce_banks[i];
2754
2755 if (b->init)
2756 wrmsrq(mca_msr_reg(i, MCA_CTL), b->ctl);
2757 }
2758 }
2759
mce_cpu_dead(unsigned int cpu)2760 static int mce_cpu_dead(unsigned int cpu)
2761 {
2762 /* intentionally ignoring frozen here */
2763 if (!cpuhp_tasks_frozen)
2764 cmci_rediscover();
2765 return 0;
2766 }
2767
mce_cpu_online(unsigned int cpu)2768 static int mce_cpu_online(unsigned int cpu)
2769 {
2770 struct timer_list *t = this_cpu_ptr(&mce_timer);
2771
2772 mce_device_create(cpu);
2773 mce_threshold_create_device(cpu);
2774 mce_reenable_cpu();
2775 mce_start_timer(t);
2776 return 0;
2777 }
2778
mce_cpu_pre_down(unsigned int cpu)2779 static int mce_cpu_pre_down(unsigned int cpu)
2780 {
2781 struct timer_list *t = this_cpu_ptr(&mce_timer);
2782
2783 mce_disable_cpu();
2784 timer_delete_sync(t);
2785 mce_threshold_remove_device(cpu);
2786 mce_device_remove(cpu);
2787 return 0;
2788 }
2789
mce_init_banks(void)2790 static __init void mce_init_banks(void)
2791 {
2792 int i;
2793
2794 for (i = 0; i < MAX_NR_BANKS; i++) {
2795 struct mce_bank_dev *b = &mce_bank_devs[i];
2796 struct device_attribute *a = &b->attr;
2797
2798 b->bank = i;
2799
2800 sysfs_attr_init(&a->attr);
2801 a->attr.name = b->attrname;
2802 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2803
2804 a->attr.mode = 0644;
2805 a->show = show_bank;
2806 a->store = set_bank;
2807 }
2808 }
2809
2810 /*
2811 * When running on XEN, this initcall is ordered against the XEN mcelog
2812 * initcall:
2813 *
2814 * device_initcall(xen_late_init_mcelog);
2815 * device_initcall_sync(mcheck_init_device);
2816 */
mcheck_init_device(void)2817 static __init int mcheck_init_device(void)
2818 {
2819 int err;
2820
2821 /*
2822 * Check if we have a spare virtual bit. This will only become
2823 * a problem if/when we move beyond 5-level page tables.
2824 */
2825 MAYBE_BUILD_BUG_ON(__VIRTUAL_MASK_SHIFT >= 63);
2826
2827 if (!mce_available(&boot_cpu_data)) {
2828 err = -EIO;
2829 goto err_out;
2830 }
2831
2832 if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2833 err = -ENOMEM;
2834 goto err_out;
2835 }
2836
2837 mce_init_banks();
2838
2839 err = subsys_system_register(&mce_subsys, NULL);
2840 if (err)
2841 goto err_out_mem;
2842
2843 err = cpuhp_setup_state(CPUHP_X86_MCE_DEAD, "x86/mce:dead", NULL,
2844 mce_cpu_dead);
2845 if (err)
2846 goto err_out_mem;
2847
2848 /*
2849 * Invokes mce_cpu_online() on all CPUs which are online when
2850 * the state is installed.
2851 */
2852 err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/mce:online",
2853 mce_cpu_online, mce_cpu_pre_down);
2854 if (err < 0)
2855 goto err_out_online;
2856
2857 register_syscore(&mce_syscore);
2858
2859 return 0;
2860
2861 err_out_online:
2862 cpuhp_remove_state(CPUHP_X86_MCE_DEAD);
2863
2864 err_out_mem:
2865 free_cpumask_var(mce_device_initialized);
2866
2867 err_out:
2868 pr_err("Unable to init MCE device (rc: %d)\n", err);
2869
2870 return err;
2871 }
2872 device_initcall_sync(mcheck_init_device);
2873
2874 /*
2875 * Old style boot options parsing. Only for compatibility.
2876 */
mcheck_disable(char * str)2877 static int __init mcheck_disable(char *str)
2878 {
2879 mca_cfg.disabled = 1;
2880 return 1;
2881 }
2882 __setup("nomce", mcheck_disable);
2883
2884 #ifdef CONFIG_DEBUG_FS
mce_get_debugfs_dir(void)2885 struct dentry *mce_get_debugfs_dir(void)
2886 {
2887 static struct dentry *dmce;
2888
2889 if (!dmce)
2890 dmce = debugfs_create_dir("mce", NULL);
2891
2892 return dmce;
2893 }
2894
mce_reset(void)2895 static void mce_reset(void)
2896 {
2897 atomic_set(&mce_fake_panicked, 0);
2898 atomic_set(&mce_executing, 0);
2899 atomic_set(&mce_callin, 0);
2900 atomic_set(&global_nwo, 0);
2901 cpumask_setall(&mce_missing_cpus);
2902 }
2903
fake_panic_get(void * data,u64 * val)2904 static int fake_panic_get(void *data, u64 *val)
2905 {
2906 *val = fake_panic;
2907 return 0;
2908 }
2909
fake_panic_set(void * data,u64 val)2910 static int fake_panic_set(void *data, u64 val)
2911 {
2912 mce_reset();
2913 fake_panic = val;
2914 return 0;
2915 }
2916
2917 DEFINE_DEBUGFS_ATTRIBUTE(fake_panic_fops, fake_panic_get, fake_panic_set,
2918 "%llu\n");
2919
mcheck_debugfs_init(void)2920 static void __init mcheck_debugfs_init(void)
2921 {
2922 struct dentry *dmce;
2923
2924 dmce = mce_get_debugfs_dir();
2925 debugfs_create_file_unsafe("fake_panic", 0444, dmce, NULL,
2926 &fake_panic_fops);
2927 }
2928 #else
mcheck_debugfs_init(void)2929 static void __init mcheck_debugfs_init(void) { }
2930 #endif
2931
mcheck_late_init(void)2932 static int __init mcheck_late_init(void)
2933 {
2934 if (mca_cfg.recovery)
2935 enable_copy_mc_fragile();
2936
2937 mcheck_debugfs_init();
2938
2939 /*
2940 * Flush out everything that has been logged during early boot, now that
2941 * everything has been initialized (workqueues, decoders, ...).
2942 */
2943 mce_schedule_work();
2944
2945 return 0;
2946 }
2947 late_initcall(mcheck_late_init);
2948