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