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