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