]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blob - arch/x86/kernel/cpu/mcheck/mce.c
Merge branch 'sched-fixes-for-linus' of git://git.kernel.org/pub/scm/linux/kernel...
[mirror_ubuntu-bionic-kernel.git] / arch / x86 / kernel / cpu / mcheck / mce.c
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 #include <linux/thread_info.h>
11 #include <linux/capability.h>
12 #include <linux/miscdevice.h>
13 #include <linux/interrupt.h>
14 #include <linux/ratelimit.h>
15 #include <linux/kallsyms.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/sysdev.h>
24 #include <linux/delay.h>
25 #include <linux/ctype.h>
26 #include <linux/sched.h>
27 #include <linux/sysfs.h>
28 #include <linux/types.h>
29 #include <linux/init.h>
30 #include <linux/kmod.h>
31 #include <linux/poll.h>
32 #include <linux/nmi.h>
33 #include <linux/cpu.h>
34 #include <linux/smp.h>
35 #include <linux/fs.h>
36 #include <linux/mm.h>
37 #include <linux/debugfs.h>
38
39 #include <asm/processor.h>
40 #include <asm/hw_irq.h>
41 #include <asm/apic.h>
42 #include <asm/idle.h>
43 #include <asm/ipi.h>
44 #include <asm/mce.h>
45 #include <asm/msr.h>
46
47 #include "mce-internal.h"
48
49 #define rcu_dereference_check_mce(p) \
50 rcu_dereference_check((p), \
51 rcu_read_lock_sched_held() || \
52 lockdep_is_held(&mce_read_mutex))
53
54 #define CREATE_TRACE_POINTS
55 #include <trace/events/mce.h>
56
57 int mce_disabled __read_mostly;
58
59 #define MISC_MCELOG_MINOR 227
60
61 #define SPINUNIT 100 /* 100ns */
62
63 atomic_t mce_entry;
64
65 DEFINE_PER_CPU(unsigned, mce_exception_count);
66
67 /*
68 * Tolerant levels:
69 * 0: always panic on uncorrected errors, log corrected errors
70 * 1: panic or SIGBUS on uncorrected errors, log corrected errors
71 * 2: SIGBUS or log uncorrected errors (if possible), log corrected errors
72 * 3: never panic or SIGBUS, log all errors (for testing only)
73 */
74 static int tolerant __read_mostly = 1;
75 static int banks __read_mostly;
76 static int rip_msr __read_mostly;
77 static int mce_bootlog __read_mostly = -1;
78 static int monarch_timeout __read_mostly = -1;
79 static int mce_panic_timeout __read_mostly;
80 static int mce_dont_log_ce __read_mostly;
81 int mce_cmci_disabled __read_mostly;
82 int mce_ignore_ce __read_mostly;
83 int mce_ser __read_mostly;
84
85 struct mce_bank *mce_banks __read_mostly;
86
87 /* User mode helper program triggered by machine check event */
88 static unsigned long mce_need_notify;
89 static char mce_helper[128];
90 static char *mce_helper_argv[2] = { mce_helper, NULL };
91
92 static DECLARE_WAIT_QUEUE_HEAD(mce_wait);
93 static DEFINE_PER_CPU(struct mce, mces_seen);
94 static int cpu_missing;
95
96 /*
97 * CPU/chipset specific EDAC code can register a notifier call here to print
98 * MCE errors in a human-readable form.
99 */
100 ATOMIC_NOTIFIER_HEAD(x86_mce_decoder_chain);
101 EXPORT_SYMBOL_GPL(x86_mce_decoder_chain);
102
103 static int default_decode_mce(struct notifier_block *nb, unsigned long val,
104 void *data)
105 {
106 pr_emerg("No human readable MCE decoding support on this CPU type.\n");
107 pr_emerg("Run the message through 'mcelog --ascii' to decode.\n");
108
109 return NOTIFY_STOP;
110 }
111
112 static struct notifier_block mce_dec_nb = {
113 .notifier_call = default_decode_mce,
114 .priority = -1,
115 };
116
117 /* MCA banks polled by the period polling timer for corrected events */
118 DEFINE_PER_CPU(mce_banks_t, mce_poll_banks) = {
119 [0 ... BITS_TO_LONGS(MAX_NR_BANKS)-1] = ~0UL
120 };
121
122 static DEFINE_PER_CPU(struct work_struct, mce_work);
123
124 /* Do initial initialization of a struct mce */
125 void mce_setup(struct mce *m)
126 {
127 memset(m, 0, sizeof(struct mce));
128 m->cpu = m->extcpu = smp_processor_id();
129 rdtscll(m->tsc);
130 /* We hope get_seconds stays lockless */
131 m->time = get_seconds();
132 m->cpuvendor = boot_cpu_data.x86_vendor;
133 m->cpuid = cpuid_eax(1);
134 #ifdef CONFIG_SMP
135 m->socketid = cpu_data(m->extcpu).phys_proc_id;
136 #endif
137 m->apicid = cpu_data(m->extcpu).initial_apicid;
138 rdmsrl(MSR_IA32_MCG_CAP, m->mcgcap);
139 }
140
141 DEFINE_PER_CPU(struct mce, injectm);
142 EXPORT_PER_CPU_SYMBOL_GPL(injectm);
143
144 /*
145 * Lockless MCE logging infrastructure.
146 * This avoids deadlocks on printk locks without having to break locks. Also
147 * separate MCEs from kernel messages to avoid bogus bug reports.
148 */
149
150 static struct mce_log mcelog = {
151 .signature = MCE_LOG_SIGNATURE,
152 .len = MCE_LOG_LEN,
153 .recordlen = sizeof(struct mce),
154 };
155
156 void mce_log(struct mce *mce)
157 {
158 unsigned next, entry;
159
160 /* Emit the trace record: */
161 trace_mce_record(mce);
162
163 mce->finished = 0;
164 wmb();
165 for (;;) {
166 entry = rcu_dereference_check_mce(mcelog.next);
167 for (;;) {
168 /*
169 * When the buffer fills up discard new entries.
170 * Assume that the earlier errors are the more
171 * interesting ones:
172 */
173 if (entry >= MCE_LOG_LEN) {
174 set_bit(MCE_OVERFLOW,
175 (unsigned long *)&mcelog.flags);
176 return;
177 }
178 /* Old left over entry. Skip: */
179 if (mcelog.entry[entry].finished) {
180 entry++;
181 continue;
182 }
183 break;
184 }
185 smp_rmb();
186 next = entry + 1;
187 if (cmpxchg(&mcelog.next, entry, next) == entry)
188 break;
189 }
190 memcpy(mcelog.entry + entry, mce, sizeof(struct mce));
191 wmb();
192 mcelog.entry[entry].finished = 1;
193 wmb();
194
195 mce->finished = 1;
196 set_bit(0, &mce_need_notify);
197 }
198
199 static void print_mce(struct mce *m)
200 {
201 pr_emerg("CPU %d: Machine Check Exception: %16Lx Bank %d: %016Lx\n",
202 m->extcpu, m->mcgstatus, m->bank, m->status);
203
204 if (m->ip) {
205 pr_emerg("RIP%s %02x:<%016Lx> ",
206 !(m->mcgstatus & MCG_STATUS_EIPV) ? " !INEXACT!" : "",
207 m->cs, m->ip);
208
209 if (m->cs == __KERNEL_CS)
210 print_symbol("{%s}", m->ip);
211 pr_cont("\n");
212 }
213
214 pr_emerg("TSC %llx ", m->tsc);
215 if (m->addr)
216 pr_cont("ADDR %llx ", m->addr);
217 if (m->misc)
218 pr_cont("MISC %llx ", m->misc);
219
220 pr_cont("\n");
221 pr_emerg("PROCESSOR %u:%x TIME %llu SOCKET %u APIC %x\n",
222 m->cpuvendor, m->cpuid, m->time, m->socketid, m->apicid);
223
224 /*
225 * Print out human-readable details about the MCE error,
226 * (if the CPU has an implementation for that)
227 */
228 atomic_notifier_call_chain(&x86_mce_decoder_chain, 0, m);
229 }
230
231 static void print_mce_head(void)
232 {
233 pr_emerg("\nHARDWARE ERROR\n");
234 }
235
236 static void print_mce_tail(void)
237 {
238 pr_emerg("This is not a software problem!\n");
239 }
240
241 #define PANIC_TIMEOUT 5 /* 5 seconds */
242
243 static atomic_t mce_paniced;
244
245 static int fake_panic;
246 static atomic_t mce_fake_paniced;
247
248 /* Panic in progress. Enable interrupts and wait for final IPI */
249 static void wait_for_panic(void)
250 {
251 long timeout = PANIC_TIMEOUT*USEC_PER_SEC;
252
253 preempt_disable();
254 local_irq_enable();
255 while (timeout-- > 0)
256 udelay(1);
257 if (panic_timeout == 0)
258 panic_timeout = mce_panic_timeout;
259 panic("Panicing machine check CPU died");
260 }
261
262 static void mce_panic(char *msg, struct mce *final, char *exp)
263 {
264 int i;
265
266 if (!fake_panic) {
267 /*
268 * Make sure only one CPU runs in machine check panic
269 */
270 if (atomic_inc_return(&mce_paniced) > 1)
271 wait_for_panic();
272 barrier();
273
274 bust_spinlocks(1);
275 console_verbose();
276 } else {
277 /* Don't log too much for fake panic */
278 if (atomic_inc_return(&mce_fake_paniced) > 1)
279 return;
280 }
281 print_mce_head();
282 /* First print corrected ones that are still unlogged */
283 for (i = 0; i < MCE_LOG_LEN; i++) {
284 struct mce *m = &mcelog.entry[i];
285 if (!(m->status & MCI_STATUS_VAL))
286 continue;
287 if (!(m->status & MCI_STATUS_UC))
288 print_mce(m);
289 }
290 /* Now print uncorrected but with the final one last */
291 for (i = 0; i < MCE_LOG_LEN; i++) {
292 struct mce *m = &mcelog.entry[i];
293 if (!(m->status & MCI_STATUS_VAL))
294 continue;
295 if (!(m->status & MCI_STATUS_UC))
296 continue;
297 if (!final || memcmp(m, final, sizeof(struct mce)))
298 print_mce(m);
299 }
300 if (final)
301 print_mce(final);
302 if (cpu_missing)
303 printk(KERN_EMERG "Some CPUs didn't answer in synchronization\n");
304 print_mce_tail();
305 if (exp)
306 printk(KERN_EMERG "Machine check: %s\n", exp);
307 if (!fake_panic) {
308 if (panic_timeout == 0)
309 panic_timeout = mce_panic_timeout;
310 panic(msg);
311 } else
312 printk(KERN_EMERG "Fake kernel panic: %s\n", msg);
313 }
314
315 /* Support code for software error injection */
316
317 static int msr_to_offset(u32 msr)
318 {
319 unsigned bank = __get_cpu_var(injectm.bank);
320
321 if (msr == rip_msr)
322 return offsetof(struct mce, ip);
323 if (msr == MSR_IA32_MCx_STATUS(bank))
324 return offsetof(struct mce, status);
325 if (msr == MSR_IA32_MCx_ADDR(bank))
326 return offsetof(struct mce, addr);
327 if (msr == MSR_IA32_MCx_MISC(bank))
328 return offsetof(struct mce, misc);
329 if (msr == MSR_IA32_MCG_STATUS)
330 return offsetof(struct mce, mcgstatus);
331 return -1;
332 }
333
334 /* MSR access wrappers used for error injection */
335 static u64 mce_rdmsrl(u32 msr)
336 {
337 u64 v;
338
339 if (__get_cpu_var(injectm).finished) {
340 int offset = msr_to_offset(msr);
341
342 if (offset < 0)
343 return 0;
344 return *(u64 *)((char *)&__get_cpu_var(injectm) + offset);
345 }
346
347 if (rdmsrl_safe(msr, &v)) {
348 WARN_ONCE(1, "mce: Unable to read msr %d!\n", msr);
349 /*
350 * Return zero in case the access faulted. This should
351 * not happen normally but can happen if the CPU does
352 * something weird, or if the code is buggy.
353 */
354 v = 0;
355 }
356
357 return v;
358 }
359
360 static void mce_wrmsrl(u32 msr, u64 v)
361 {
362 if (__get_cpu_var(injectm).finished) {
363 int offset = msr_to_offset(msr);
364
365 if (offset >= 0)
366 *(u64 *)((char *)&__get_cpu_var(injectm) + offset) = v;
367 return;
368 }
369 wrmsrl(msr, v);
370 }
371
372 /*
373 * Simple lockless ring to communicate PFNs from the exception handler with the
374 * process context work function. This is vastly simplified because there's
375 * only a single reader and a single writer.
376 */
377 #define MCE_RING_SIZE 16 /* we use one entry less */
378
379 struct mce_ring {
380 unsigned short start;
381 unsigned short end;
382 unsigned long ring[MCE_RING_SIZE];
383 };
384 static DEFINE_PER_CPU(struct mce_ring, mce_ring);
385
386 /* Runs with CPU affinity in workqueue */
387 static int mce_ring_empty(void)
388 {
389 struct mce_ring *r = &__get_cpu_var(mce_ring);
390
391 return r->start == r->end;
392 }
393
394 static int mce_ring_get(unsigned long *pfn)
395 {
396 struct mce_ring *r;
397 int ret = 0;
398
399 *pfn = 0;
400 get_cpu();
401 r = &__get_cpu_var(mce_ring);
402 if (r->start == r->end)
403 goto out;
404 *pfn = r->ring[r->start];
405 r->start = (r->start + 1) % MCE_RING_SIZE;
406 ret = 1;
407 out:
408 put_cpu();
409 return ret;
410 }
411
412 /* Always runs in MCE context with preempt off */
413 static int mce_ring_add(unsigned long pfn)
414 {
415 struct mce_ring *r = &__get_cpu_var(mce_ring);
416 unsigned next;
417
418 next = (r->end + 1) % MCE_RING_SIZE;
419 if (next == r->start)
420 return -1;
421 r->ring[r->end] = pfn;
422 wmb();
423 r->end = next;
424 return 0;
425 }
426
427 int mce_available(struct cpuinfo_x86 *c)
428 {
429 if (mce_disabled)
430 return 0;
431 return cpu_has(c, X86_FEATURE_MCE) && cpu_has(c, X86_FEATURE_MCA);
432 }
433
434 static void mce_schedule_work(void)
435 {
436 if (!mce_ring_empty()) {
437 struct work_struct *work = &__get_cpu_var(mce_work);
438 if (!work_pending(work))
439 schedule_work(work);
440 }
441 }
442
443 /*
444 * Get the address of the instruction at the time of the machine check
445 * error.
446 */
447 static inline void mce_get_rip(struct mce *m, struct pt_regs *regs)
448 {
449
450 if (regs && (m->mcgstatus & (MCG_STATUS_RIPV|MCG_STATUS_EIPV))) {
451 m->ip = regs->ip;
452 m->cs = regs->cs;
453 } else {
454 m->ip = 0;
455 m->cs = 0;
456 }
457 if (rip_msr)
458 m->ip = mce_rdmsrl(rip_msr);
459 }
460
461 #ifdef CONFIG_X86_LOCAL_APIC
462 /*
463 * Called after interrupts have been reenabled again
464 * when a MCE happened during an interrupts off region
465 * in the kernel.
466 */
467 asmlinkage void smp_mce_self_interrupt(struct pt_regs *regs)
468 {
469 ack_APIC_irq();
470 exit_idle();
471 irq_enter();
472 mce_notify_irq();
473 mce_schedule_work();
474 irq_exit();
475 }
476 #endif
477
478 static void mce_report_event(struct pt_regs *regs)
479 {
480 if (regs->flags & (X86_VM_MASK|X86_EFLAGS_IF)) {
481 mce_notify_irq();
482 /*
483 * Triggering the work queue here is just an insurance
484 * policy in case the syscall exit notify handler
485 * doesn't run soon enough or ends up running on the
486 * wrong CPU (can happen when audit sleeps)
487 */
488 mce_schedule_work();
489 return;
490 }
491
492 #ifdef CONFIG_X86_LOCAL_APIC
493 /*
494 * Without APIC do not notify. The event will be picked
495 * up eventually.
496 */
497 if (!cpu_has_apic)
498 return;
499
500 /*
501 * When interrupts are disabled we cannot use
502 * kernel services safely. Trigger an self interrupt
503 * through the APIC to instead do the notification
504 * after interrupts are reenabled again.
505 */
506 apic->send_IPI_self(MCE_SELF_VECTOR);
507
508 /*
509 * Wait for idle afterwards again so that we don't leave the
510 * APIC in a non idle state because the normal APIC writes
511 * cannot exclude us.
512 */
513 apic_wait_icr_idle();
514 #endif
515 }
516
517 DEFINE_PER_CPU(unsigned, mce_poll_count);
518
519 /*
520 * Poll for corrected events or events that happened before reset.
521 * Those are just logged through /dev/mcelog.
522 *
523 * This is executed in standard interrupt context.
524 *
525 * Note: spec recommends to panic for fatal unsignalled
526 * errors here. However this would be quite problematic --
527 * we would need to reimplement the Monarch handling and
528 * it would mess up the exclusion between exception handler
529 * and poll hander -- * so we skip this for now.
530 * These cases should not happen anyways, or only when the CPU
531 * is already totally * confused. In this case it's likely it will
532 * not fully execute the machine check handler either.
533 */
534 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
535 {
536 struct mce m;
537 int i;
538
539 __get_cpu_var(mce_poll_count)++;
540
541 mce_setup(&m);
542
543 m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
544 for (i = 0; i < banks; i++) {
545 if (!mce_banks[i].ctl || !test_bit(i, *b))
546 continue;
547
548 m.misc = 0;
549 m.addr = 0;
550 m.bank = i;
551 m.tsc = 0;
552
553 barrier();
554 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
555 if (!(m.status & MCI_STATUS_VAL))
556 continue;
557
558 /*
559 * Uncorrected or signalled events are handled by the exception
560 * handler when it is enabled, so don't process those here.
561 *
562 * TBD do the same check for MCI_STATUS_EN here?
563 */
564 if (!(flags & MCP_UC) &&
565 (m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)))
566 continue;
567
568 if (m.status & MCI_STATUS_MISCV)
569 m.misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
570 if (m.status & MCI_STATUS_ADDRV)
571 m.addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
572
573 if (!(flags & MCP_TIMESTAMP))
574 m.tsc = 0;
575 /*
576 * Don't get the IP here because it's unlikely to
577 * have anything to do with the actual error location.
578 */
579 if (!(flags & MCP_DONTLOG) && !mce_dont_log_ce) {
580 mce_log(&m);
581 add_taint(TAINT_MACHINE_CHECK);
582 }
583
584 /*
585 * Clear state for this bank.
586 */
587 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
588 }
589
590 /*
591 * Don't clear MCG_STATUS here because it's only defined for
592 * exceptions.
593 */
594
595 sync_core();
596 }
597 EXPORT_SYMBOL_GPL(machine_check_poll);
598
599 /*
600 * Do a quick check if any of the events requires a panic.
601 * This decides if we keep the events around or clear them.
602 */
603 static int mce_no_way_out(struct mce *m, char **msg)
604 {
605 int i;
606
607 for (i = 0; i < banks; i++) {
608 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
609 if (mce_severity(m, tolerant, msg) >= MCE_PANIC_SEVERITY)
610 return 1;
611 }
612 return 0;
613 }
614
615 /*
616 * Variable to establish order between CPUs while scanning.
617 * Each CPU spins initially until executing is equal its number.
618 */
619 static atomic_t mce_executing;
620
621 /*
622 * Defines order of CPUs on entry. First CPU becomes Monarch.
623 */
624 static atomic_t mce_callin;
625
626 /*
627 * Check if a timeout waiting for other CPUs happened.
628 */
629 static int mce_timed_out(u64 *t)
630 {
631 /*
632 * The others already did panic for some reason.
633 * Bail out like in a timeout.
634 * rmb() to tell the compiler that system_state
635 * might have been modified by someone else.
636 */
637 rmb();
638 if (atomic_read(&mce_paniced))
639 wait_for_panic();
640 if (!monarch_timeout)
641 goto out;
642 if ((s64)*t < SPINUNIT) {
643 /* CHECKME: Make panic default for 1 too? */
644 if (tolerant < 1)
645 mce_panic("Timeout synchronizing machine check over CPUs",
646 NULL, NULL);
647 cpu_missing = 1;
648 return 1;
649 }
650 *t -= SPINUNIT;
651 out:
652 touch_nmi_watchdog();
653 return 0;
654 }
655
656 /*
657 * The Monarch's reign. The Monarch is the CPU who entered
658 * the machine check handler first. It waits for the others to
659 * raise the exception too and then grades them. When any
660 * error is fatal panic. Only then let the others continue.
661 *
662 * The other CPUs entering the MCE handler will be controlled by the
663 * Monarch. They are called Subjects.
664 *
665 * This way we prevent any potential data corruption in a unrecoverable case
666 * and also makes sure always all CPU's errors are examined.
667 *
668 * Also this detects the case of a machine check event coming from outer
669 * space (not detected by any CPUs) In this case some external agent wants
670 * us to shut down, so panic too.
671 *
672 * The other CPUs might still decide to panic if the handler happens
673 * in a unrecoverable place, but in this case the system is in a semi-stable
674 * state and won't corrupt anything by itself. It's ok to let the others
675 * continue for a bit first.
676 *
677 * All the spin loops have timeouts; when a timeout happens a CPU
678 * typically elects itself to be Monarch.
679 */
680 static void mce_reign(void)
681 {
682 int cpu;
683 struct mce *m = NULL;
684 int global_worst = 0;
685 char *msg = NULL;
686 char *nmsg = NULL;
687
688 /*
689 * This CPU is the Monarch and the other CPUs have run
690 * through their handlers.
691 * Grade the severity of the errors of all the CPUs.
692 */
693 for_each_possible_cpu(cpu) {
694 int severity = mce_severity(&per_cpu(mces_seen, cpu), tolerant,
695 &nmsg);
696 if (severity > global_worst) {
697 msg = nmsg;
698 global_worst = severity;
699 m = &per_cpu(mces_seen, cpu);
700 }
701 }
702
703 /*
704 * Cannot recover? Panic here then.
705 * This dumps all the mces in the log buffer and stops the
706 * other CPUs.
707 */
708 if (m && global_worst >= MCE_PANIC_SEVERITY && tolerant < 3)
709 mce_panic("Fatal Machine check", m, msg);
710
711 /*
712 * For UC somewhere we let the CPU who detects it handle it.
713 * Also must let continue the others, otherwise the handling
714 * CPU could deadlock on a lock.
715 */
716
717 /*
718 * No machine check event found. Must be some external
719 * source or one CPU is hung. Panic.
720 */
721 if (global_worst <= MCE_KEEP_SEVERITY && tolerant < 3)
722 mce_panic("Machine check from unknown source", NULL, NULL);
723
724 /*
725 * Now clear all the mces_seen so that they don't reappear on
726 * the next mce.
727 */
728 for_each_possible_cpu(cpu)
729 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
730 }
731
732 static atomic_t global_nwo;
733
734 /*
735 * Start of Monarch synchronization. This waits until all CPUs have
736 * entered the exception handler and then determines if any of them
737 * saw a fatal event that requires panic. Then it executes them
738 * in the entry order.
739 * TBD double check parallel CPU hotunplug
740 */
741 static int mce_start(int *no_way_out)
742 {
743 int order;
744 int cpus = num_online_cpus();
745 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
746
747 if (!timeout)
748 return -1;
749
750 atomic_add(*no_way_out, &global_nwo);
751 /*
752 * global_nwo should be updated before mce_callin
753 */
754 smp_wmb();
755 order = atomic_inc_return(&mce_callin);
756
757 /*
758 * Wait for everyone.
759 */
760 while (atomic_read(&mce_callin) != cpus) {
761 if (mce_timed_out(&timeout)) {
762 atomic_set(&global_nwo, 0);
763 return -1;
764 }
765 ndelay(SPINUNIT);
766 }
767
768 /*
769 * mce_callin should be read before global_nwo
770 */
771 smp_rmb();
772
773 if (order == 1) {
774 /*
775 * Monarch: Starts executing now, the others wait.
776 */
777 atomic_set(&mce_executing, 1);
778 } else {
779 /*
780 * Subject: Now start the scanning loop one by one in
781 * the original callin order.
782 * This way when there are any shared banks it will be
783 * only seen by one CPU before cleared, avoiding duplicates.
784 */
785 while (atomic_read(&mce_executing) < order) {
786 if (mce_timed_out(&timeout)) {
787 atomic_set(&global_nwo, 0);
788 return -1;
789 }
790 ndelay(SPINUNIT);
791 }
792 }
793
794 /*
795 * Cache the global no_way_out state.
796 */
797 *no_way_out = atomic_read(&global_nwo);
798
799 return order;
800 }
801
802 /*
803 * Synchronize between CPUs after main scanning loop.
804 * This invokes the bulk of the Monarch processing.
805 */
806 static int mce_end(int order)
807 {
808 int ret = -1;
809 u64 timeout = (u64)monarch_timeout * NSEC_PER_USEC;
810
811 if (!timeout)
812 goto reset;
813 if (order < 0)
814 goto reset;
815
816 /*
817 * Allow others to run.
818 */
819 atomic_inc(&mce_executing);
820
821 if (order == 1) {
822 /* CHECKME: Can this race with a parallel hotplug? */
823 int cpus = num_online_cpus();
824
825 /*
826 * Monarch: Wait for everyone to go through their scanning
827 * loops.
828 */
829 while (atomic_read(&mce_executing) <= cpus) {
830 if (mce_timed_out(&timeout))
831 goto reset;
832 ndelay(SPINUNIT);
833 }
834
835 mce_reign();
836 barrier();
837 ret = 0;
838 } else {
839 /*
840 * Subject: Wait for Monarch to finish.
841 */
842 while (atomic_read(&mce_executing) != 0) {
843 if (mce_timed_out(&timeout))
844 goto reset;
845 ndelay(SPINUNIT);
846 }
847
848 /*
849 * Don't reset anything. That's done by the Monarch.
850 */
851 return 0;
852 }
853
854 /*
855 * Reset all global state.
856 */
857 reset:
858 atomic_set(&global_nwo, 0);
859 atomic_set(&mce_callin, 0);
860 barrier();
861
862 /*
863 * Let others run again.
864 */
865 atomic_set(&mce_executing, 0);
866 return ret;
867 }
868
869 /*
870 * Check if the address reported by the CPU is in a format we can parse.
871 * It would be possible to add code for most other cases, but all would
872 * be somewhat complicated (e.g. segment offset would require an instruction
873 * parser). So only support physical addresses upto page granuality for now.
874 */
875 static int mce_usable_address(struct mce *m)
876 {
877 if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
878 return 0;
879 if ((m->misc & 0x3f) > PAGE_SHIFT)
880 return 0;
881 if (((m->misc >> 6) & 7) != MCM_ADDR_PHYS)
882 return 0;
883 return 1;
884 }
885
886 static void mce_clear_state(unsigned long *toclear)
887 {
888 int i;
889
890 for (i = 0; i < banks; i++) {
891 if (test_bit(i, toclear))
892 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
893 }
894 }
895
896 /*
897 * The actual machine check handler. This only handles real
898 * exceptions when something got corrupted coming in through int 18.
899 *
900 * This is executed in NMI context not subject to normal locking rules. This
901 * implies that most kernel services cannot be safely used. Don't even
902 * think about putting a printk in there!
903 *
904 * On Intel systems this is entered on all CPUs in parallel through
905 * MCE broadcast. However some CPUs might be broken beyond repair,
906 * so be always careful when synchronizing with others.
907 */
908 void do_machine_check(struct pt_regs *regs, long error_code)
909 {
910 struct mce m, *final;
911 int i;
912 int worst = 0;
913 int severity;
914 /*
915 * Establish sequential order between the CPUs entering the machine
916 * check handler.
917 */
918 int order;
919 /*
920 * If no_way_out gets set, there is no safe way to recover from this
921 * MCE. If tolerant is cranked up, we'll try anyway.
922 */
923 int no_way_out = 0;
924 /*
925 * If kill_it gets set, there might be a way to recover from this
926 * error.
927 */
928 int kill_it = 0;
929 DECLARE_BITMAP(toclear, MAX_NR_BANKS);
930 char *msg = "Unknown";
931
932 atomic_inc(&mce_entry);
933
934 __get_cpu_var(mce_exception_count)++;
935
936 if (notify_die(DIE_NMI, "machine check", regs, error_code,
937 18, SIGKILL) == NOTIFY_STOP)
938 goto out;
939 if (!banks)
940 goto out;
941
942 mce_setup(&m);
943
944 m.mcgstatus = mce_rdmsrl(MSR_IA32_MCG_STATUS);
945 final = &__get_cpu_var(mces_seen);
946 *final = m;
947
948 no_way_out = mce_no_way_out(&m, &msg);
949
950 barrier();
951
952 /*
953 * When no restart IP must always kill or panic.
954 */
955 if (!(m.mcgstatus & MCG_STATUS_RIPV))
956 kill_it = 1;
957
958 /*
959 * Go through all the banks in exclusion of the other CPUs.
960 * This way we don't report duplicated events on shared banks
961 * because the first one to see it will clear it.
962 */
963 order = mce_start(&no_way_out);
964 for (i = 0; i < banks; i++) {
965 __clear_bit(i, toclear);
966 if (!mce_banks[i].ctl)
967 continue;
968
969 m.misc = 0;
970 m.addr = 0;
971 m.bank = i;
972
973 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
974 if ((m.status & MCI_STATUS_VAL) == 0)
975 continue;
976
977 /*
978 * Non uncorrected or non signaled errors are handled by
979 * machine_check_poll. Leave them alone, unless this panics.
980 */
981 if (!(m.status & (mce_ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
982 !no_way_out)
983 continue;
984
985 /*
986 * Set taint even when machine check was not enabled.
987 */
988 add_taint(TAINT_MACHINE_CHECK);
989
990 severity = mce_severity(&m, tolerant, NULL);
991
992 /*
993 * When machine check was for corrected handler don't touch,
994 * unless we're panicing.
995 */
996 if (severity == MCE_KEEP_SEVERITY && !no_way_out)
997 continue;
998 __set_bit(i, toclear);
999 if (severity == MCE_NO_SEVERITY) {
1000 /*
1001 * Machine check event was not enabled. Clear, but
1002 * ignore.
1003 */
1004 continue;
1005 }
1006
1007 /*
1008 * Kill on action required.
1009 */
1010 if (severity == MCE_AR_SEVERITY)
1011 kill_it = 1;
1012
1013 if (m.status & MCI_STATUS_MISCV)
1014 m.misc = mce_rdmsrl(MSR_IA32_MCx_MISC(i));
1015 if (m.status & MCI_STATUS_ADDRV)
1016 m.addr = mce_rdmsrl(MSR_IA32_MCx_ADDR(i));
1017
1018 /*
1019 * Action optional error. Queue address for later processing.
1020 * When the ring overflows we just ignore the AO error.
1021 * RED-PEN add some logging mechanism when
1022 * usable_address or mce_add_ring fails.
1023 * RED-PEN don't ignore overflow for tolerant == 0
1024 */
1025 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1026 mce_ring_add(m.addr >> PAGE_SHIFT);
1027
1028 mce_get_rip(&m, regs);
1029 mce_log(&m);
1030
1031 if (severity > worst) {
1032 *final = m;
1033 worst = severity;
1034 }
1035 }
1036
1037 if (!no_way_out)
1038 mce_clear_state(toclear);
1039
1040 /*
1041 * Do most of the synchronization with other CPUs.
1042 * When there's any problem use only local no_way_out state.
1043 */
1044 if (mce_end(order) < 0)
1045 no_way_out = worst >= MCE_PANIC_SEVERITY;
1046
1047 /*
1048 * If we have decided that we just CAN'T continue, and the user
1049 * has not set tolerant to an insane level, give up and die.
1050 *
1051 * This is mainly used in the case when the system doesn't
1052 * support MCE broadcasting or it has been disabled.
1053 */
1054 if (no_way_out && tolerant < 3)
1055 mce_panic("Fatal machine check on current CPU", final, msg);
1056
1057 /*
1058 * If the error seems to be unrecoverable, something should be
1059 * done. Try to kill as little as possible. If we can kill just
1060 * one task, do that. If the user has set the tolerance very
1061 * high, don't try to do anything at all.
1062 */
1063
1064 if (kill_it && tolerant < 3)
1065 force_sig(SIGBUS, current);
1066
1067 /* notify userspace ASAP */
1068 set_thread_flag(TIF_MCE_NOTIFY);
1069
1070 if (worst > 0)
1071 mce_report_event(regs);
1072 mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1073 out:
1074 atomic_dec(&mce_entry);
1075 sync_core();
1076 }
1077 EXPORT_SYMBOL_GPL(do_machine_check);
1078
1079 /* dummy to break dependency. actual code is in mm/memory-failure.c */
1080 void __attribute__((weak)) memory_failure(unsigned long pfn, int vector)
1081 {
1082 printk(KERN_ERR "Action optional memory failure at %lx ignored\n", pfn);
1083 }
1084
1085 /*
1086 * Called after mce notification in process context. This code
1087 * is allowed to sleep. Call the high level VM handler to process
1088 * any corrupted pages.
1089 * Assume that the work queue code only calls this one at a time
1090 * per CPU.
1091 * Note we don't disable preemption, so this code might run on the wrong
1092 * CPU. In this case the event is picked up by the scheduled work queue.
1093 * This is merely a fast path to expedite processing in some common
1094 * cases.
1095 */
1096 void mce_notify_process(void)
1097 {
1098 unsigned long pfn;
1099 mce_notify_irq();
1100 while (mce_ring_get(&pfn))
1101 memory_failure(pfn, MCE_VECTOR);
1102 }
1103
1104 static void mce_process_work(struct work_struct *dummy)
1105 {
1106 mce_notify_process();
1107 }
1108
1109 #ifdef CONFIG_X86_MCE_INTEL
1110 /***
1111 * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1112 * @cpu: The CPU on which the event occurred.
1113 * @status: Event status information
1114 *
1115 * This function should be called by the thermal interrupt after the
1116 * event has been processed and the decision was made to log the event
1117 * further.
1118 *
1119 * The status parameter will be saved to the 'status' field of 'struct mce'
1120 * and historically has been the register value of the
1121 * MSR_IA32_THERMAL_STATUS (Intel) msr.
1122 */
1123 void mce_log_therm_throt_event(__u64 status)
1124 {
1125 struct mce m;
1126
1127 mce_setup(&m);
1128 m.bank = MCE_THERMAL_BANK;
1129 m.status = status;
1130 mce_log(&m);
1131 }
1132 #endif /* CONFIG_X86_MCE_INTEL */
1133
1134 /*
1135 * Periodic polling timer for "silent" machine check errors. If the
1136 * poller finds an MCE, poll 2x faster. When the poller finds no more
1137 * errors, poll 2x slower (up to check_interval seconds).
1138 */
1139 static int check_interval = 5 * 60; /* 5 minutes */
1140
1141 static DEFINE_PER_CPU(int, mce_next_interval); /* in jiffies */
1142 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1143
1144 static void mce_start_timer(unsigned long data)
1145 {
1146 struct timer_list *t = &per_cpu(mce_timer, data);
1147 int *n;
1148
1149 WARN_ON(smp_processor_id() != data);
1150
1151 if (mce_available(&current_cpu_data)) {
1152 machine_check_poll(MCP_TIMESTAMP,
1153 &__get_cpu_var(mce_poll_banks));
1154 }
1155
1156 /*
1157 * Alert userspace if needed. If we logged an MCE, reduce the
1158 * polling interval, otherwise increase the polling interval.
1159 */
1160 n = &__get_cpu_var(mce_next_interval);
1161 if (mce_notify_irq())
1162 *n = max(*n/2, HZ/100);
1163 else
1164 *n = min(*n*2, (int)round_jiffies_relative(check_interval*HZ));
1165
1166 t->expires = jiffies + *n;
1167 add_timer_on(t, smp_processor_id());
1168 }
1169
1170 static void mce_do_trigger(struct work_struct *work)
1171 {
1172 call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1173 }
1174
1175 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1176
1177 /*
1178 * Notify the user(s) about new machine check events.
1179 * Can be called from interrupt context, but not from machine check/NMI
1180 * context.
1181 */
1182 int mce_notify_irq(void)
1183 {
1184 /* Not more than two messages every minute */
1185 static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1186
1187 clear_thread_flag(TIF_MCE_NOTIFY);
1188
1189 if (test_and_clear_bit(0, &mce_need_notify)) {
1190 wake_up_interruptible(&mce_wait);
1191
1192 /*
1193 * There is no risk of missing notifications because
1194 * work_pending is always cleared before the function is
1195 * executed.
1196 */
1197 if (mce_helper[0] && !work_pending(&mce_trigger_work))
1198 schedule_work(&mce_trigger_work);
1199
1200 if (__ratelimit(&ratelimit))
1201 printk(KERN_INFO "Machine check events logged\n");
1202
1203 return 1;
1204 }
1205 return 0;
1206 }
1207 EXPORT_SYMBOL_GPL(mce_notify_irq);
1208
1209 static int __cpuinit __mcheck_cpu_mce_banks_init(void)
1210 {
1211 int i;
1212
1213 mce_banks = kzalloc(banks * sizeof(struct mce_bank), GFP_KERNEL);
1214 if (!mce_banks)
1215 return -ENOMEM;
1216 for (i = 0; i < banks; i++) {
1217 struct mce_bank *b = &mce_banks[i];
1218
1219 b->ctl = -1ULL;
1220 b->init = 1;
1221 }
1222 return 0;
1223 }
1224
1225 /*
1226 * Initialize Machine Checks for a CPU.
1227 */
1228 static int __cpuinit __mcheck_cpu_cap_init(void)
1229 {
1230 unsigned b;
1231 u64 cap;
1232
1233 rdmsrl(MSR_IA32_MCG_CAP, cap);
1234
1235 b = cap & MCG_BANKCNT_MASK;
1236 if (!banks)
1237 printk(KERN_INFO "mce: CPU supports %d MCE banks\n", b);
1238
1239 if (b > MAX_NR_BANKS) {
1240 printk(KERN_WARNING
1241 "MCE: Using only %u machine check banks out of %u\n",
1242 MAX_NR_BANKS, b);
1243 b = MAX_NR_BANKS;
1244 }
1245
1246 /* Don't support asymmetric configurations today */
1247 WARN_ON(banks != 0 && b != banks);
1248 banks = b;
1249 if (!mce_banks) {
1250 int err = __mcheck_cpu_mce_banks_init();
1251
1252 if (err)
1253 return err;
1254 }
1255
1256 /* Use accurate RIP reporting if available. */
1257 if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1258 rip_msr = MSR_IA32_MCG_EIP;
1259
1260 if (cap & MCG_SER_P)
1261 mce_ser = 1;
1262
1263 return 0;
1264 }
1265
1266 static void __mcheck_cpu_init_generic(void)
1267 {
1268 mce_banks_t all_banks;
1269 u64 cap;
1270 int i;
1271
1272 /*
1273 * Log the machine checks left over from the previous reset.
1274 */
1275 bitmap_fill(all_banks, MAX_NR_BANKS);
1276 machine_check_poll(MCP_UC|(!mce_bootlog ? MCP_DONTLOG : 0), &all_banks);
1277
1278 set_in_cr4(X86_CR4_MCE);
1279
1280 rdmsrl(MSR_IA32_MCG_CAP, cap);
1281 if (cap & MCG_CTL_P)
1282 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1283
1284 for (i = 0; i < banks; i++) {
1285 struct mce_bank *b = &mce_banks[i];
1286
1287 if (!b->init)
1288 continue;
1289 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1290 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1291 }
1292 }
1293
1294 /* Add per CPU specific workarounds here */
1295 static int __cpuinit __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1296 {
1297 if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1298 pr_info("MCE: unknown CPU type - not enabling MCE support.\n");
1299 return -EOPNOTSUPP;
1300 }
1301
1302 /* This should be disabled by the BIOS, but isn't always */
1303 if (c->x86_vendor == X86_VENDOR_AMD) {
1304 if (c->x86 == 15 && banks > 4) {
1305 /*
1306 * disable GART TBL walk error reporting, which
1307 * trips off incorrectly with the IOMMU & 3ware
1308 * & Cerberus:
1309 */
1310 clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1311 }
1312 if (c->x86 <= 17 && mce_bootlog < 0) {
1313 /*
1314 * Lots of broken BIOS around that don't clear them
1315 * by default and leave crap in there. Don't log:
1316 */
1317 mce_bootlog = 0;
1318 }
1319 /*
1320 * Various K7s with broken bank 0 around. Always disable
1321 * by default.
1322 */
1323 if (c->x86 == 6 && banks > 0)
1324 mce_banks[0].ctl = 0;
1325 }
1326
1327 if (c->x86_vendor == X86_VENDOR_INTEL) {
1328 /*
1329 * SDM documents that on family 6 bank 0 should not be written
1330 * because it aliases to another special BIOS controlled
1331 * register.
1332 * But it's not aliased anymore on model 0x1a+
1333 * Don't ignore bank 0 completely because there could be a
1334 * valid event later, merely don't write CTL0.
1335 */
1336
1337 if (c->x86 == 6 && c->x86_model < 0x1A && banks > 0)
1338 mce_banks[0].init = 0;
1339
1340 /*
1341 * All newer Intel systems support MCE broadcasting. Enable
1342 * synchronization with a one second timeout.
1343 */
1344 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1345 monarch_timeout < 0)
1346 monarch_timeout = USEC_PER_SEC;
1347
1348 /*
1349 * There are also broken BIOSes on some Pentium M and
1350 * earlier systems:
1351 */
1352 if (c->x86 == 6 && c->x86_model <= 13 && mce_bootlog < 0)
1353 mce_bootlog = 0;
1354 }
1355 if (monarch_timeout < 0)
1356 monarch_timeout = 0;
1357 if (mce_bootlog != 0)
1358 mce_panic_timeout = 30;
1359
1360 return 0;
1361 }
1362
1363 static void __cpuinit __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1364 {
1365 if (c->x86 != 5)
1366 return;
1367 switch (c->x86_vendor) {
1368 case X86_VENDOR_INTEL:
1369 intel_p5_mcheck_init(c);
1370 break;
1371 case X86_VENDOR_CENTAUR:
1372 winchip_mcheck_init(c);
1373 break;
1374 }
1375 }
1376
1377 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1378 {
1379 switch (c->x86_vendor) {
1380 case X86_VENDOR_INTEL:
1381 mce_intel_feature_init(c);
1382 break;
1383 case X86_VENDOR_AMD:
1384 mce_amd_feature_init(c);
1385 break;
1386 default:
1387 break;
1388 }
1389 }
1390
1391 static void __mcheck_cpu_init_timer(void)
1392 {
1393 struct timer_list *t = &__get_cpu_var(mce_timer);
1394 int *n = &__get_cpu_var(mce_next_interval);
1395
1396 setup_timer(t, mce_start_timer, smp_processor_id());
1397
1398 if (mce_ignore_ce)
1399 return;
1400
1401 *n = check_interval * HZ;
1402 if (!*n)
1403 return;
1404 t->expires = round_jiffies(jiffies + *n);
1405 add_timer_on(t, smp_processor_id());
1406 }
1407
1408 /* Handle unconfigured int18 (should never happen) */
1409 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1410 {
1411 printk(KERN_ERR "CPU#%d: Unexpected int18 (Machine Check).\n",
1412 smp_processor_id());
1413 }
1414
1415 /* Call the installed machine check handler for this CPU setup. */
1416 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1417 unexpected_machine_check;
1418
1419 /*
1420 * Called for each booted CPU to set up machine checks.
1421 * Must be called with preempt off:
1422 */
1423 void __cpuinit mcheck_cpu_init(struct cpuinfo_x86 *c)
1424 {
1425 if (mce_disabled)
1426 return;
1427
1428 __mcheck_cpu_ancient_init(c);
1429
1430 if (!mce_available(c))
1431 return;
1432
1433 if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1434 mce_disabled = 1;
1435 return;
1436 }
1437
1438 machine_check_vector = do_machine_check;
1439
1440 __mcheck_cpu_init_generic();
1441 __mcheck_cpu_init_vendor(c);
1442 __mcheck_cpu_init_timer();
1443 INIT_WORK(&__get_cpu_var(mce_work), mce_process_work);
1444
1445 }
1446
1447 /*
1448 * Character device to read and clear the MCE log.
1449 */
1450
1451 static DEFINE_SPINLOCK(mce_state_lock);
1452 static int open_count; /* #times opened */
1453 static int open_exclu; /* already open exclusive? */
1454
1455 static int mce_open(struct inode *inode, struct file *file)
1456 {
1457 spin_lock(&mce_state_lock);
1458
1459 if (open_exclu || (open_count && (file->f_flags & O_EXCL))) {
1460 spin_unlock(&mce_state_lock);
1461
1462 return -EBUSY;
1463 }
1464
1465 if (file->f_flags & O_EXCL)
1466 open_exclu = 1;
1467 open_count++;
1468
1469 spin_unlock(&mce_state_lock);
1470
1471 return nonseekable_open(inode, file);
1472 }
1473
1474 static int mce_release(struct inode *inode, struct file *file)
1475 {
1476 spin_lock(&mce_state_lock);
1477
1478 open_count--;
1479 open_exclu = 0;
1480
1481 spin_unlock(&mce_state_lock);
1482
1483 return 0;
1484 }
1485
1486 static void collect_tscs(void *data)
1487 {
1488 unsigned long *cpu_tsc = (unsigned long *)data;
1489
1490 rdtscll(cpu_tsc[smp_processor_id()]);
1491 }
1492
1493 static DEFINE_MUTEX(mce_read_mutex);
1494
1495 static ssize_t mce_read(struct file *filp, char __user *ubuf, size_t usize,
1496 loff_t *off)
1497 {
1498 char __user *buf = ubuf;
1499 unsigned long *cpu_tsc;
1500 unsigned prev, next;
1501 int i, err;
1502
1503 cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1504 if (!cpu_tsc)
1505 return -ENOMEM;
1506
1507 mutex_lock(&mce_read_mutex);
1508 next = rcu_dereference_check_mce(mcelog.next);
1509
1510 /* Only supports full reads right now */
1511 if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce)) {
1512 mutex_unlock(&mce_read_mutex);
1513 kfree(cpu_tsc);
1514
1515 return -EINVAL;
1516 }
1517
1518 err = 0;
1519 prev = 0;
1520 do {
1521 for (i = prev; i < next; i++) {
1522 unsigned long start = jiffies;
1523
1524 while (!mcelog.entry[i].finished) {
1525 if (time_after_eq(jiffies, start + 2)) {
1526 memset(mcelog.entry + i, 0,
1527 sizeof(struct mce));
1528 goto timeout;
1529 }
1530 cpu_relax();
1531 }
1532 smp_rmb();
1533 err |= copy_to_user(buf, mcelog.entry + i,
1534 sizeof(struct mce));
1535 buf += sizeof(struct mce);
1536 timeout:
1537 ;
1538 }
1539
1540 memset(mcelog.entry + prev, 0,
1541 (next - prev) * sizeof(struct mce));
1542 prev = next;
1543 next = cmpxchg(&mcelog.next, prev, 0);
1544 } while (next != prev);
1545
1546 synchronize_sched();
1547
1548 /*
1549 * Collect entries that were still getting written before the
1550 * synchronize.
1551 */
1552 on_each_cpu(collect_tscs, cpu_tsc, 1);
1553
1554 for (i = next; i < MCE_LOG_LEN; i++) {
1555 if (mcelog.entry[i].finished &&
1556 mcelog.entry[i].tsc < cpu_tsc[mcelog.entry[i].cpu]) {
1557 err |= copy_to_user(buf, mcelog.entry+i,
1558 sizeof(struct mce));
1559 smp_rmb();
1560 buf += sizeof(struct mce);
1561 memset(&mcelog.entry[i], 0, sizeof(struct mce));
1562 }
1563 }
1564 mutex_unlock(&mce_read_mutex);
1565 kfree(cpu_tsc);
1566
1567 return err ? -EFAULT : buf - ubuf;
1568 }
1569
1570 static unsigned int mce_poll(struct file *file, poll_table *wait)
1571 {
1572 poll_wait(file, &mce_wait, wait);
1573 if (rcu_dereference_check_mce(mcelog.next))
1574 return POLLIN | POLLRDNORM;
1575 return 0;
1576 }
1577
1578 static long mce_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
1579 {
1580 int __user *p = (int __user *)arg;
1581
1582 if (!capable(CAP_SYS_ADMIN))
1583 return -EPERM;
1584
1585 switch (cmd) {
1586 case MCE_GET_RECORD_LEN:
1587 return put_user(sizeof(struct mce), p);
1588 case MCE_GET_LOG_LEN:
1589 return put_user(MCE_LOG_LEN, p);
1590 case MCE_GETCLEAR_FLAGS: {
1591 unsigned flags;
1592
1593 do {
1594 flags = mcelog.flags;
1595 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1596
1597 return put_user(flags, p);
1598 }
1599 default:
1600 return -ENOTTY;
1601 }
1602 }
1603
1604 /* Modified in mce-inject.c, so not static or const */
1605 struct file_operations mce_chrdev_ops = {
1606 .open = mce_open,
1607 .release = mce_release,
1608 .read = mce_read,
1609 .poll = mce_poll,
1610 .unlocked_ioctl = mce_ioctl,
1611 };
1612 EXPORT_SYMBOL_GPL(mce_chrdev_ops);
1613
1614 static struct miscdevice mce_log_device = {
1615 MISC_MCELOG_MINOR,
1616 "mcelog",
1617 &mce_chrdev_ops,
1618 };
1619
1620 /*
1621 * mce=off Disables machine check
1622 * mce=no_cmci Disables CMCI
1623 * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1624 * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1625 * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1626 * monarchtimeout is how long to wait for other CPUs on machine
1627 * check, or 0 to not wait
1628 * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1629 * mce=nobootlog Don't log MCEs from before booting.
1630 */
1631 static int __init mcheck_enable(char *str)
1632 {
1633 if (*str == 0) {
1634 enable_p5_mce();
1635 return 1;
1636 }
1637 if (*str == '=')
1638 str++;
1639 if (!strcmp(str, "off"))
1640 mce_disabled = 1;
1641 else if (!strcmp(str, "no_cmci"))
1642 mce_cmci_disabled = 1;
1643 else if (!strcmp(str, "dont_log_ce"))
1644 mce_dont_log_ce = 1;
1645 else if (!strcmp(str, "ignore_ce"))
1646 mce_ignore_ce = 1;
1647 else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
1648 mce_bootlog = (str[0] == 'b');
1649 else if (isdigit(str[0])) {
1650 get_option(&str, &tolerant);
1651 if (*str == ',') {
1652 ++str;
1653 get_option(&str, &monarch_timeout);
1654 }
1655 } else {
1656 printk(KERN_INFO "mce argument %s ignored. Please use /sys\n",
1657 str);
1658 return 0;
1659 }
1660 return 1;
1661 }
1662 __setup("mce", mcheck_enable);
1663
1664 int __init mcheck_init(void)
1665 {
1666 atomic_notifier_chain_register(&x86_mce_decoder_chain, &mce_dec_nb);
1667
1668 mcheck_intel_therm_init();
1669
1670 return 0;
1671 }
1672
1673 /*
1674 * Sysfs support
1675 */
1676
1677 /*
1678 * Disable machine checks on suspend and shutdown. We can't really handle
1679 * them later.
1680 */
1681 static int mce_disable_error_reporting(void)
1682 {
1683 int i;
1684
1685 for (i = 0; i < banks; i++) {
1686 struct mce_bank *b = &mce_banks[i];
1687
1688 if (b->init)
1689 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
1690 }
1691 return 0;
1692 }
1693
1694 static int mce_suspend(struct sys_device *dev, pm_message_t state)
1695 {
1696 return mce_disable_error_reporting();
1697 }
1698
1699 static int mce_shutdown(struct sys_device *dev)
1700 {
1701 return mce_disable_error_reporting();
1702 }
1703
1704 /*
1705 * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
1706 * Only one CPU is active at this time, the others get re-added later using
1707 * CPU hotplug:
1708 */
1709 static int mce_resume(struct sys_device *dev)
1710 {
1711 __mcheck_cpu_init_generic();
1712 __mcheck_cpu_init_vendor(&current_cpu_data);
1713
1714 return 0;
1715 }
1716
1717 static void mce_cpu_restart(void *data)
1718 {
1719 del_timer_sync(&__get_cpu_var(mce_timer));
1720 if (!mce_available(&current_cpu_data))
1721 return;
1722 __mcheck_cpu_init_generic();
1723 __mcheck_cpu_init_timer();
1724 }
1725
1726 /* Reinit MCEs after user configuration changes */
1727 static void mce_restart(void)
1728 {
1729 on_each_cpu(mce_cpu_restart, NULL, 1);
1730 }
1731
1732 /* Toggle features for corrected errors */
1733 static void mce_disable_ce(void *all)
1734 {
1735 if (!mce_available(&current_cpu_data))
1736 return;
1737 if (all)
1738 del_timer_sync(&__get_cpu_var(mce_timer));
1739 cmci_clear();
1740 }
1741
1742 static void mce_enable_ce(void *all)
1743 {
1744 if (!mce_available(&current_cpu_data))
1745 return;
1746 cmci_reenable();
1747 cmci_recheck();
1748 if (all)
1749 __mcheck_cpu_init_timer();
1750 }
1751
1752 static struct sysdev_class mce_sysclass = {
1753 .suspend = mce_suspend,
1754 .shutdown = mce_shutdown,
1755 .resume = mce_resume,
1756 .name = "machinecheck",
1757 };
1758
1759 DEFINE_PER_CPU(struct sys_device, mce_dev);
1760
1761 __cpuinitdata
1762 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
1763
1764 static inline struct mce_bank *attr_to_bank(struct sysdev_attribute *attr)
1765 {
1766 return container_of(attr, struct mce_bank, attr);
1767 }
1768
1769 static ssize_t show_bank(struct sys_device *s, struct sysdev_attribute *attr,
1770 char *buf)
1771 {
1772 return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
1773 }
1774
1775 static ssize_t set_bank(struct sys_device *s, struct sysdev_attribute *attr,
1776 const char *buf, size_t size)
1777 {
1778 u64 new;
1779
1780 if (strict_strtoull(buf, 0, &new) < 0)
1781 return -EINVAL;
1782
1783 attr_to_bank(attr)->ctl = new;
1784 mce_restart();
1785
1786 return size;
1787 }
1788
1789 static ssize_t
1790 show_trigger(struct sys_device *s, struct sysdev_attribute *attr, char *buf)
1791 {
1792 strcpy(buf, mce_helper);
1793 strcat(buf, "\n");
1794 return strlen(mce_helper) + 1;
1795 }
1796
1797 static ssize_t set_trigger(struct sys_device *s, struct sysdev_attribute *attr,
1798 const char *buf, size_t siz)
1799 {
1800 char *p;
1801
1802 strncpy(mce_helper, buf, sizeof(mce_helper));
1803 mce_helper[sizeof(mce_helper)-1] = 0;
1804 p = strchr(mce_helper, '\n');
1805
1806 if (p)
1807 *p = 0;
1808
1809 return strlen(mce_helper) + !!p;
1810 }
1811
1812 static ssize_t set_ignore_ce(struct sys_device *s,
1813 struct sysdev_attribute *attr,
1814 const char *buf, size_t size)
1815 {
1816 u64 new;
1817
1818 if (strict_strtoull(buf, 0, &new) < 0)
1819 return -EINVAL;
1820
1821 if (mce_ignore_ce ^ !!new) {
1822 if (new) {
1823 /* disable ce features */
1824 on_each_cpu(mce_disable_ce, (void *)1, 1);
1825 mce_ignore_ce = 1;
1826 } else {
1827 /* enable ce features */
1828 mce_ignore_ce = 0;
1829 on_each_cpu(mce_enable_ce, (void *)1, 1);
1830 }
1831 }
1832 return size;
1833 }
1834
1835 static ssize_t set_cmci_disabled(struct sys_device *s,
1836 struct sysdev_attribute *attr,
1837 const char *buf, size_t size)
1838 {
1839 u64 new;
1840
1841 if (strict_strtoull(buf, 0, &new) < 0)
1842 return -EINVAL;
1843
1844 if (mce_cmci_disabled ^ !!new) {
1845 if (new) {
1846 /* disable cmci */
1847 on_each_cpu(mce_disable_ce, NULL, 1);
1848 mce_cmci_disabled = 1;
1849 } else {
1850 /* enable cmci */
1851 mce_cmci_disabled = 0;
1852 on_each_cpu(mce_enable_ce, NULL, 1);
1853 }
1854 }
1855 return size;
1856 }
1857
1858 static ssize_t store_int_with_restart(struct sys_device *s,
1859 struct sysdev_attribute *attr,
1860 const char *buf, size_t size)
1861 {
1862 ssize_t ret = sysdev_store_int(s, attr, buf, size);
1863 mce_restart();
1864 return ret;
1865 }
1866
1867 static SYSDEV_ATTR(trigger, 0644, show_trigger, set_trigger);
1868 static SYSDEV_INT_ATTR(tolerant, 0644, tolerant);
1869 static SYSDEV_INT_ATTR(monarch_timeout, 0644, monarch_timeout);
1870 static SYSDEV_INT_ATTR(dont_log_ce, 0644, mce_dont_log_ce);
1871
1872 static struct sysdev_ext_attribute attr_check_interval = {
1873 _SYSDEV_ATTR(check_interval, 0644, sysdev_show_int,
1874 store_int_with_restart),
1875 &check_interval
1876 };
1877
1878 static struct sysdev_ext_attribute attr_ignore_ce = {
1879 _SYSDEV_ATTR(ignore_ce, 0644, sysdev_show_int, set_ignore_ce),
1880 &mce_ignore_ce
1881 };
1882
1883 static struct sysdev_ext_attribute attr_cmci_disabled = {
1884 _SYSDEV_ATTR(cmci_disabled, 0644, sysdev_show_int, set_cmci_disabled),
1885 &mce_cmci_disabled
1886 };
1887
1888 static struct sysdev_attribute *mce_attrs[] = {
1889 &attr_tolerant.attr,
1890 &attr_check_interval.attr,
1891 &attr_trigger,
1892 &attr_monarch_timeout.attr,
1893 &attr_dont_log_ce.attr,
1894 &attr_ignore_ce.attr,
1895 &attr_cmci_disabled.attr,
1896 NULL
1897 };
1898
1899 static cpumask_var_t mce_dev_initialized;
1900
1901 /* Per cpu sysdev init. All of the cpus still share the same ctrl bank: */
1902 static __cpuinit int mce_create_device(unsigned int cpu)
1903 {
1904 int err;
1905 int i, j;
1906
1907 if (!mce_available(&boot_cpu_data))
1908 return -EIO;
1909
1910 memset(&per_cpu(mce_dev, cpu).kobj, 0, sizeof(struct kobject));
1911 per_cpu(mce_dev, cpu).id = cpu;
1912 per_cpu(mce_dev, cpu).cls = &mce_sysclass;
1913
1914 err = sysdev_register(&per_cpu(mce_dev, cpu));
1915 if (err)
1916 return err;
1917
1918 for (i = 0; mce_attrs[i]; i++) {
1919 err = sysdev_create_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1920 if (err)
1921 goto error;
1922 }
1923 for (j = 0; j < banks; j++) {
1924 err = sysdev_create_file(&per_cpu(mce_dev, cpu),
1925 &mce_banks[j].attr);
1926 if (err)
1927 goto error2;
1928 }
1929 cpumask_set_cpu(cpu, mce_dev_initialized);
1930
1931 return 0;
1932 error2:
1933 while (--j >= 0)
1934 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[j].attr);
1935 error:
1936 while (--i >= 0)
1937 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1938
1939 sysdev_unregister(&per_cpu(mce_dev, cpu));
1940
1941 return err;
1942 }
1943
1944 static __cpuinit void mce_remove_device(unsigned int cpu)
1945 {
1946 int i;
1947
1948 if (!cpumask_test_cpu(cpu, mce_dev_initialized))
1949 return;
1950
1951 for (i = 0; mce_attrs[i]; i++)
1952 sysdev_remove_file(&per_cpu(mce_dev, cpu), mce_attrs[i]);
1953
1954 for (i = 0; i < banks; i++)
1955 sysdev_remove_file(&per_cpu(mce_dev, cpu), &mce_banks[i].attr);
1956
1957 sysdev_unregister(&per_cpu(mce_dev, cpu));
1958 cpumask_clear_cpu(cpu, mce_dev_initialized);
1959 }
1960
1961 /* Make sure there are no machine checks on offlined CPUs. */
1962 static void __cpuinit mce_disable_cpu(void *h)
1963 {
1964 unsigned long action = *(unsigned long *)h;
1965 int i;
1966
1967 if (!mce_available(&current_cpu_data))
1968 return;
1969
1970 if (!(action & CPU_TASKS_FROZEN))
1971 cmci_clear();
1972 for (i = 0; i < banks; i++) {
1973 struct mce_bank *b = &mce_banks[i];
1974
1975 if (b->init)
1976 wrmsrl(MSR_IA32_MCx_CTL(i), 0);
1977 }
1978 }
1979
1980 static void __cpuinit mce_reenable_cpu(void *h)
1981 {
1982 unsigned long action = *(unsigned long *)h;
1983 int i;
1984
1985 if (!mce_available(&current_cpu_data))
1986 return;
1987
1988 if (!(action & CPU_TASKS_FROZEN))
1989 cmci_reenable();
1990 for (i = 0; i < banks; i++) {
1991 struct mce_bank *b = &mce_banks[i];
1992
1993 if (b->init)
1994 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1995 }
1996 }
1997
1998 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
1999 static int __cpuinit
2000 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2001 {
2002 unsigned int cpu = (unsigned long)hcpu;
2003 struct timer_list *t = &per_cpu(mce_timer, cpu);
2004
2005 switch (action) {
2006 case CPU_ONLINE:
2007 case CPU_ONLINE_FROZEN:
2008 mce_create_device(cpu);
2009 if (threshold_cpu_callback)
2010 threshold_cpu_callback(action, cpu);
2011 break;
2012 case CPU_DEAD:
2013 case CPU_DEAD_FROZEN:
2014 if (threshold_cpu_callback)
2015 threshold_cpu_callback(action, cpu);
2016 mce_remove_device(cpu);
2017 break;
2018 case CPU_DOWN_PREPARE:
2019 case CPU_DOWN_PREPARE_FROZEN:
2020 del_timer_sync(t);
2021 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2022 break;
2023 case CPU_DOWN_FAILED:
2024 case CPU_DOWN_FAILED_FROZEN:
2025 if (!mce_ignore_ce && check_interval) {
2026 t->expires = round_jiffies(jiffies +
2027 __get_cpu_var(mce_next_interval));
2028 add_timer_on(t, cpu);
2029 }
2030 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2031 break;
2032 case CPU_POST_DEAD:
2033 /* intentionally ignoring frozen here */
2034 cmci_rediscover(cpu);
2035 break;
2036 }
2037 return NOTIFY_OK;
2038 }
2039
2040 static struct notifier_block mce_cpu_notifier __cpuinitdata = {
2041 .notifier_call = mce_cpu_callback,
2042 };
2043
2044 static __init void mce_init_banks(void)
2045 {
2046 int i;
2047
2048 for (i = 0; i < banks; i++) {
2049 struct mce_bank *b = &mce_banks[i];
2050 struct sysdev_attribute *a = &b->attr;
2051
2052 sysfs_attr_init(&a->attr);
2053 a->attr.name = b->attrname;
2054 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2055
2056 a->attr.mode = 0644;
2057 a->show = show_bank;
2058 a->store = set_bank;
2059 }
2060 }
2061
2062 static __init int mcheck_init_device(void)
2063 {
2064 int err;
2065 int i = 0;
2066
2067 if (!mce_available(&boot_cpu_data))
2068 return -EIO;
2069
2070 zalloc_cpumask_var(&mce_dev_initialized, GFP_KERNEL);
2071
2072 mce_init_banks();
2073
2074 err = sysdev_class_register(&mce_sysclass);
2075 if (err)
2076 return err;
2077
2078 for_each_online_cpu(i) {
2079 err = mce_create_device(i);
2080 if (err)
2081 return err;
2082 }
2083
2084 register_hotcpu_notifier(&mce_cpu_notifier);
2085 misc_register(&mce_log_device);
2086
2087 return err;
2088 }
2089
2090 device_initcall(mcheck_init_device);
2091
2092 /*
2093 * Old style boot options parsing. Only for compatibility.
2094 */
2095 static int __init mcheck_disable(char *str)
2096 {
2097 mce_disabled = 1;
2098 return 1;
2099 }
2100 __setup("nomce", mcheck_disable);
2101
2102 #ifdef CONFIG_DEBUG_FS
2103 struct dentry *mce_get_debugfs_dir(void)
2104 {
2105 static struct dentry *dmce;
2106
2107 if (!dmce)
2108 dmce = debugfs_create_dir("mce", NULL);
2109
2110 return dmce;
2111 }
2112
2113 static void mce_reset(void)
2114 {
2115 cpu_missing = 0;
2116 atomic_set(&mce_fake_paniced, 0);
2117 atomic_set(&mce_executing, 0);
2118 atomic_set(&mce_callin, 0);
2119 atomic_set(&global_nwo, 0);
2120 }
2121
2122 static int fake_panic_get(void *data, u64 *val)
2123 {
2124 *val = fake_panic;
2125 return 0;
2126 }
2127
2128 static int fake_panic_set(void *data, u64 val)
2129 {
2130 mce_reset();
2131 fake_panic = val;
2132 return 0;
2133 }
2134
2135 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2136 fake_panic_set, "%llu\n");
2137
2138 static int __init mcheck_debugfs_init(void)
2139 {
2140 struct dentry *dmce, *ffake_panic;
2141
2142 dmce = mce_get_debugfs_dir();
2143 if (!dmce)
2144 return -ENOMEM;
2145 ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2146 &fake_panic_fops);
2147 if (!ffake_panic)
2148 return -ENOMEM;
2149
2150 return 0;
2151 }
2152 late_initcall(mcheck_debugfs_init);
2153 #endif