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