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