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