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