• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
should_enable_timer(unsigned long iv)1691 static bool should_enable_timer(unsigned long iv)
1692 {
1693 	return !mca_cfg.ignore_ce && iv;
1694 }
1695 
mce_timer_fn(struct timer_list * t)1696 static void mce_timer_fn(struct timer_list *t)
1697 {
1698 	struct timer_list *cpu_t = this_cpu_ptr(&mce_timer);
1699 	unsigned long iv;
1700 
1701 	WARN_ON(cpu_t != t);
1702 
1703 	iv = __this_cpu_read(mce_next_interval);
1704 
1705 	if (mce_available(this_cpu_ptr(&cpu_info)))
1706 		mc_poll_banks();
1707 
1708 	/*
1709 	 * Alert userspace if needed. If we logged an MCE, reduce the polling
1710 	 * interval, otherwise increase the polling interval.
1711 	 */
1712 	if (mce_notify_irq())
1713 		iv = max(iv / 2, (unsigned long) HZ/100);
1714 	else
1715 		iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1716 
1717 	if (mce_get_storm_mode()) {
1718 		__start_timer(t, HZ);
1719 	} else if (should_enable_timer(iv)) {
1720 		__this_cpu_write(mce_next_interval, iv);
1721 		__start_timer(t, iv);
1722 	}
1723 }
1724 
1725 /*
1726  * When a storm starts on any bank on this CPU, switch to polling
1727  * once per second. When the storm ends, revert to the default
1728  * polling interval.
1729  */
mce_timer_kick(bool storm)1730 void mce_timer_kick(bool storm)
1731 {
1732 	struct timer_list *t = this_cpu_ptr(&mce_timer);
1733 
1734 	mce_set_storm_mode(storm);
1735 
1736 	if (storm)
1737 		__start_timer(t, HZ);
1738 	else
1739 		__this_cpu_write(mce_next_interval, check_interval * HZ);
1740 }
1741 
1742 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
mce_timer_delete_all(void)1743 static void mce_timer_delete_all(void)
1744 {
1745 	int cpu;
1746 
1747 	for_each_online_cpu(cpu)
1748 		del_timer_sync(&per_cpu(mce_timer, cpu));
1749 }
1750 
1751 /*
1752  * Notify the user(s) about new machine check events.
1753  * Can be called from interrupt context, but not from machine check/NMI
1754  * context.
1755  */
mce_notify_irq(void)1756 int mce_notify_irq(void)
1757 {
1758 	/* Not more than two messages every minute */
1759 	static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1760 
1761 	if (test_and_clear_bit(0, &mce_need_notify)) {
1762 		mce_work_trigger();
1763 
1764 		if (__ratelimit(&ratelimit))
1765 			pr_info(HW_ERR "Machine check events logged\n");
1766 
1767 		return 1;
1768 	}
1769 	return 0;
1770 }
1771 EXPORT_SYMBOL_GPL(mce_notify_irq);
1772 
__mcheck_cpu_mce_banks_init(void)1773 static void __mcheck_cpu_mce_banks_init(void)
1774 {
1775 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1776 	u8 n_banks = this_cpu_read(mce_num_banks);
1777 	int i;
1778 
1779 	for (i = 0; i < n_banks; i++) {
1780 		struct mce_bank *b = &mce_banks[i];
1781 
1782 		/*
1783 		 * Init them all, __mcheck_cpu_apply_quirks() is going to apply
1784 		 * the required vendor quirks before
1785 		 * __mcheck_cpu_init_clear_banks() does the final bank setup.
1786 		 */
1787 		b->ctl = -1ULL;
1788 		b->init = true;
1789 	}
1790 }
1791 
1792 /*
1793  * Initialize Machine Checks for a CPU.
1794  */
__mcheck_cpu_cap_init(void)1795 static void __mcheck_cpu_cap_init(void)
1796 {
1797 	u64 cap;
1798 	u8 b;
1799 
1800 	rdmsrl(MSR_IA32_MCG_CAP, cap);
1801 
1802 	b = cap & MCG_BANKCNT_MASK;
1803 
1804 	if (b > MAX_NR_BANKS) {
1805 		pr_warn("CPU%d: Using only %u machine check banks out of %u\n",
1806 			smp_processor_id(), MAX_NR_BANKS, b);
1807 		b = MAX_NR_BANKS;
1808 	}
1809 
1810 	this_cpu_write(mce_num_banks, b);
1811 
1812 	__mcheck_cpu_mce_banks_init();
1813 
1814 	/* Use accurate RIP reporting if available. */
1815 	if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1816 		mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1817 
1818 	if (cap & MCG_SER_P)
1819 		mca_cfg.ser = 1;
1820 }
1821 
__mcheck_cpu_init_generic(void)1822 static void __mcheck_cpu_init_generic(void)
1823 {
1824 	enum mcp_flags m_fl = 0;
1825 	mce_banks_t all_banks;
1826 	u64 cap;
1827 
1828 	if (!mca_cfg.bootlog)
1829 		m_fl = MCP_DONTLOG;
1830 
1831 	/*
1832 	 * Log the machine checks left over from the previous reset. Log them
1833 	 * only, do not start processing them. That will happen in mcheck_late_init()
1834 	 * when all consumers have been registered on the notifier chain.
1835 	 */
1836 	bitmap_fill(all_banks, MAX_NR_BANKS);
1837 	machine_check_poll(MCP_UC | MCP_QUEUE_LOG | m_fl, &all_banks);
1838 
1839 	cr4_set_bits(X86_CR4_MCE);
1840 
1841 	rdmsrl(MSR_IA32_MCG_CAP, cap);
1842 	if (cap & MCG_CTL_P)
1843 		wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1844 }
1845 
__mcheck_cpu_init_clear_banks(void)1846 static void __mcheck_cpu_init_clear_banks(void)
1847 {
1848 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1849 	int i;
1850 
1851 	for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1852 		struct mce_bank *b = &mce_banks[i];
1853 
1854 		if (!b->init)
1855 			continue;
1856 		wrmsrl(mca_msr_reg(i, MCA_CTL), b->ctl);
1857 		wrmsrl(mca_msr_reg(i, MCA_STATUS), 0);
1858 	}
1859 }
1860 
1861 /*
1862  * Do a final check to see if there are any unused/RAZ banks.
1863  *
1864  * This must be done after the banks have been initialized and any quirks have
1865  * been applied.
1866  *
1867  * Do not call this from any user-initiated flows, e.g. CPU hotplug or sysfs.
1868  * Otherwise, a user who disables a bank will not be able to re-enable it
1869  * without a system reboot.
1870  */
__mcheck_cpu_check_banks(void)1871 static void __mcheck_cpu_check_banks(void)
1872 {
1873 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1874 	u64 msrval;
1875 	int i;
1876 
1877 	for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
1878 		struct mce_bank *b = &mce_banks[i];
1879 
1880 		if (!b->init)
1881 			continue;
1882 
1883 		rdmsrl(mca_msr_reg(i, MCA_CTL), msrval);
1884 		b->init = !!msrval;
1885 	}
1886 }
1887 
1888 /* Add per CPU specific workarounds here */
__mcheck_cpu_apply_quirks(struct cpuinfo_x86 * c)1889 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1890 {
1891 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
1892 	struct mca_config *cfg = &mca_cfg;
1893 
1894 	if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1895 		pr_info("unknown CPU type - not enabling MCE support\n");
1896 		return -EOPNOTSUPP;
1897 	}
1898 
1899 	/* This should be disabled by the BIOS, but isn't always */
1900 	if (c->x86_vendor == X86_VENDOR_AMD) {
1901 		if (c->x86 == 15 && this_cpu_read(mce_num_banks) > 4) {
1902 			/*
1903 			 * disable GART TBL walk error reporting, which
1904 			 * trips off incorrectly with the IOMMU & 3ware
1905 			 * & Cerberus:
1906 			 */
1907 			clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1908 		}
1909 		if (c->x86 < 0x11 && cfg->bootlog < 0) {
1910 			/*
1911 			 * Lots of broken BIOS around that don't clear them
1912 			 * by default and leave crap in there. Don't log:
1913 			 */
1914 			cfg->bootlog = 0;
1915 		}
1916 		/*
1917 		 * Various K7s with broken bank 0 around. Always disable
1918 		 * by default.
1919 		 */
1920 		if (c->x86 == 6 && this_cpu_read(mce_num_banks) > 0)
1921 			mce_banks[0].ctl = 0;
1922 
1923 		/*
1924 		 * overflow_recov is supported for F15h Models 00h-0fh
1925 		 * even though we don't have a CPUID bit for it.
1926 		 */
1927 		if (c->x86 == 0x15 && c->x86_model <= 0xf)
1928 			mce_flags.overflow_recov = 1;
1929 
1930 		if (c->x86 >= 0x17 && c->x86 <= 0x1A)
1931 			mce_flags.zen_ifu_quirk = 1;
1932 
1933 	}
1934 
1935 	if (c->x86_vendor == X86_VENDOR_INTEL) {
1936 		/*
1937 		 * SDM documents that on family 6 bank 0 should not be written
1938 		 * because it aliases to another special BIOS controlled
1939 		 * register.
1940 		 * But it's not aliased anymore on model 0x1a+
1941 		 * Don't ignore bank 0 completely because there could be a
1942 		 * valid event later, merely don't write CTL0.
1943 		 */
1944 
1945 		if (c->x86 == 6 && c->x86_model < 0x1A && this_cpu_read(mce_num_banks) > 0)
1946 			mce_banks[0].init = false;
1947 
1948 		/*
1949 		 * All newer Intel systems support MCE broadcasting. Enable
1950 		 * synchronization with a one second timeout.
1951 		 */
1952 		if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1953 			cfg->monarch_timeout < 0)
1954 			cfg->monarch_timeout = USEC_PER_SEC;
1955 
1956 		/*
1957 		 * There are also broken BIOSes on some Pentium M and
1958 		 * earlier systems:
1959 		 */
1960 		if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1961 			cfg->bootlog = 0;
1962 
1963 		if (c->x86_vfm == INTEL_SANDYBRIDGE_X)
1964 			mce_flags.snb_ifu_quirk = 1;
1965 
1966 		/*
1967 		 * Skylake, Cascacde Lake and Cooper Lake require a quirk on
1968 		 * rep movs.
1969 		 */
1970 		if (c->x86_vfm == INTEL_SKYLAKE_X)
1971 			mce_flags.skx_repmov_quirk = 1;
1972 	}
1973 
1974 	if (c->x86_vendor == X86_VENDOR_ZHAOXIN) {
1975 		/*
1976 		 * All newer Zhaoxin CPUs support MCE broadcasting. Enable
1977 		 * synchronization with a one second timeout.
1978 		 */
1979 		if (c->x86 > 6 || (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
1980 			if (cfg->monarch_timeout < 0)
1981 				cfg->monarch_timeout = USEC_PER_SEC;
1982 		}
1983 	}
1984 
1985 	if (cfg->monarch_timeout < 0)
1986 		cfg->monarch_timeout = 0;
1987 	if (cfg->bootlog != 0)
1988 		cfg->panic_timeout = 30;
1989 
1990 	return 0;
1991 }
1992 
__mcheck_cpu_ancient_init(struct cpuinfo_x86 * c)1993 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1994 {
1995 	if (c->x86 != 5)
1996 		return 0;
1997 
1998 	switch (c->x86_vendor) {
1999 	case X86_VENDOR_INTEL:
2000 		intel_p5_mcheck_init(c);
2001 		mce_flags.p5 = 1;
2002 		return 1;
2003 	case X86_VENDOR_CENTAUR:
2004 		winchip_mcheck_init(c);
2005 		mce_flags.winchip = 1;
2006 		return 1;
2007 	default:
2008 		return 0;
2009 	}
2010 
2011 	return 0;
2012 }
2013 
2014 /*
2015  * Init basic CPU features needed for early decoding of MCEs.
2016  */
__mcheck_cpu_init_early(struct cpuinfo_x86 * c)2017 static void __mcheck_cpu_init_early(struct cpuinfo_x86 *c)
2018 {
2019 	if (c->x86_vendor == X86_VENDOR_AMD || c->x86_vendor == X86_VENDOR_HYGON) {
2020 		mce_flags.overflow_recov = !!cpu_has(c, X86_FEATURE_OVERFLOW_RECOV);
2021 		mce_flags.succor	 = !!cpu_has(c, X86_FEATURE_SUCCOR);
2022 		mce_flags.smca		 = !!cpu_has(c, X86_FEATURE_SMCA);
2023 		mce_flags.amd_threshold	 = 1;
2024 	}
2025 }
2026 
mce_centaur_feature_init(struct cpuinfo_x86 * c)2027 static void mce_centaur_feature_init(struct cpuinfo_x86 *c)
2028 {
2029 	struct mca_config *cfg = &mca_cfg;
2030 
2031 	 /*
2032 	  * All newer Centaur CPUs support MCE broadcasting. Enable
2033 	  * synchronization with a one second timeout.
2034 	  */
2035 	if ((c->x86 == 6 && c->x86_model == 0xf && c->x86_stepping >= 0xe) ||
2036 	     c->x86 > 6) {
2037 		if (cfg->monarch_timeout < 0)
2038 			cfg->monarch_timeout = USEC_PER_SEC;
2039 	}
2040 }
2041 
mce_zhaoxin_feature_init(struct cpuinfo_x86 * c)2042 static void mce_zhaoxin_feature_init(struct cpuinfo_x86 *c)
2043 {
2044 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2045 
2046 	/*
2047 	 * These CPUs have MCA bank 8 which reports only one error type called
2048 	 * SVAD (System View Address Decoder). The reporting of that error is
2049 	 * controlled by IA32_MC8.CTL.0.
2050 	 *
2051 	 * If enabled, prefetching on these CPUs will cause SVAD MCE when
2052 	 * virtual machines start and result in a system  panic. Always disable
2053 	 * bank 8 SVAD error by default.
2054 	 */
2055 	if ((c->x86 == 7 && c->x86_model == 0x1b) ||
2056 	    (c->x86_model == 0x19 || c->x86_model == 0x1f)) {
2057 		if (this_cpu_read(mce_num_banks) > 8)
2058 			mce_banks[8].ctl = 0;
2059 	}
2060 
2061 	intel_init_cmci();
2062 	intel_init_lmce();
2063 }
2064 
mce_zhaoxin_feature_clear(struct cpuinfo_x86 * c)2065 static void mce_zhaoxin_feature_clear(struct cpuinfo_x86 *c)
2066 {
2067 	intel_clear_lmce();
2068 }
2069 
__mcheck_cpu_init_vendor(struct cpuinfo_x86 * c)2070 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
2071 {
2072 	switch (c->x86_vendor) {
2073 	case X86_VENDOR_INTEL:
2074 		mce_intel_feature_init(c);
2075 		break;
2076 
2077 	case X86_VENDOR_AMD: {
2078 		mce_amd_feature_init(c);
2079 		break;
2080 		}
2081 
2082 	case X86_VENDOR_HYGON:
2083 		mce_hygon_feature_init(c);
2084 		break;
2085 
2086 	case X86_VENDOR_CENTAUR:
2087 		mce_centaur_feature_init(c);
2088 		break;
2089 
2090 	case X86_VENDOR_ZHAOXIN:
2091 		mce_zhaoxin_feature_init(c);
2092 		break;
2093 
2094 	default:
2095 		break;
2096 	}
2097 }
2098 
__mcheck_cpu_clear_vendor(struct cpuinfo_x86 * c)2099 static void __mcheck_cpu_clear_vendor(struct cpuinfo_x86 *c)
2100 {
2101 	switch (c->x86_vendor) {
2102 	case X86_VENDOR_INTEL:
2103 		mce_intel_feature_clear(c);
2104 		break;
2105 
2106 	case X86_VENDOR_ZHAOXIN:
2107 		mce_zhaoxin_feature_clear(c);
2108 		break;
2109 
2110 	default:
2111 		break;
2112 	}
2113 }
2114 
mce_start_timer(struct timer_list * t)2115 static void mce_start_timer(struct timer_list *t)
2116 {
2117 	unsigned long iv = check_interval * HZ;
2118 
2119 	if (should_enable_timer(iv)) {
2120 		this_cpu_write(mce_next_interval, iv);
2121 		__start_timer(t, iv);
2122 	}
2123 }
2124 
__mcheck_cpu_setup_timer(void)2125 static void __mcheck_cpu_setup_timer(void)
2126 {
2127 	struct timer_list *t = this_cpu_ptr(&mce_timer);
2128 
2129 	timer_setup(t, mce_timer_fn, TIMER_PINNED);
2130 }
2131 
__mcheck_cpu_init_timer(void)2132 static void __mcheck_cpu_init_timer(void)
2133 {
2134 	struct timer_list *t = this_cpu_ptr(&mce_timer);
2135 
2136 	timer_setup(t, mce_timer_fn, TIMER_PINNED);
2137 	mce_start_timer(t);
2138 }
2139 
filter_mce(struct mce * m)2140 bool filter_mce(struct mce *m)
2141 {
2142 	if (boot_cpu_data.x86_vendor == X86_VENDOR_AMD)
2143 		return amd_filter_mce(m);
2144 	if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL)
2145 		return intel_filter_mce(m);
2146 
2147 	return false;
2148 }
2149 
exc_machine_check_kernel(struct pt_regs * regs)2150 static __always_inline void exc_machine_check_kernel(struct pt_regs *regs)
2151 {
2152 	irqentry_state_t irq_state;
2153 
2154 	WARN_ON_ONCE(user_mode(regs));
2155 
2156 	/*
2157 	 * Only required when from kernel mode. See
2158 	 * mce_check_crashing_cpu() for details.
2159 	 */
2160 	if (mca_cfg.initialized && mce_check_crashing_cpu())
2161 		return;
2162 
2163 	irq_state = irqentry_nmi_enter(regs);
2164 
2165 	do_machine_check(regs);
2166 
2167 	irqentry_nmi_exit(regs, irq_state);
2168 }
2169 
exc_machine_check_user(struct pt_regs * regs)2170 static __always_inline void exc_machine_check_user(struct pt_regs *regs)
2171 {
2172 	irqentry_enter_from_user_mode(regs);
2173 
2174 	do_machine_check(regs);
2175 
2176 	irqentry_exit_to_user_mode(regs);
2177 }
2178 
2179 #ifdef CONFIG_X86_64
2180 /* MCE hit kernel mode */
DEFINE_IDTENTRY_MCE(exc_machine_check)2181 DEFINE_IDTENTRY_MCE(exc_machine_check)
2182 {
2183 	unsigned long dr7;
2184 
2185 	dr7 = local_db_save();
2186 	exc_machine_check_kernel(regs);
2187 	local_db_restore(dr7);
2188 }
2189 
2190 /* The user mode variant. */
DEFINE_IDTENTRY_MCE_USER(exc_machine_check)2191 DEFINE_IDTENTRY_MCE_USER(exc_machine_check)
2192 {
2193 	unsigned long dr7;
2194 
2195 	dr7 = local_db_save();
2196 	exc_machine_check_user(regs);
2197 	local_db_restore(dr7);
2198 }
2199 
2200 #ifdef CONFIG_X86_FRED
2201 /*
2202  * When occurred on different ring level, i.e., from user or kernel
2203  * context, #MCE needs to be handled on different stack: User #MCE
2204  * on current task stack, while kernel #MCE on a dedicated stack.
2205  *
2206  * This is exactly how FRED event delivery invokes an exception
2207  * handler: ring 3 event on level 0 stack, i.e., current task stack;
2208  * ring 0 event on the #MCE dedicated stack specified in the
2209  * IA32_FRED_STKLVLS MSR. So unlike IDT, the FRED machine check entry
2210  * stub doesn't do stack switch.
2211  */
DEFINE_FREDENTRY_MCE(exc_machine_check)2212 DEFINE_FREDENTRY_MCE(exc_machine_check)
2213 {
2214 	unsigned long dr7;
2215 
2216 	dr7 = local_db_save();
2217 	if (user_mode(regs))
2218 		exc_machine_check_user(regs);
2219 	else
2220 		exc_machine_check_kernel(regs);
2221 	local_db_restore(dr7);
2222 }
2223 #endif
2224 #else
2225 /* 32bit unified entry point */
DEFINE_IDTENTRY_RAW(exc_machine_check)2226 DEFINE_IDTENTRY_RAW(exc_machine_check)
2227 {
2228 	unsigned long dr7;
2229 
2230 	dr7 = local_db_save();
2231 	if (user_mode(regs))
2232 		exc_machine_check_user(regs);
2233 	else
2234 		exc_machine_check_kernel(regs);
2235 	local_db_restore(dr7);
2236 }
2237 #endif
2238 
2239 /*
2240  * Called for each booted CPU to set up machine checks.
2241  * Must be called with preempt off:
2242  */
mcheck_cpu_init(struct cpuinfo_x86 * c)2243 void mcheck_cpu_init(struct cpuinfo_x86 *c)
2244 {
2245 	if (mca_cfg.disabled)
2246 		return;
2247 
2248 	if (__mcheck_cpu_ancient_init(c))
2249 		return;
2250 
2251 	if (!mce_available(c))
2252 		return;
2253 
2254 	__mcheck_cpu_cap_init();
2255 
2256 	if (__mcheck_cpu_apply_quirks(c) < 0) {
2257 		mca_cfg.disabled = 1;
2258 		return;
2259 	}
2260 
2261 	if (mce_gen_pool_init()) {
2262 		mca_cfg.disabled = 1;
2263 		pr_emerg("Couldn't allocate MCE records pool!\n");
2264 		return;
2265 	}
2266 
2267 	mca_cfg.initialized = 1;
2268 
2269 	__mcheck_cpu_init_early(c);
2270 	__mcheck_cpu_init_generic();
2271 	__mcheck_cpu_init_vendor(c);
2272 	__mcheck_cpu_init_clear_banks();
2273 	__mcheck_cpu_check_banks();
2274 	__mcheck_cpu_setup_timer();
2275 }
2276 
2277 /*
2278  * Called for each booted CPU to clear some machine checks opt-ins
2279  */
mcheck_cpu_clear(struct cpuinfo_x86 * c)2280 void mcheck_cpu_clear(struct cpuinfo_x86 *c)
2281 {
2282 	if (mca_cfg.disabled)
2283 		return;
2284 
2285 	if (!mce_available(c))
2286 		return;
2287 
2288 	/*
2289 	 * Possibly to clear general settings generic to x86
2290 	 * __mcheck_cpu_clear_generic(c);
2291 	 */
2292 	__mcheck_cpu_clear_vendor(c);
2293 
2294 }
2295 
__mce_disable_bank(void * arg)2296 static void __mce_disable_bank(void *arg)
2297 {
2298 	int bank = *((int *)arg);
2299 	__clear_bit(bank, this_cpu_ptr(mce_poll_banks));
2300 	cmci_disable_bank(bank);
2301 }
2302 
mce_disable_bank(int bank)2303 void mce_disable_bank(int bank)
2304 {
2305 	if (bank >= this_cpu_read(mce_num_banks)) {
2306 		pr_warn(FW_BUG
2307 			"Ignoring request to disable invalid MCA bank %d.\n",
2308 			bank);
2309 		return;
2310 	}
2311 	set_bit(bank, mce_banks_ce_disabled);
2312 	on_each_cpu(__mce_disable_bank, &bank, 1);
2313 }
2314 
2315 /*
2316  * mce=off Disables machine check
2317  * mce=no_cmci Disables CMCI
2318  * mce=no_lmce Disables LMCE
2319  * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
2320  * mce=print_all Print all machine check logs to console
2321  * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
2322  * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
2323  *	monarchtimeout is how long to wait for other CPUs on machine
2324  *	check, or 0 to not wait
2325  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD Fam10h
2326 	and older.
2327  * mce=nobootlog Don't log MCEs from before booting.
2328  * mce=bios_cmci_threshold Don't program the CMCI threshold
2329  * mce=recovery force enable copy_mc_fragile()
2330  */
mcheck_enable(char * str)2331 static int __init mcheck_enable(char *str)
2332 {
2333 	struct mca_config *cfg = &mca_cfg;
2334 
2335 	if (*str == 0) {
2336 		enable_p5_mce();
2337 		return 1;
2338 	}
2339 	if (*str == '=')
2340 		str++;
2341 	if (!strcmp(str, "off"))
2342 		cfg->disabled = 1;
2343 	else if (!strcmp(str, "no_cmci"))
2344 		cfg->cmci_disabled = true;
2345 	else if (!strcmp(str, "no_lmce"))
2346 		cfg->lmce_disabled = 1;
2347 	else if (!strcmp(str, "dont_log_ce"))
2348 		cfg->dont_log_ce = true;
2349 	else if (!strcmp(str, "print_all"))
2350 		cfg->print_all = true;
2351 	else if (!strcmp(str, "ignore_ce"))
2352 		cfg->ignore_ce = true;
2353 	else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2354 		cfg->bootlog = (str[0] == 'b');
2355 	else if (!strcmp(str, "bios_cmci_threshold"))
2356 		cfg->bios_cmci_threshold = 1;
2357 	else if (!strcmp(str, "recovery"))
2358 		cfg->recovery = 1;
2359 	else if (isdigit(str[0]))
2360 		get_option(&str, &(cfg->monarch_timeout));
2361 	else {
2362 		pr_info("mce argument %s ignored. Please use /sys\n", str);
2363 		return 0;
2364 	}
2365 	return 1;
2366 }
2367 __setup("mce", mcheck_enable);
2368 
mcheck_init(void)2369 int __init mcheck_init(void)
2370 {
2371 	mce_register_decode_chain(&early_nb);
2372 	mce_register_decode_chain(&mce_uc_nb);
2373 	mce_register_decode_chain(&mce_default_nb);
2374 
2375 	INIT_WORK(&mce_work, mce_gen_pool_process);
2376 	init_irq_work(&mce_irq_work, mce_irq_work_cb);
2377 
2378 	return 0;
2379 }
2380 
2381 /*
2382  * mce_syscore: PM support
2383  */
2384 
2385 /*
2386  * Disable machine checks on suspend and shutdown. We can't really handle
2387  * them later.
2388  */
mce_disable_error_reporting(void)2389 static void mce_disable_error_reporting(void)
2390 {
2391 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2392 	int i;
2393 
2394 	for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2395 		struct mce_bank *b = &mce_banks[i];
2396 
2397 		if (b->init)
2398 			wrmsrl(mca_msr_reg(i, MCA_CTL), 0);
2399 	}
2400 	return;
2401 }
2402 
vendor_disable_error_reporting(void)2403 static void vendor_disable_error_reporting(void)
2404 {
2405 	/*
2406 	 * Don't clear on Intel or AMD or Hygon or Zhaoxin CPUs. Some of these
2407 	 * MSRs are socket-wide. Disabling them for just a single offlined CPU
2408 	 * is bad, since it will inhibit reporting for all shared resources on
2409 	 * the socket like the last level cache (LLC), the integrated memory
2410 	 * controller (iMC), etc.
2411 	 */
2412 	if (boot_cpu_data.x86_vendor == X86_VENDOR_INTEL ||
2413 	    boot_cpu_data.x86_vendor == X86_VENDOR_HYGON ||
2414 	    boot_cpu_data.x86_vendor == X86_VENDOR_AMD ||
2415 	    boot_cpu_data.x86_vendor == X86_VENDOR_ZHAOXIN)
2416 		return;
2417 
2418 	mce_disable_error_reporting();
2419 }
2420 
mce_syscore_suspend(void)2421 static int mce_syscore_suspend(void)
2422 {
2423 	vendor_disable_error_reporting();
2424 	return 0;
2425 }
2426 
mce_syscore_shutdown(void)2427 static void mce_syscore_shutdown(void)
2428 {
2429 	vendor_disable_error_reporting();
2430 }
2431 
2432 /*
2433  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2434  * Only one CPU is active at this time, the others get re-added later using
2435  * CPU hotplug:
2436  */
mce_syscore_resume(void)2437 static void mce_syscore_resume(void)
2438 {
2439 	__mcheck_cpu_init_generic();
2440 	__mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2441 	__mcheck_cpu_init_clear_banks();
2442 }
2443 
2444 static struct syscore_ops mce_syscore_ops = {
2445 	.suspend	= mce_syscore_suspend,
2446 	.shutdown	= mce_syscore_shutdown,
2447 	.resume		= mce_syscore_resume,
2448 };
2449 
2450 /*
2451  * mce_device: Sysfs support
2452  */
2453 
mce_cpu_restart(void * data)2454 static void mce_cpu_restart(void *data)
2455 {
2456 	if (!mce_available(raw_cpu_ptr(&cpu_info)))
2457 		return;
2458 	__mcheck_cpu_init_generic();
2459 	__mcheck_cpu_init_clear_banks();
2460 	__mcheck_cpu_init_timer();
2461 }
2462 
2463 /* Reinit MCEs after user configuration changes */
mce_restart(void)2464 static void mce_restart(void)
2465 {
2466 	mce_timer_delete_all();
2467 	on_each_cpu(mce_cpu_restart, NULL, 1);
2468 	mce_schedule_work();
2469 }
2470 
2471 /* Toggle features for corrected errors */
mce_disable_cmci(void * data)2472 static void mce_disable_cmci(void *data)
2473 {
2474 	if (!mce_available(raw_cpu_ptr(&cpu_info)))
2475 		return;
2476 	cmci_clear();
2477 }
2478 
mce_enable_ce(void * all)2479 static void mce_enable_ce(void *all)
2480 {
2481 	if (!mce_available(raw_cpu_ptr(&cpu_info)))
2482 		return;
2483 	cmci_reenable();
2484 	cmci_recheck();
2485 	if (all)
2486 		__mcheck_cpu_init_timer();
2487 }
2488 
2489 static const struct bus_type mce_subsys = {
2490 	.name		= "machinecheck",
2491 	.dev_name	= "machinecheck",
2492 };
2493 
2494 DEFINE_PER_CPU(struct device *, mce_device);
2495 
attr_to_bank(struct device_attribute * attr)2496 static inline struct mce_bank_dev *attr_to_bank(struct device_attribute *attr)
2497 {
2498 	return container_of(attr, struct mce_bank_dev, attr);
2499 }
2500 
show_bank(struct device * s,struct device_attribute * attr,char * buf)2501 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2502 			 char *buf)
2503 {
2504 	u8 bank = attr_to_bank(attr)->bank;
2505 	struct mce_bank *b;
2506 
2507 	if (bank >= per_cpu(mce_num_banks, s->id))
2508 		return -EINVAL;
2509 
2510 	b = &per_cpu(mce_banks_array, s->id)[bank];
2511 
2512 	if (!b->init)
2513 		return -ENODEV;
2514 
2515 	return sprintf(buf, "%llx\n", b->ctl);
2516 }
2517 
set_bank(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2518 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2519 			const char *buf, size_t size)
2520 {
2521 	u8 bank = attr_to_bank(attr)->bank;
2522 	struct mce_bank *b;
2523 	u64 new;
2524 
2525 	if (kstrtou64(buf, 0, &new) < 0)
2526 		return -EINVAL;
2527 
2528 	if (bank >= per_cpu(mce_num_banks, s->id))
2529 		return -EINVAL;
2530 
2531 	b = &per_cpu(mce_banks_array, s->id)[bank];
2532 	if (!b->init)
2533 		return -ENODEV;
2534 
2535 	b->ctl = new;
2536 
2537 	mutex_lock(&mce_sysfs_mutex);
2538 	mce_restart();
2539 	mutex_unlock(&mce_sysfs_mutex);
2540 
2541 	return size;
2542 }
2543 
set_ignore_ce(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2544 static ssize_t set_ignore_ce(struct device *s,
2545 			     struct device_attribute *attr,
2546 			     const char *buf, size_t size)
2547 {
2548 	u64 new;
2549 
2550 	if (kstrtou64(buf, 0, &new) < 0)
2551 		return -EINVAL;
2552 
2553 	mutex_lock(&mce_sysfs_mutex);
2554 	if (mca_cfg.ignore_ce ^ !!new) {
2555 		if (new) {
2556 			/* disable ce features */
2557 			mce_timer_delete_all();
2558 			on_each_cpu(mce_disable_cmci, NULL, 1);
2559 			mca_cfg.ignore_ce = true;
2560 		} else {
2561 			/* enable ce features */
2562 			mca_cfg.ignore_ce = false;
2563 			on_each_cpu(mce_enable_ce, (void *)1, 1);
2564 		}
2565 	}
2566 	mutex_unlock(&mce_sysfs_mutex);
2567 
2568 	return size;
2569 }
2570 
set_cmci_disabled(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2571 static ssize_t set_cmci_disabled(struct device *s,
2572 				 struct device_attribute *attr,
2573 				 const char *buf, size_t size)
2574 {
2575 	u64 new;
2576 
2577 	if (kstrtou64(buf, 0, &new) < 0)
2578 		return -EINVAL;
2579 
2580 	mutex_lock(&mce_sysfs_mutex);
2581 	if (mca_cfg.cmci_disabled ^ !!new) {
2582 		if (new) {
2583 			/* disable cmci */
2584 			on_each_cpu(mce_disable_cmci, NULL, 1);
2585 			mca_cfg.cmci_disabled = true;
2586 		} else {
2587 			/* enable cmci */
2588 			mca_cfg.cmci_disabled = false;
2589 			on_each_cpu(mce_enable_ce, NULL, 1);
2590 		}
2591 	}
2592 	mutex_unlock(&mce_sysfs_mutex);
2593 
2594 	return size;
2595 }
2596 
store_int_with_restart(struct device * s,struct device_attribute * attr,const char * buf,size_t size)2597 static ssize_t store_int_with_restart(struct device *s,
2598 				      struct device_attribute *attr,
2599 				      const char *buf, size_t size)
2600 {
2601 	unsigned long old_check_interval = check_interval;
2602 	ssize_t ret = device_store_ulong(s, attr, buf, size);
2603 
2604 	if (check_interval == old_check_interval)
2605 		return ret;
2606 
2607 	mutex_lock(&mce_sysfs_mutex);
2608 	mce_restart();
2609 	mutex_unlock(&mce_sysfs_mutex);
2610 
2611 	return ret;
2612 }
2613 
2614 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2615 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2616 static DEVICE_BOOL_ATTR(print_all, 0644, mca_cfg.print_all);
2617 
2618 static struct dev_ext_attribute dev_attr_check_interval = {
2619 	__ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2620 	&check_interval
2621 };
2622 
2623 static struct dev_ext_attribute dev_attr_ignore_ce = {
2624 	__ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2625 	&mca_cfg.ignore_ce
2626 };
2627 
2628 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2629 	__ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2630 	&mca_cfg.cmci_disabled
2631 };
2632 
2633 static struct device_attribute *mce_device_attrs[] = {
2634 	&dev_attr_check_interval.attr,
2635 #ifdef CONFIG_X86_MCELOG_LEGACY
2636 	&dev_attr_trigger,
2637 #endif
2638 	&dev_attr_monarch_timeout.attr,
2639 	&dev_attr_dont_log_ce.attr,
2640 	&dev_attr_print_all.attr,
2641 	&dev_attr_ignore_ce.attr,
2642 	&dev_attr_cmci_disabled.attr,
2643 	NULL
2644 };
2645 
2646 static cpumask_var_t mce_device_initialized;
2647 
mce_device_release(struct device * dev)2648 static void mce_device_release(struct device *dev)
2649 {
2650 	kfree(dev);
2651 }
2652 
2653 /* Per CPU device init. All of the CPUs still share the same bank device: */
mce_device_create(unsigned int cpu)2654 static int mce_device_create(unsigned int cpu)
2655 {
2656 	struct device *dev;
2657 	int err;
2658 	int i, j;
2659 
2660 	dev = per_cpu(mce_device, cpu);
2661 	if (dev)
2662 		return 0;
2663 
2664 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2665 	if (!dev)
2666 		return -ENOMEM;
2667 	dev->id  = cpu;
2668 	dev->bus = &mce_subsys;
2669 	dev->release = &mce_device_release;
2670 
2671 	err = device_register(dev);
2672 	if (err) {
2673 		put_device(dev);
2674 		return err;
2675 	}
2676 
2677 	for (i = 0; mce_device_attrs[i]; i++) {
2678 		err = device_create_file(dev, mce_device_attrs[i]);
2679 		if (err)
2680 			goto error;
2681 	}
2682 	for (j = 0; j < per_cpu(mce_num_banks, cpu); j++) {
2683 		err = device_create_file(dev, &mce_bank_devs[j].attr);
2684 		if (err)
2685 			goto error2;
2686 	}
2687 	cpumask_set_cpu(cpu, mce_device_initialized);
2688 	per_cpu(mce_device, cpu) = dev;
2689 
2690 	return 0;
2691 error2:
2692 	while (--j >= 0)
2693 		device_remove_file(dev, &mce_bank_devs[j].attr);
2694 error:
2695 	while (--i >= 0)
2696 		device_remove_file(dev, mce_device_attrs[i]);
2697 
2698 	device_unregister(dev);
2699 
2700 	return err;
2701 }
2702 
mce_device_remove(unsigned int cpu)2703 static void mce_device_remove(unsigned int cpu)
2704 {
2705 	struct device *dev = per_cpu(mce_device, cpu);
2706 	int i;
2707 
2708 	if (!cpumask_test_cpu(cpu, mce_device_initialized))
2709 		return;
2710 
2711 	for (i = 0; mce_device_attrs[i]; i++)
2712 		device_remove_file(dev, mce_device_attrs[i]);
2713 
2714 	for (i = 0; i < per_cpu(mce_num_banks, cpu); i++)
2715 		device_remove_file(dev, &mce_bank_devs[i].attr);
2716 
2717 	device_unregister(dev);
2718 	cpumask_clear_cpu(cpu, mce_device_initialized);
2719 	per_cpu(mce_device, cpu) = NULL;
2720 }
2721 
2722 /* Make sure there are no machine checks on offlined CPUs. */
mce_disable_cpu(void)2723 static void mce_disable_cpu(void)
2724 {
2725 	if (!mce_available(raw_cpu_ptr(&cpu_info)))
2726 		return;
2727 
2728 	if (!cpuhp_tasks_frozen)
2729 		cmci_clear();
2730 
2731 	vendor_disable_error_reporting();
2732 }
2733 
mce_reenable_cpu(void)2734 static void mce_reenable_cpu(void)
2735 {
2736 	struct mce_bank *mce_banks = this_cpu_ptr(mce_banks_array);
2737 	int i;
2738 
2739 	if (!mce_available(raw_cpu_ptr(&cpu_info)))
2740 		return;
2741 
2742 	if (!cpuhp_tasks_frozen)
2743 		cmci_reenable();
2744 	for (i = 0; i < this_cpu_read(mce_num_banks); i++) {
2745 		struct mce_bank *b = &mce_banks[i];
2746 
2747 		if (b->init)
2748 			wrmsrl(mca_msr_reg(i, MCA_CTL), b->ctl);
2749 	}
2750 }
2751 
mce_cpu_dead(unsigned int cpu)2752 static int mce_cpu_dead(unsigned int cpu)
2753 {
2754 	/* intentionally ignoring frozen here */
2755 	if (!cpuhp_tasks_frozen)
2756 		cmci_rediscover();
2757 	return 0;
2758 }
2759 
mce_cpu_online(unsigned int cpu)2760 static int mce_cpu_online(unsigned int cpu)
2761 {
2762 	struct timer_list *t = this_cpu_ptr(&mce_timer);
2763 
2764 	mce_device_create(cpu);
2765 	mce_threshold_create_device(cpu);
2766 	mce_reenable_cpu();
2767 	mce_start_timer(t);
2768 	return 0;
2769 }
2770 
mce_cpu_pre_down(unsigned int cpu)2771 static int mce_cpu_pre_down(unsigned int cpu)
2772 {
2773 	struct timer_list *t = this_cpu_ptr(&mce_timer);
2774 
2775 	mce_disable_cpu();
2776 	del_timer_sync(t);
2777 	mce_threshold_remove_device(cpu);
2778 	mce_device_remove(cpu);
2779 	return 0;
2780 }
2781 
mce_init_banks(void)2782 static __init void mce_init_banks(void)
2783 {
2784 	int i;
2785 
2786 	for (i = 0; i < MAX_NR_BANKS; i++) {
2787 		struct mce_bank_dev *b = &mce_bank_devs[i];
2788 		struct device_attribute *a = &b->attr;
2789 
2790 		b->bank = i;
2791 
2792 		sysfs_attr_init(&a->attr);
2793 		a->attr.name	= b->attrname;
2794 		snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2795 
2796 		a->attr.mode	= 0644;
2797 		a->show		= show_bank;
2798 		a->store	= set_bank;
2799 	}
2800 }
2801 
2802 /*
2803  * When running on XEN, this initcall is ordered against the XEN mcelog
2804  * initcall:
2805  *
2806  *   device_initcall(xen_late_init_mcelog);
2807  *   device_initcall_sync(mcheck_init_device);
2808  */
mcheck_init_device(void)2809 static __init int mcheck_init_device(void)
2810 {
2811 	int err;
2812 
2813 	/*
2814 	 * Check if we have a spare virtual bit. This will only become
2815 	 * a problem if/when we move beyond 5-level page tables.
2816 	 */
2817 	MAYBE_BUILD_BUG_ON(__VIRTUAL_MASK_SHIFT >= 63);
2818 
2819 	if (!mce_available(&boot_cpu_data)) {
2820 		err = -EIO;
2821 		goto err_out;
2822 	}
2823 
2824 	if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2825 		err = -ENOMEM;
2826 		goto err_out;
2827 	}
2828 
2829 	mce_init_banks();
2830 
2831 	err = subsys_system_register(&mce_subsys, NULL);
2832 	if (err)
2833 		goto err_out_mem;
2834 
2835 	err = cpuhp_setup_state(CPUHP_X86_MCE_DEAD, "x86/mce:dead", NULL,
2836 				mce_cpu_dead);
2837 	if (err)
2838 		goto err_out_mem;
2839 
2840 	/*
2841 	 * Invokes mce_cpu_online() on all CPUs which are online when
2842 	 * the state is installed.
2843 	 */
2844 	err = cpuhp_setup_state(CPUHP_AP_ONLINE_DYN, "x86/mce:online",
2845 				mce_cpu_online, mce_cpu_pre_down);
2846 	if (err < 0)
2847 		goto err_out_online;
2848 
2849 	register_syscore_ops(&mce_syscore_ops);
2850 
2851 	return 0;
2852 
2853 err_out_online:
2854 	cpuhp_remove_state(CPUHP_X86_MCE_DEAD);
2855 
2856 err_out_mem:
2857 	free_cpumask_var(mce_device_initialized);
2858 
2859 err_out:
2860 	pr_err("Unable to init MCE device (rc: %d)\n", err);
2861 
2862 	return err;
2863 }
2864 device_initcall_sync(mcheck_init_device);
2865 
2866 /*
2867  * Old style boot options parsing. Only for compatibility.
2868  */
mcheck_disable(char * str)2869 static int __init mcheck_disable(char *str)
2870 {
2871 	mca_cfg.disabled = 1;
2872 	return 1;
2873 }
2874 __setup("nomce", mcheck_disable);
2875 
2876 #ifdef CONFIG_DEBUG_FS
mce_get_debugfs_dir(void)2877 struct dentry *mce_get_debugfs_dir(void)
2878 {
2879 	static struct dentry *dmce;
2880 
2881 	if (!dmce)
2882 		dmce = debugfs_create_dir("mce", NULL);
2883 
2884 	return dmce;
2885 }
2886 
mce_reset(void)2887 static void mce_reset(void)
2888 {
2889 	atomic_set(&mce_fake_panicked, 0);
2890 	atomic_set(&mce_executing, 0);
2891 	atomic_set(&mce_callin, 0);
2892 	atomic_set(&global_nwo, 0);
2893 	cpumask_setall(&mce_missing_cpus);
2894 }
2895 
fake_panic_get(void * data,u64 * val)2896 static int fake_panic_get(void *data, u64 *val)
2897 {
2898 	*val = fake_panic;
2899 	return 0;
2900 }
2901 
fake_panic_set(void * data,u64 val)2902 static int fake_panic_set(void *data, u64 val)
2903 {
2904 	mce_reset();
2905 	fake_panic = val;
2906 	return 0;
2907 }
2908 
2909 DEFINE_DEBUGFS_ATTRIBUTE(fake_panic_fops, fake_panic_get, fake_panic_set,
2910 			 "%llu\n");
2911 
mcheck_debugfs_init(void)2912 static void __init mcheck_debugfs_init(void)
2913 {
2914 	struct dentry *dmce;
2915 
2916 	dmce = mce_get_debugfs_dir();
2917 	debugfs_create_file_unsafe("fake_panic", 0444, dmce, NULL,
2918 				   &fake_panic_fops);
2919 }
2920 #else
mcheck_debugfs_init(void)2921 static void __init mcheck_debugfs_init(void) { }
2922 #endif
2923 
mcheck_late_init(void)2924 static int __init mcheck_late_init(void)
2925 {
2926 	if (mca_cfg.recovery)
2927 		enable_copy_mc_fragile();
2928 
2929 	mcheck_debugfs_init();
2930 
2931 	/*
2932 	 * Flush out everything that has been logged during early boot, now that
2933 	 * everything has been initialized (workqueues, decoders, ...).
2934 	 */
2935 	mce_schedule_work();
2936 
2937 	return 0;
2938 }
2939 late_initcall(mcheck_late_init);
2940