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