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