OSDN Git Service

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