]> git.samba.org - sfrench/cifs-2.6.git/blob - arch/x86/kernel/cpu/mcheck/mce.c
Merge branches 'acpi-ec', 'acpi-soc', 'acpi-video' and 'acpi-resources'
[sfrench/cifs-2.6.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/traps.h>
47 #include <asm/tlbflush.h>
48 #include <asm/mce.h>
49 #include <asm/msr.h>
50
51 #include "mce-internal.h"
52
53 static DEFINE_MUTEX(mce_chrdev_read_mutex);
54
55 #define rcu_dereference_check_mce(p) \
56         rcu_dereference_index_check((p), \
57                               rcu_read_lock_sched_held() || \
58                               lockdep_is_held(&mce_chrdev_read_mutex))
59
60 #define CREATE_TRACE_POINTS
61 #include <trace/events/mce.h>
62
63 #define SPINUNIT 100    /* 100ns */
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 static 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_panicked;
298
299 static int fake_panic;
300 static atomic_t mce_fake_panicked;
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(const 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_panicked) > 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_panicked) > 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 *)this_cpu_ptr(&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 *)this_cpu_ptr(&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 = this_cpu_ptr(&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 = this_cpu_ptr(&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 = this_cpu_ptr(&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(this_cpu_ptr(&mce_work));
532 }
533
534 static 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(this_cpu_ptr(&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 static bool memory_error(struct mce *m)
581 {
582         struct cpuinfo_x86 *c = &boot_cpu_data;
583
584         if (c->x86_vendor == X86_VENDOR_AMD) {
585                 /*
586                  * coming soon
587                  */
588                 return false;
589         } else if (c->x86_vendor == X86_VENDOR_INTEL) {
590                 /*
591                  * Intel SDM Volume 3B - 15.9.2 Compound Error Codes
592                  *
593                  * Bit 7 of the MCACOD field of IA32_MCi_STATUS is used for
594                  * indicating a memory error. Bit 8 is used for indicating a
595                  * cache hierarchy error. The combination of bit 2 and bit 3
596                  * is used for indicating a `generic' cache hierarchy error
597                  * But we can't just blindly check the above bits, because if
598                  * bit 11 is set, then it is a bus/interconnect error - and
599                  * either way the above bits just gives more detail on what
600                  * bus/interconnect error happened. Note that bit 12 can be
601                  * ignored, as it's the "filter" bit.
602                  */
603                 return (m->status & 0xef80) == BIT(7) ||
604                        (m->status & 0xef00) == BIT(8) ||
605                        (m->status & 0xeffc) == 0xc;
606         }
607
608         return false;
609 }
610
611 DEFINE_PER_CPU(unsigned, mce_poll_count);
612
613 /*
614  * Poll for corrected events or events that happened before reset.
615  * Those are just logged through /dev/mcelog.
616  *
617  * This is executed in standard interrupt context.
618  *
619  * Note: spec recommends to panic for fatal unsignalled
620  * errors here. However this would be quite problematic --
621  * we would need to reimplement the Monarch handling and
622  * it would mess up the exclusion between exception handler
623  * and poll hander -- * so we skip this for now.
624  * These cases should not happen anyways, or only when the CPU
625  * is already totally * confused. In this case it's likely it will
626  * not fully execute the machine check handler either.
627  */
628 void machine_check_poll(enum mcp_flags flags, mce_banks_t *b)
629 {
630         struct mce m;
631         int severity;
632         int i;
633
634         this_cpu_inc(mce_poll_count);
635
636         mce_gather_info(&m, NULL);
637
638         for (i = 0; i < mca_cfg.banks; i++) {
639                 if (!mce_banks[i].ctl || !test_bit(i, *b))
640                         continue;
641
642                 m.misc = 0;
643                 m.addr = 0;
644                 m.bank = i;
645                 m.tsc = 0;
646
647                 barrier();
648                 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
649                 if (!(m.status & MCI_STATUS_VAL))
650                         continue;
651
652                 this_cpu_write(mce_polled_error, 1);
653                 /*
654                  * Uncorrected or signalled events are handled by the exception
655                  * handler when it is enabled, so don't process those here.
656                  *
657                  * TBD do the same check for MCI_STATUS_EN here?
658                  */
659                 if (!(flags & MCP_UC) &&
660                     (m.status & (mca_cfg.ser ? MCI_STATUS_S : MCI_STATUS_UC)))
661                         continue;
662
663                 mce_read_aux(&m, i);
664
665                 if (!(flags & MCP_TIMESTAMP))
666                         m.tsc = 0;
667
668                 severity = mce_severity(&m, mca_cfg.tolerant, NULL, false);
669
670                 /*
671                  * In the cases where we don't have a valid address after all,
672                  * do not add it into the ring buffer.
673                  */
674                 if (severity == MCE_DEFERRED_SEVERITY && memory_error(&m)) {
675                         if (m.status & MCI_STATUS_ADDRV) {
676                                 mce_ring_add(m.addr >> PAGE_SHIFT);
677                                 mce_schedule_work();
678                         }
679                 }
680
681                 /*
682                  * Don't get the IP here because it's unlikely to
683                  * have anything to do with the actual error location.
684                  */
685                 if (!(flags & MCP_DONTLOG) && !mca_cfg.dont_log_ce)
686                         mce_log(&m);
687
688                 /*
689                  * Clear state for this bank.
690                  */
691                 mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
692         }
693
694         /*
695          * Don't clear MCG_STATUS here because it's only defined for
696          * exceptions.
697          */
698
699         sync_core();
700 }
701 EXPORT_SYMBOL_GPL(machine_check_poll);
702
703 /*
704  * Do a quick check if any of the events requires a panic.
705  * This decides if we keep the events around or clear them.
706  */
707 static int mce_no_way_out(struct mce *m, char **msg, unsigned long *validp,
708                           struct pt_regs *regs)
709 {
710         int i, ret = 0;
711
712         for (i = 0; i < mca_cfg.banks; i++) {
713                 m->status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
714                 if (m->status & MCI_STATUS_VAL) {
715                         __set_bit(i, validp);
716                         if (quirk_no_way_out)
717                                 quirk_no_way_out(i, m, regs);
718                 }
719                 if (mce_severity(m, mca_cfg.tolerant, msg, true) >=
720                     MCE_PANIC_SEVERITY)
721                         ret = 1;
722         }
723         return ret;
724 }
725
726 /*
727  * Variable to establish order between CPUs while scanning.
728  * Each CPU spins initially until executing is equal its number.
729  */
730 static atomic_t mce_executing;
731
732 /*
733  * Defines order of CPUs on entry. First CPU becomes Monarch.
734  */
735 static atomic_t mce_callin;
736
737 /*
738  * Check if a timeout waiting for other CPUs happened.
739  */
740 static int mce_timed_out(u64 *t, const char *msg)
741 {
742         /*
743          * The others already did panic for some reason.
744          * Bail out like in a timeout.
745          * rmb() to tell the compiler that system_state
746          * might have been modified by someone else.
747          */
748         rmb();
749         if (atomic_read(&mce_panicked))
750                 wait_for_panic();
751         if (!mca_cfg.monarch_timeout)
752                 goto out;
753         if ((s64)*t < SPINUNIT) {
754                 if (mca_cfg.tolerant <= 1)
755                         mce_panic(msg, NULL, NULL);
756                 cpu_missing = 1;
757                 return 1;
758         }
759         *t -= SPINUNIT;
760 out:
761         touch_nmi_watchdog();
762         return 0;
763 }
764
765 /*
766  * The Monarch's reign.  The Monarch is the CPU who entered
767  * the machine check handler first. It waits for the others to
768  * raise the exception too and then grades them. When any
769  * error is fatal panic. Only then let the others continue.
770  *
771  * The other CPUs entering the MCE handler will be controlled by the
772  * Monarch. They are called Subjects.
773  *
774  * This way we prevent any potential data corruption in a unrecoverable case
775  * and also makes sure always all CPU's errors are examined.
776  *
777  * Also this detects the case of a machine check event coming from outer
778  * space (not detected by any CPUs) In this case some external agent wants
779  * us to shut down, so panic too.
780  *
781  * The other CPUs might still decide to panic if the handler happens
782  * in a unrecoverable place, but in this case the system is in a semi-stable
783  * state and won't corrupt anything by itself. It's ok to let the others
784  * continue for a bit first.
785  *
786  * All the spin loops have timeouts; when a timeout happens a CPU
787  * typically elects itself to be Monarch.
788  */
789 static void mce_reign(void)
790 {
791         int cpu;
792         struct mce *m = NULL;
793         int global_worst = 0;
794         char *msg = NULL;
795         char *nmsg = NULL;
796
797         /*
798          * This CPU is the Monarch and the other CPUs have run
799          * through their handlers.
800          * Grade the severity of the errors of all the CPUs.
801          */
802         for_each_possible_cpu(cpu) {
803                 int severity = mce_severity(&per_cpu(mces_seen, cpu),
804                                             mca_cfg.tolerant,
805                                             &nmsg, true);
806                 if (severity > global_worst) {
807                         msg = nmsg;
808                         global_worst = severity;
809                         m = &per_cpu(mces_seen, cpu);
810                 }
811         }
812
813         /*
814          * Cannot recover? Panic here then.
815          * This dumps all the mces in the log buffer and stops the
816          * other CPUs.
817          */
818         if (m && global_worst >= MCE_PANIC_SEVERITY && mca_cfg.tolerant < 3)
819                 mce_panic("Fatal Machine check", m, msg);
820
821         /*
822          * For UC somewhere we let the CPU who detects it handle it.
823          * Also must let continue the others, otherwise the handling
824          * CPU could deadlock on a lock.
825          */
826
827         /*
828          * No machine check event found. Must be some external
829          * source or one CPU is hung. Panic.
830          */
831         if (global_worst <= MCE_KEEP_SEVERITY && mca_cfg.tolerant < 3)
832                 mce_panic("Machine check from unknown source", NULL, NULL);
833
834         /*
835          * Now clear all the mces_seen so that they don't reappear on
836          * the next mce.
837          */
838         for_each_possible_cpu(cpu)
839                 memset(&per_cpu(mces_seen, cpu), 0, sizeof(struct mce));
840 }
841
842 static atomic_t global_nwo;
843
844 /*
845  * Start of Monarch synchronization. This waits until all CPUs have
846  * entered the exception handler and then determines if any of them
847  * saw a fatal event that requires panic. Then it executes them
848  * in the entry order.
849  * TBD double check parallel CPU hotunplug
850  */
851 static int mce_start(int *no_way_out)
852 {
853         int order;
854         int cpus = num_online_cpus();
855         u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
856
857         if (!timeout)
858                 return -1;
859
860         atomic_add(*no_way_out, &global_nwo);
861         /*
862          * global_nwo should be updated before mce_callin
863          */
864         smp_wmb();
865         order = atomic_inc_return(&mce_callin);
866
867         /*
868          * Wait for everyone.
869          */
870         while (atomic_read(&mce_callin) != cpus) {
871                 if (mce_timed_out(&timeout,
872                                   "Timeout: Not all CPUs entered broadcast exception handler")) {
873                         atomic_set(&global_nwo, 0);
874                         return -1;
875                 }
876                 ndelay(SPINUNIT);
877         }
878
879         /*
880          * mce_callin should be read before global_nwo
881          */
882         smp_rmb();
883
884         if (order == 1) {
885                 /*
886                  * Monarch: Starts executing now, the others wait.
887                  */
888                 atomic_set(&mce_executing, 1);
889         } else {
890                 /*
891                  * Subject: Now start the scanning loop one by one in
892                  * the original callin order.
893                  * This way when there are any shared banks it will be
894                  * only seen by one CPU before cleared, avoiding duplicates.
895                  */
896                 while (atomic_read(&mce_executing) < order) {
897                         if (mce_timed_out(&timeout,
898                                           "Timeout: Subject CPUs unable to finish machine check processing")) {
899                                 atomic_set(&global_nwo, 0);
900                                 return -1;
901                         }
902                         ndelay(SPINUNIT);
903                 }
904         }
905
906         /*
907          * Cache the global no_way_out state.
908          */
909         *no_way_out = atomic_read(&global_nwo);
910
911         return order;
912 }
913
914 /*
915  * Synchronize between CPUs after main scanning loop.
916  * This invokes the bulk of the Monarch processing.
917  */
918 static int mce_end(int order)
919 {
920         int ret = -1;
921         u64 timeout = (u64)mca_cfg.monarch_timeout * NSEC_PER_USEC;
922
923         if (!timeout)
924                 goto reset;
925         if (order < 0)
926                 goto reset;
927
928         /*
929          * Allow others to run.
930          */
931         atomic_inc(&mce_executing);
932
933         if (order == 1) {
934                 /* CHECKME: Can this race with a parallel hotplug? */
935                 int cpus = num_online_cpus();
936
937                 /*
938                  * Monarch: Wait for everyone to go through their scanning
939                  * loops.
940                  */
941                 while (atomic_read(&mce_executing) <= cpus) {
942                         if (mce_timed_out(&timeout,
943                                           "Timeout: Monarch CPU unable to finish machine check processing"))
944                                 goto reset;
945                         ndelay(SPINUNIT);
946                 }
947
948                 mce_reign();
949                 barrier();
950                 ret = 0;
951         } else {
952                 /*
953                  * Subject: Wait for Monarch to finish.
954                  */
955                 while (atomic_read(&mce_executing) != 0) {
956                         if (mce_timed_out(&timeout,
957                                           "Timeout: Monarch CPU did not finish machine check processing"))
958                                 goto reset;
959                         ndelay(SPINUNIT);
960                 }
961
962                 /*
963                  * Don't reset anything. That's done by the Monarch.
964                  */
965                 return 0;
966         }
967
968         /*
969          * Reset all global state.
970          */
971 reset:
972         atomic_set(&global_nwo, 0);
973         atomic_set(&mce_callin, 0);
974         barrier();
975
976         /*
977          * Let others run again.
978          */
979         atomic_set(&mce_executing, 0);
980         return ret;
981 }
982
983 /*
984  * Check if the address reported by the CPU is in a format we can parse.
985  * It would be possible to add code for most other cases, but all would
986  * be somewhat complicated (e.g. segment offset would require an instruction
987  * parser). So only support physical addresses up to page granuality for now.
988  */
989 static int mce_usable_address(struct mce *m)
990 {
991         if (!(m->status & MCI_STATUS_MISCV) || !(m->status & MCI_STATUS_ADDRV))
992                 return 0;
993         if (MCI_MISC_ADDR_LSB(m->misc) > PAGE_SHIFT)
994                 return 0;
995         if (MCI_MISC_ADDR_MODE(m->misc) != MCI_MISC_ADDR_PHYS)
996                 return 0;
997         return 1;
998 }
999
1000 static void mce_clear_state(unsigned long *toclear)
1001 {
1002         int i;
1003
1004         for (i = 0; i < mca_cfg.banks; i++) {
1005                 if (test_bit(i, toclear))
1006                         mce_wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1007         }
1008 }
1009
1010 /*
1011  * The actual machine check handler. This only handles real
1012  * exceptions when something got corrupted coming in through int 18.
1013  *
1014  * This is executed in NMI context not subject to normal locking rules. This
1015  * implies that most kernel services cannot be safely used. Don't even
1016  * think about putting a printk in there!
1017  *
1018  * On Intel systems this is entered on all CPUs in parallel through
1019  * MCE broadcast. However some CPUs might be broken beyond repair,
1020  * so be always careful when synchronizing with others.
1021  */
1022 void do_machine_check(struct pt_regs *regs, long error_code)
1023 {
1024         struct mca_config *cfg = &mca_cfg;
1025         struct mce m, *final;
1026         enum ctx_state prev_state;
1027         int i;
1028         int worst = 0;
1029         int severity;
1030         /*
1031          * Establish sequential order between the CPUs entering the machine
1032          * check handler.
1033          */
1034         int order;
1035         /*
1036          * If no_way_out gets set, there is no safe way to recover from this
1037          * MCE.  If mca_cfg.tolerant is cranked up, we'll try anyway.
1038          */
1039         int no_way_out = 0;
1040         /*
1041          * If kill_it gets set, there might be a way to recover from this
1042          * error.
1043          */
1044         int kill_it = 0;
1045         DECLARE_BITMAP(toclear, MAX_NR_BANKS);
1046         DECLARE_BITMAP(valid_banks, MAX_NR_BANKS);
1047         char *msg = "Unknown";
1048         u64 recover_paddr = ~0ull;
1049         int flags = MF_ACTION_REQUIRED;
1050
1051         prev_state = ist_enter(regs);
1052
1053         this_cpu_inc(mce_exception_count);
1054
1055         if (!cfg->banks)
1056                 goto out;
1057
1058         mce_gather_info(&m, regs);
1059
1060         final = this_cpu_ptr(&mces_seen);
1061         *final = m;
1062
1063         memset(valid_banks, 0, sizeof(valid_banks));
1064         no_way_out = mce_no_way_out(&m, &msg, valid_banks, regs);
1065
1066         barrier();
1067
1068         /*
1069          * When no restart IP might need to kill or panic.
1070          * Assume the worst for now, but if we find the
1071          * severity is MCE_AR_SEVERITY we have other options.
1072          */
1073         if (!(m.mcgstatus & MCG_STATUS_RIPV))
1074                 kill_it = 1;
1075
1076         /*
1077          * Go through all the banks in exclusion of the other CPUs.
1078          * This way we don't report duplicated events on shared banks
1079          * because the first one to see it will clear it.
1080          */
1081         order = mce_start(&no_way_out);
1082         for (i = 0; i < cfg->banks; i++) {
1083                 __clear_bit(i, toclear);
1084                 if (!test_bit(i, valid_banks))
1085                         continue;
1086                 if (!mce_banks[i].ctl)
1087                         continue;
1088
1089                 m.misc = 0;
1090                 m.addr = 0;
1091                 m.bank = i;
1092
1093                 m.status = mce_rdmsrl(MSR_IA32_MCx_STATUS(i));
1094                 if ((m.status & MCI_STATUS_VAL) == 0)
1095                         continue;
1096
1097                 /*
1098                  * Non uncorrected or non signaled errors are handled by
1099                  * machine_check_poll. Leave them alone, unless this panics.
1100                  */
1101                 if (!(m.status & (cfg->ser ? MCI_STATUS_S : MCI_STATUS_UC)) &&
1102                         !no_way_out)
1103                         continue;
1104
1105                 /*
1106                  * Set taint even when machine check was not enabled.
1107                  */
1108                 add_taint(TAINT_MACHINE_CHECK, LOCKDEP_NOW_UNRELIABLE);
1109
1110                 severity = mce_severity(&m, cfg->tolerant, NULL, true);
1111
1112                 /*
1113                  * When machine check was for corrected/deferred handler don't
1114                  * touch, unless we're panicing.
1115                  */
1116                 if ((severity == MCE_KEEP_SEVERITY ||
1117                      severity == MCE_UCNA_SEVERITY) && !no_way_out)
1118                         continue;
1119                 __set_bit(i, toclear);
1120                 if (severity == MCE_NO_SEVERITY) {
1121                         /*
1122                          * Machine check event was not enabled. Clear, but
1123                          * ignore.
1124                          */
1125                         continue;
1126                 }
1127
1128                 mce_read_aux(&m, i);
1129
1130                 /*
1131                  * Action optional error. Queue address for later processing.
1132                  * When the ring overflows we just ignore the AO error.
1133                  * RED-PEN add some logging mechanism when
1134                  * usable_address or mce_add_ring fails.
1135                  * RED-PEN don't ignore overflow for mca_cfg.tolerant == 0
1136                  */
1137                 if (severity == MCE_AO_SEVERITY && mce_usable_address(&m))
1138                         mce_ring_add(m.addr >> PAGE_SHIFT);
1139
1140                 mce_log(&m);
1141
1142                 if (severity > worst) {
1143                         *final = m;
1144                         worst = severity;
1145                 }
1146         }
1147
1148         /* mce_clear_state will clear *final, save locally for use later */
1149         m = *final;
1150
1151         if (!no_way_out)
1152                 mce_clear_state(toclear);
1153
1154         /*
1155          * Do most of the synchronization with other CPUs.
1156          * When there's any problem use only local no_way_out state.
1157          */
1158         if (mce_end(order) < 0)
1159                 no_way_out = worst >= MCE_PANIC_SEVERITY;
1160
1161         /*
1162          * At insane "tolerant" levels we take no action. Otherwise
1163          * we only die if we have no other choice. For less serious
1164          * issues we try to recover, or limit damage to the current
1165          * process.
1166          */
1167         if (cfg->tolerant < 3) {
1168                 if (no_way_out)
1169                         mce_panic("Fatal machine check on current CPU", &m, msg);
1170                 if (worst == MCE_AR_SEVERITY) {
1171                         recover_paddr = m.addr;
1172                         if (!(m.mcgstatus & MCG_STATUS_RIPV))
1173                                 flags |= MF_MUST_KILL;
1174                 } else if (kill_it) {
1175                         force_sig(SIGBUS, current);
1176                 }
1177         }
1178
1179         if (worst > 0)
1180                 mce_report_event(regs);
1181         mce_wrmsrl(MSR_IA32_MCG_STATUS, 0);
1182 out:
1183         sync_core();
1184
1185         if (recover_paddr == ~0ull)
1186                 goto done;
1187
1188         pr_err("Uncorrected hardware memory error in user-access at %llx",
1189                  recover_paddr);
1190         /*
1191          * We must call memory_failure() here even if the current process is
1192          * doomed. We still need to mark the page as poisoned and alert any
1193          * other users of the page.
1194          */
1195         ist_begin_non_atomic(regs);
1196         local_irq_enable();
1197         if (memory_failure(recover_paddr >> PAGE_SHIFT, MCE_VECTOR, flags) < 0) {
1198                 pr_err("Memory error not recovered");
1199                 force_sig(SIGBUS, current);
1200         }
1201         local_irq_disable();
1202         ist_end_non_atomic();
1203 done:
1204         ist_exit(regs, prev_state);
1205 }
1206 EXPORT_SYMBOL_GPL(do_machine_check);
1207
1208 #ifndef CONFIG_MEMORY_FAILURE
1209 int memory_failure(unsigned long pfn, int vector, int flags)
1210 {
1211         /* mce_severity() should not hand us an ACTION_REQUIRED error */
1212         BUG_ON(flags & MF_ACTION_REQUIRED);
1213         pr_err("Uncorrected memory error in page 0x%lx ignored\n"
1214                "Rebuild kernel with CONFIG_MEMORY_FAILURE=y for smarter handling\n",
1215                pfn);
1216
1217         return 0;
1218 }
1219 #endif
1220
1221 /*
1222  * Action optional processing happens here (picking up
1223  * from the list of faulting pages that do_machine_check()
1224  * placed into the "ring").
1225  */
1226 static void mce_process_work(struct work_struct *dummy)
1227 {
1228         unsigned long pfn;
1229
1230         while (mce_ring_get(&pfn))
1231                 memory_failure(pfn, MCE_VECTOR, 0);
1232 }
1233
1234 #ifdef CONFIG_X86_MCE_INTEL
1235 /***
1236  * mce_log_therm_throt_event - Logs the thermal throttling event to mcelog
1237  * @cpu: The CPU on which the event occurred.
1238  * @status: Event status information
1239  *
1240  * This function should be called by the thermal interrupt after the
1241  * event has been processed and the decision was made to log the event
1242  * further.
1243  *
1244  * The status parameter will be saved to the 'status' field of 'struct mce'
1245  * and historically has been the register value of the
1246  * MSR_IA32_THERMAL_STATUS (Intel) msr.
1247  */
1248 void mce_log_therm_throt_event(__u64 status)
1249 {
1250         struct mce m;
1251
1252         mce_setup(&m);
1253         m.bank = MCE_THERMAL_BANK;
1254         m.status = status;
1255         mce_log(&m);
1256 }
1257 #endif /* CONFIG_X86_MCE_INTEL */
1258
1259 /*
1260  * Periodic polling timer for "silent" machine check errors.  If the
1261  * poller finds an MCE, poll 2x faster.  When the poller finds no more
1262  * errors, poll 2x slower (up to check_interval seconds).
1263  */
1264 static unsigned long check_interval = 5 * 60; /* 5 minutes */
1265
1266 static DEFINE_PER_CPU(unsigned long, mce_next_interval); /* in jiffies */
1267 static DEFINE_PER_CPU(struct timer_list, mce_timer);
1268
1269 static unsigned long mce_adjust_timer_default(unsigned long interval)
1270 {
1271         return interval;
1272 }
1273
1274 static unsigned long (*mce_adjust_timer)(unsigned long interval) =
1275         mce_adjust_timer_default;
1276
1277 static int cmc_error_seen(void)
1278 {
1279         unsigned long *v = this_cpu_ptr(&mce_polled_error);
1280
1281         return test_and_clear_bit(0, v);
1282 }
1283
1284 static void mce_timer_fn(unsigned long data)
1285 {
1286         struct timer_list *t = this_cpu_ptr(&mce_timer);
1287         unsigned long iv;
1288         int notify;
1289
1290         WARN_ON(smp_processor_id() != data);
1291
1292         if (mce_available(this_cpu_ptr(&cpu_info))) {
1293                 machine_check_poll(MCP_TIMESTAMP,
1294                                 this_cpu_ptr(&mce_poll_banks));
1295                 mce_intel_cmci_poll();
1296         }
1297
1298         /*
1299          * Alert userspace if needed.  If we logged an MCE, reduce the
1300          * polling interval, otherwise increase the polling interval.
1301          */
1302         iv = __this_cpu_read(mce_next_interval);
1303         notify = mce_notify_irq();
1304         notify |= cmc_error_seen();
1305         if (notify) {
1306                 iv = max(iv / 2, (unsigned long) HZ/100);
1307         } else {
1308                 iv = min(iv * 2, round_jiffies_relative(check_interval * HZ));
1309                 iv = mce_adjust_timer(iv);
1310         }
1311         __this_cpu_write(mce_next_interval, iv);
1312         /* Might have become 0 after CMCI storm subsided */
1313         if (iv) {
1314                 t->expires = jiffies + iv;
1315                 add_timer_on(t, smp_processor_id());
1316         }
1317 }
1318
1319 /*
1320  * Ensure that the timer is firing in @interval from now.
1321  */
1322 void mce_timer_kick(unsigned long interval)
1323 {
1324         struct timer_list *t = this_cpu_ptr(&mce_timer);
1325         unsigned long when = jiffies + interval;
1326         unsigned long iv = __this_cpu_read(mce_next_interval);
1327
1328         if (timer_pending(t)) {
1329                 if (time_before(when, t->expires))
1330                         mod_timer_pinned(t, when);
1331         } else {
1332                 t->expires = round_jiffies(when);
1333                 add_timer_on(t, smp_processor_id());
1334         }
1335         if (interval < iv)
1336                 __this_cpu_write(mce_next_interval, interval);
1337 }
1338
1339 /* Must not be called in IRQ context where del_timer_sync() can deadlock */
1340 static void mce_timer_delete_all(void)
1341 {
1342         int cpu;
1343
1344         for_each_online_cpu(cpu)
1345                 del_timer_sync(&per_cpu(mce_timer, cpu));
1346 }
1347
1348 static void mce_do_trigger(struct work_struct *work)
1349 {
1350         call_usermodehelper(mce_helper, mce_helper_argv, NULL, UMH_NO_WAIT);
1351 }
1352
1353 static DECLARE_WORK(mce_trigger_work, mce_do_trigger);
1354
1355 /*
1356  * Notify the user(s) about new machine check events.
1357  * Can be called from interrupt context, but not from machine check/NMI
1358  * context.
1359  */
1360 int mce_notify_irq(void)
1361 {
1362         /* Not more than two messages every minute */
1363         static DEFINE_RATELIMIT_STATE(ratelimit, 60*HZ, 2);
1364
1365         if (test_and_clear_bit(0, &mce_need_notify)) {
1366                 /* wake processes polling /dev/mcelog */
1367                 wake_up_interruptible(&mce_chrdev_wait);
1368
1369                 if (mce_helper[0])
1370                         schedule_work(&mce_trigger_work);
1371
1372                 if (__ratelimit(&ratelimit))
1373                         pr_info(HW_ERR "Machine check events logged\n");
1374
1375                 return 1;
1376         }
1377         return 0;
1378 }
1379 EXPORT_SYMBOL_GPL(mce_notify_irq);
1380
1381 static int __mcheck_cpu_mce_banks_init(void)
1382 {
1383         int i;
1384         u8 num_banks = mca_cfg.banks;
1385
1386         mce_banks = kzalloc(num_banks * sizeof(struct mce_bank), GFP_KERNEL);
1387         if (!mce_banks)
1388                 return -ENOMEM;
1389
1390         for (i = 0; i < num_banks; i++) {
1391                 struct mce_bank *b = &mce_banks[i];
1392
1393                 b->ctl = -1ULL;
1394                 b->init = 1;
1395         }
1396         return 0;
1397 }
1398
1399 /*
1400  * Initialize Machine Checks for a CPU.
1401  */
1402 static int __mcheck_cpu_cap_init(void)
1403 {
1404         unsigned b;
1405         u64 cap;
1406
1407         rdmsrl(MSR_IA32_MCG_CAP, cap);
1408
1409         b = cap & MCG_BANKCNT_MASK;
1410         if (!mca_cfg.banks)
1411                 pr_info("CPU supports %d MCE banks\n", b);
1412
1413         if (b > MAX_NR_BANKS) {
1414                 pr_warn("Using only %u machine check banks out of %u\n",
1415                         MAX_NR_BANKS, b);
1416                 b = MAX_NR_BANKS;
1417         }
1418
1419         /* Don't support asymmetric configurations today */
1420         WARN_ON(mca_cfg.banks != 0 && b != mca_cfg.banks);
1421         mca_cfg.banks = b;
1422
1423         if (!mce_banks) {
1424                 int err = __mcheck_cpu_mce_banks_init();
1425
1426                 if (err)
1427                         return err;
1428         }
1429
1430         /* Use accurate RIP reporting if available. */
1431         if ((cap & MCG_EXT_P) && MCG_EXT_CNT(cap) >= 9)
1432                 mca_cfg.rip_msr = MSR_IA32_MCG_EIP;
1433
1434         if (cap & MCG_SER_P)
1435                 mca_cfg.ser = true;
1436
1437         return 0;
1438 }
1439
1440 static void __mcheck_cpu_init_generic(void)
1441 {
1442         enum mcp_flags m_fl = 0;
1443         mce_banks_t all_banks;
1444         u64 cap;
1445         int i;
1446
1447         if (!mca_cfg.bootlog)
1448                 m_fl = MCP_DONTLOG;
1449
1450         /*
1451          * Log the machine checks left over from the previous reset.
1452          */
1453         bitmap_fill(all_banks, MAX_NR_BANKS);
1454         machine_check_poll(MCP_UC | m_fl, &all_banks);
1455
1456         cr4_set_bits(X86_CR4_MCE);
1457
1458         rdmsrl(MSR_IA32_MCG_CAP, cap);
1459         if (cap & MCG_CTL_P)
1460                 wrmsr(MSR_IA32_MCG_CTL, 0xffffffff, 0xffffffff);
1461
1462         for (i = 0; i < mca_cfg.banks; i++) {
1463                 struct mce_bank *b = &mce_banks[i];
1464
1465                 if (!b->init)
1466                         continue;
1467                 wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
1468                 wrmsrl(MSR_IA32_MCx_STATUS(i), 0);
1469         }
1470 }
1471
1472 /*
1473  * During IFU recovery Sandy Bridge -EP4S processors set the RIPV and
1474  * EIPV bits in MCG_STATUS to zero on the affected logical processor (SDM
1475  * Vol 3B Table 15-20). But this confuses both the code that determines
1476  * whether the machine check occurred in kernel or user mode, and also
1477  * the severity assessment code. Pretend that EIPV was set, and take the
1478  * ip/cs values from the pt_regs that mce_gather_info() ignored earlier.
1479  */
1480 static void quirk_sandybridge_ifu(int bank, struct mce *m, struct pt_regs *regs)
1481 {
1482         if (bank != 0)
1483                 return;
1484         if ((m->mcgstatus & (MCG_STATUS_EIPV|MCG_STATUS_RIPV)) != 0)
1485                 return;
1486         if ((m->status & (MCI_STATUS_OVER|MCI_STATUS_UC|
1487                           MCI_STATUS_EN|MCI_STATUS_MISCV|MCI_STATUS_ADDRV|
1488                           MCI_STATUS_PCC|MCI_STATUS_S|MCI_STATUS_AR|
1489                           MCACOD)) !=
1490                          (MCI_STATUS_UC|MCI_STATUS_EN|
1491                           MCI_STATUS_MISCV|MCI_STATUS_ADDRV|MCI_STATUS_S|
1492                           MCI_STATUS_AR|MCACOD_INSTR))
1493                 return;
1494
1495         m->mcgstatus |= MCG_STATUS_EIPV;
1496         m->ip = regs->ip;
1497         m->cs = regs->cs;
1498 }
1499
1500 /* Add per CPU specific workarounds here */
1501 static int __mcheck_cpu_apply_quirks(struct cpuinfo_x86 *c)
1502 {
1503         struct mca_config *cfg = &mca_cfg;
1504
1505         if (c->x86_vendor == X86_VENDOR_UNKNOWN) {
1506                 pr_info("unknown CPU type - not enabling MCE support\n");
1507                 return -EOPNOTSUPP;
1508         }
1509
1510         /* This should be disabled by the BIOS, but isn't always */
1511         if (c->x86_vendor == X86_VENDOR_AMD) {
1512                 if (c->x86 == 15 && cfg->banks > 4) {
1513                         /*
1514                          * disable GART TBL walk error reporting, which
1515                          * trips off incorrectly with the IOMMU & 3ware
1516                          * & Cerberus:
1517                          */
1518                         clear_bit(10, (unsigned long *)&mce_banks[4].ctl);
1519                 }
1520                 if (c->x86 <= 17 && cfg->bootlog < 0) {
1521                         /*
1522                          * Lots of broken BIOS around that don't clear them
1523                          * by default and leave crap in there. Don't log:
1524                          */
1525                         cfg->bootlog = 0;
1526                 }
1527                 /*
1528                  * Various K7s with broken bank 0 around. Always disable
1529                  * by default.
1530                  */
1531                  if (c->x86 == 6 && cfg->banks > 0)
1532                         mce_banks[0].ctl = 0;
1533
1534                  /*
1535                   * Turn off MC4_MISC thresholding banks on those models since
1536                   * they're not supported there.
1537                   */
1538                  if (c->x86 == 0x15 &&
1539                      (c->x86_model >= 0x10 && c->x86_model <= 0x1f)) {
1540                          int i;
1541                          u64 val, hwcr;
1542                          bool need_toggle;
1543                          u32 msrs[] = {
1544                                 0x00000413, /* MC4_MISC0 */
1545                                 0xc0000408, /* MC4_MISC1 */
1546                          };
1547
1548                          rdmsrl(MSR_K7_HWCR, hwcr);
1549
1550                          /* McStatusWrEn has to be set */
1551                          need_toggle = !(hwcr & BIT(18));
1552
1553                          if (need_toggle)
1554                                  wrmsrl(MSR_K7_HWCR, hwcr | BIT(18));
1555
1556                          for (i = 0; i < ARRAY_SIZE(msrs); i++) {
1557                                  rdmsrl(msrs[i], val);
1558
1559                                  /* CntP bit set? */
1560                                  if (val & BIT_64(62)) {
1561                                         val &= ~BIT_64(62);
1562                                         wrmsrl(msrs[i], val);
1563                                  }
1564                          }
1565
1566                          /* restore old settings */
1567                          if (need_toggle)
1568                                  wrmsrl(MSR_K7_HWCR, hwcr);
1569                  }
1570         }
1571
1572         if (c->x86_vendor == X86_VENDOR_INTEL) {
1573                 /*
1574                  * SDM documents that on family 6 bank 0 should not be written
1575                  * because it aliases to another special BIOS controlled
1576                  * register.
1577                  * But it's not aliased anymore on model 0x1a+
1578                  * Don't ignore bank 0 completely because there could be a
1579                  * valid event later, merely don't write CTL0.
1580                  */
1581
1582                 if (c->x86 == 6 && c->x86_model < 0x1A && cfg->banks > 0)
1583                         mce_banks[0].init = 0;
1584
1585                 /*
1586                  * All newer Intel systems support MCE broadcasting. Enable
1587                  * synchronization with a one second timeout.
1588                  */
1589                 if ((c->x86 > 6 || (c->x86 == 6 && c->x86_model >= 0xe)) &&
1590                         cfg->monarch_timeout < 0)
1591                         cfg->monarch_timeout = USEC_PER_SEC;
1592
1593                 /*
1594                  * There are also broken BIOSes on some Pentium M and
1595                  * earlier systems:
1596                  */
1597                 if (c->x86 == 6 && c->x86_model <= 13 && cfg->bootlog < 0)
1598                         cfg->bootlog = 0;
1599
1600                 if (c->x86 == 6 && c->x86_model == 45)
1601                         quirk_no_way_out = quirk_sandybridge_ifu;
1602         }
1603         if (cfg->monarch_timeout < 0)
1604                 cfg->monarch_timeout = 0;
1605         if (cfg->bootlog != 0)
1606                 cfg->panic_timeout = 30;
1607
1608         return 0;
1609 }
1610
1611 static int __mcheck_cpu_ancient_init(struct cpuinfo_x86 *c)
1612 {
1613         if (c->x86 != 5)
1614                 return 0;
1615
1616         switch (c->x86_vendor) {
1617         case X86_VENDOR_INTEL:
1618                 intel_p5_mcheck_init(c);
1619                 return 1;
1620                 break;
1621         case X86_VENDOR_CENTAUR:
1622                 winchip_mcheck_init(c);
1623                 return 1;
1624                 break;
1625         }
1626
1627         return 0;
1628 }
1629
1630 static void __mcheck_cpu_init_vendor(struct cpuinfo_x86 *c)
1631 {
1632         switch (c->x86_vendor) {
1633         case X86_VENDOR_INTEL:
1634                 mce_intel_feature_init(c);
1635                 mce_adjust_timer = mce_intel_adjust_timer;
1636                 break;
1637         case X86_VENDOR_AMD:
1638                 mce_amd_feature_init(c);
1639                 break;
1640         default:
1641                 break;
1642         }
1643 }
1644
1645 static void mce_start_timer(unsigned int cpu, struct timer_list *t)
1646 {
1647         unsigned long iv = check_interval * HZ;
1648
1649         if (mca_cfg.ignore_ce || !iv)
1650                 return;
1651
1652         per_cpu(mce_next_interval, cpu) = iv;
1653
1654         t->expires = round_jiffies(jiffies + iv);
1655         add_timer_on(t, cpu);
1656 }
1657
1658 static void __mcheck_cpu_init_timer(void)
1659 {
1660         struct timer_list *t = this_cpu_ptr(&mce_timer);
1661         unsigned int cpu = smp_processor_id();
1662
1663         setup_timer(t, mce_timer_fn, cpu);
1664         mce_start_timer(cpu, t);
1665 }
1666
1667 /* Handle unconfigured int18 (should never happen) */
1668 static void unexpected_machine_check(struct pt_regs *regs, long error_code)
1669 {
1670         pr_err("CPU#%d: Unexpected int18 (Machine Check)\n",
1671                smp_processor_id());
1672 }
1673
1674 /* Call the installed machine check handler for this CPU setup. */
1675 void (*machine_check_vector)(struct pt_regs *, long error_code) =
1676                                                 unexpected_machine_check;
1677
1678 /*
1679  * Called for each booted CPU to set up machine checks.
1680  * Must be called with preempt off:
1681  */
1682 void mcheck_cpu_init(struct cpuinfo_x86 *c)
1683 {
1684         if (mca_cfg.disabled)
1685                 return;
1686
1687         if (__mcheck_cpu_ancient_init(c))
1688                 return;
1689
1690         if (!mce_available(c))
1691                 return;
1692
1693         if (__mcheck_cpu_cap_init() < 0 || __mcheck_cpu_apply_quirks(c) < 0) {
1694                 mca_cfg.disabled = true;
1695                 return;
1696         }
1697
1698         machine_check_vector = do_machine_check;
1699
1700         __mcheck_cpu_init_generic();
1701         __mcheck_cpu_init_vendor(c);
1702         __mcheck_cpu_init_timer();
1703         INIT_WORK(this_cpu_ptr(&mce_work), mce_process_work);
1704         init_irq_work(this_cpu_ptr(&mce_irq_work), &mce_irq_work_cb);
1705 }
1706
1707 /*
1708  * mce_chrdev: Character device /dev/mcelog to read and clear the MCE log.
1709  */
1710
1711 static DEFINE_SPINLOCK(mce_chrdev_state_lock);
1712 static int mce_chrdev_open_count;       /* #times opened */
1713 static int mce_chrdev_open_exclu;       /* already open exclusive? */
1714
1715 static int mce_chrdev_open(struct inode *inode, struct file *file)
1716 {
1717         spin_lock(&mce_chrdev_state_lock);
1718
1719         if (mce_chrdev_open_exclu ||
1720             (mce_chrdev_open_count && (file->f_flags & O_EXCL))) {
1721                 spin_unlock(&mce_chrdev_state_lock);
1722
1723                 return -EBUSY;
1724         }
1725
1726         if (file->f_flags & O_EXCL)
1727                 mce_chrdev_open_exclu = 1;
1728         mce_chrdev_open_count++;
1729
1730         spin_unlock(&mce_chrdev_state_lock);
1731
1732         return nonseekable_open(inode, file);
1733 }
1734
1735 static int mce_chrdev_release(struct inode *inode, struct file *file)
1736 {
1737         spin_lock(&mce_chrdev_state_lock);
1738
1739         mce_chrdev_open_count--;
1740         mce_chrdev_open_exclu = 0;
1741
1742         spin_unlock(&mce_chrdev_state_lock);
1743
1744         return 0;
1745 }
1746
1747 static void collect_tscs(void *data)
1748 {
1749         unsigned long *cpu_tsc = (unsigned long *)data;
1750
1751         rdtscll(cpu_tsc[smp_processor_id()]);
1752 }
1753
1754 static int mce_apei_read_done;
1755
1756 /* Collect MCE record of previous boot in persistent storage via APEI ERST. */
1757 static int __mce_read_apei(char __user **ubuf, size_t usize)
1758 {
1759         int rc;
1760         u64 record_id;
1761         struct mce m;
1762
1763         if (usize < sizeof(struct mce))
1764                 return -EINVAL;
1765
1766         rc = apei_read_mce(&m, &record_id);
1767         /* Error or no more MCE record */
1768         if (rc <= 0) {
1769                 mce_apei_read_done = 1;
1770                 /*
1771                  * When ERST is disabled, mce_chrdev_read() should return
1772                  * "no record" instead of "no device."
1773                  */
1774                 if (rc == -ENODEV)
1775                         return 0;
1776                 return rc;
1777         }
1778         rc = -EFAULT;
1779         if (copy_to_user(*ubuf, &m, sizeof(struct mce)))
1780                 return rc;
1781         /*
1782          * In fact, we should have cleared the record after that has
1783          * been flushed to the disk or sent to network in
1784          * /sbin/mcelog, but we have no interface to support that now,
1785          * so just clear it to avoid duplication.
1786          */
1787         rc = apei_clear_mce(record_id);
1788         if (rc) {
1789                 mce_apei_read_done = 1;
1790                 return rc;
1791         }
1792         *ubuf += sizeof(struct mce);
1793
1794         return 0;
1795 }
1796
1797 static ssize_t mce_chrdev_read(struct file *filp, char __user *ubuf,
1798                                 size_t usize, loff_t *off)
1799 {
1800         char __user *buf = ubuf;
1801         unsigned long *cpu_tsc;
1802         unsigned prev, next;
1803         int i, err;
1804
1805         cpu_tsc = kmalloc(nr_cpu_ids * sizeof(long), GFP_KERNEL);
1806         if (!cpu_tsc)
1807                 return -ENOMEM;
1808
1809         mutex_lock(&mce_chrdev_read_mutex);
1810
1811         if (!mce_apei_read_done) {
1812                 err = __mce_read_apei(&buf, usize);
1813                 if (err || buf != ubuf)
1814                         goto out;
1815         }
1816
1817         next = rcu_dereference_check_mce(mcelog.next);
1818
1819         /* Only supports full reads right now */
1820         err = -EINVAL;
1821         if (*off != 0 || usize < MCE_LOG_LEN*sizeof(struct mce))
1822                 goto out;
1823
1824         err = 0;
1825         prev = 0;
1826         do {
1827                 for (i = prev; i < next; i++) {
1828                         unsigned long start = jiffies;
1829                         struct mce *m = &mcelog.entry[i];
1830
1831                         while (!m->finished) {
1832                                 if (time_after_eq(jiffies, start + 2)) {
1833                                         memset(m, 0, sizeof(*m));
1834                                         goto timeout;
1835                                 }
1836                                 cpu_relax();
1837                         }
1838                         smp_rmb();
1839                         err |= copy_to_user(buf, m, sizeof(*m));
1840                         buf += sizeof(*m);
1841 timeout:
1842                         ;
1843                 }
1844
1845                 memset(mcelog.entry + prev, 0,
1846                        (next - prev) * sizeof(struct mce));
1847                 prev = next;
1848                 next = cmpxchg(&mcelog.next, prev, 0);
1849         } while (next != prev);
1850
1851         synchronize_sched();
1852
1853         /*
1854          * Collect entries that were still getting written before the
1855          * synchronize.
1856          */
1857         on_each_cpu(collect_tscs, cpu_tsc, 1);
1858
1859         for (i = next; i < MCE_LOG_LEN; i++) {
1860                 struct mce *m = &mcelog.entry[i];
1861
1862                 if (m->finished && m->tsc < cpu_tsc[m->cpu]) {
1863                         err |= copy_to_user(buf, m, sizeof(*m));
1864                         smp_rmb();
1865                         buf += sizeof(*m);
1866                         memset(m, 0, sizeof(*m));
1867                 }
1868         }
1869
1870         if (err)
1871                 err = -EFAULT;
1872
1873 out:
1874         mutex_unlock(&mce_chrdev_read_mutex);
1875         kfree(cpu_tsc);
1876
1877         return err ? err : buf - ubuf;
1878 }
1879
1880 static unsigned int mce_chrdev_poll(struct file *file, poll_table *wait)
1881 {
1882         poll_wait(file, &mce_chrdev_wait, wait);
1883         if (rcu_access_index(mcelog.next))
1884                 return POLLIN | POLLRDNORM;
1885         if (!mce_apei_read_done && apei_check_mce())
1886                 return POLLIN | POLLRDNORM;
1887         return 0;
1888 }
1889
1890 static long mce_chrdev_ioctl(struct file *f, unsigned int cmd,
1891                                 unsigned long arg)
1892 {
1893         int __user *p = (int __user *)arg;
1894
1895         if (!capable(CAP_SYS_ADMIN))
1896                 return -EPERM;
1897
1898         switch (cmd) {
1899         case MCE_GET_RECORD_LEN:
1900                 return put_user(sizeof(struct mce), p);
1901         case MCE_GET_LOG_LEN:
1902                 return put_user(MCE_LOG_LEN, p);
1903         case MCE_GETCLEAR_FLAGS: {
1904                 unsigned flags;
1905
1906                 do {
1907                         flags = mcelog.flags;
1908                 } while (cmpxchg(&mcelog.flags, flags, 0) != flags);
1909
1910                 return put_user(flags, p);
1911         }
1912         default:
1913                 return -ENOTTY;
1914         }
1915 }
1916
1917 static ssize_t (*mce_write)(struct file *filp, const char __user *ubuf,
1918                             size_t usize, loff_t *off);
1919
1920 void register_mce_write_callback(ssize_t (*fn)(struct file *filp,
1921                              const char __user *ubuf,
1922                              size_t usize, loff_t *off))
1923 {
1924         mce_write = fn;
1925 }
1926 EXPORT_SYMBOL_GPL(register_mce_write_callback);
1927
1928 ssize_t mce_chrdev_write(struct file *filp, const char __user *ubuf,
1929                          size_t usize, loff_t *off)
1930 {
1931         if (mce_write)
1932                 return mce_write(filp, ubuf, usize, off);
1933         else
1934                 return -EINVAL;
1935 }
1936
1937 static const struct file_operations mce_chrdev_ops = {
1938         .open                   = mce_chrdev_open,
1939         .release                = mce_chrdev_release,
1940         .read                   = mce_chrdev_read,
1941         .write                  = mce_chrdev_write,
1942         .poll                   = mce_chrdev_poll,
1943         .unlocked_ioctl         = mce_chrdev_ioctl,
1944         .llseek                 = no_llseek,
1945 };
1946
1947 static struct miscdevice mce_chrdev_device = {
1948         MISC_MCELOG_MINOR,
1949         "mcelog",
1950         &mce_chrdev_ops,
1951 };
1952
1953 static void __mce_disable_bank(void *arg)
1954 {
1955         int bank = *((int *)arg);
1956         __clear_bit(bank, this_cpu_ptr(mce_poll_banks));
1957         cmci_disable_bank(bank);
1958 }
1959
1960 void mce_disable_bank(int bank)
1961 {
1962         if (bank >= mca_cfg.banks) {
1963                 pr_warn(FW_BUG
1964                         "Ignoring request to disable invalid MCA bank %d.\n",
1965                         bank);
1966                 return;
1967         }
1968         set_bit(bank, mce_banks_ce_disabled);
1969         on_each_cpu(__mce_disable_bank, &bank, 1);
1970 }
1971
1972 /*
1973  * mce=off Disables machine check
1974  * mce=no_cmci Disables CMCI
1975  * mce=dont_log_ce Clears corrected events silently, no log created for CEs.
1976  * mce=ignore_ce Disables polling and CMCI, corrected events are not cleared.
1977  * mce=TOLERANCELEVEL[,monarchtimeout] (number, see above)
1978  *      monarchtimeout is how long to wait for other CPUs on machine
1979  *      check, or 0 to not wait
1980  * mce=bootlog Log MCEs from before booting. Disabled by default on AMD.
1981  * mce=nobootlog Don't log MCEs from before booting.
1982  * mce=bios_cmci_threshold Don't program the CMCI threshold
1983  */
1984 static int __init mcheck_enable(char *str)
1985 {
1986         struct mca_config *cfg = &mca_cfg;
1987
1988         if (*str == 0) {
1989                 enable_p5_mce();
1990                 return 1;
1991         }
1992         if (*str == '=')
1993                 str++;
1994         if (!strcmp(str, "off"))
1995                 cfg->disabled = true;
1996         else if (!strcmp(str, "no_cmci"))
1997                 cfg->cmci_disabled = true;
1998         else if (!strcmp(str, "dont_log_ce"))
1999                 cfg->dont_log_ce = true;
2000         else if (!strcmp(str, "ignore_ce"))
2001                 cfg->ignore_ce = true;
2002         else if (!strcmp(str, "bootlog") || !strcmp(str, "nobootlog"))
2003                 cfg->bootlog = (str[0] == 'b');
2004         else if (!strcmp(str, "bios_cmci_threshold"))
2005                 cfg->bios_cmci_threshold = true;
2006         else if (isdigit(str[0])) {
2007                 get_option(&str, &(cfg->tolerant));
2008                 if (*str == ',') {
2009                         ++str;
2010                         get_option(&str, &(cfg->monarch_timeout));
2011                 }
2012         } else {
2013                 pr_info("mce argument %s ignored. Please use /sys\n", str);
2014                 return 0;
2015         }
2016         return 1;
2017 }
2018 __setup("mce", mcheck_enable);
2019
2020 int __init mcheck_init(void)
2021 {
2022         mcheck_intel_therm_init();
2023
2024         return 0;
2025 }
2026
2027 /*
2028  * mce_syscore: PM support
2029  */
2030
2031 /*
2032  * Disable machine checks on suspend and shutdown. We can't really handle
2033  * them later.
2034  */
2035 static int mce_disable_error_reporting(void)
2036 {
2037         int i;
2038
2039         for (i = 0; i < mca_cfg.banks; i++) {
2040                 struct mce_bank *b = &mce_banks[i];
2041
2042                 if (b->init)
2043                         wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2044         }
2045         return 0;
2046 }
2047
2048 static int mce_syscore_suspend(void)
2049 {
2050         return mce_disable_error_reporting();
2051 }
2052
2053 static void mce_syscore_shutdown(void)
2054 {
2055         mce_disable_error_reporting();
2056 }
2057
2058 /*
2059  * On resume clear all MCE state. Don't want to see leftovers from the BIOS.
2060  * Only one CPU is active at this time, the others get re-added later using
2061  * CPU hotplug:
2062  */
2063 static void mce_syscore_resume(void)
2064 {
2065         __mcheck_cpu_init_generic();
2066         __mcheck_cpu_init_vendor(raw_cpu_ptr(&cpu_info));
2067 }
2068
2069 static struct syscore_ops mce_syscore_ops = {
2070         .suspend        = mce_syscore_suspend,
2071         .shutdown       = mce_syscore_shutdown,
2072         .resume         = mce_syscore_resume,
2073 };
2074
2075 /*
2076  * mce_device: Sysfs support
2077  */
2078
2079 static void mce_cpu_restart(void *data)
2080 {
2081         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2082                 return;
2083         __mcheck_cpu_init_generic();
2084         __mcheck_cpu_init_timer();
2085 }
2086
2087 /* Reinit MCEs after user configuration changes */
2088 static void mce_restart(void)
2089 {
2090         mce_timer_delete_all();
2091         on_each_cpu(mce_cpu_restart, NULL, 1);
2092 }
2093
2094 /* Toggle features for corrected errors */
2095 static void mce_disable_cmci(void *data)
2096 {
2097         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2098                 return;
2099         cmci_clear();
2100 }
2101
2102 static void mce_enable_ce(void *all)
2103 {
2104         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2105                 return;
2106         cmci_reenable();
2107         cmci_recheck();
2108         if (all)
2109                 __mcheck_cpu_init_timer();
2110 }
2111
2112 static struct bus_type mce_subsys = {
2113         .name           = "machinecheck",
2114         .dev_name       = "machinecheck",
2115 };
2116
2117 DEFINE_PER_CPU(struct device *, mce_device);
2118
2119 void (*threshold_cpu_callback)(unsigned long action, unsigned int cpu);
2120
2121 static inline struct mce_bank *attr_to_bank(struct device_attribute *attr)
2122 {
2123         return container_of(attr, struct mce_bank, attr);
2124 }
2125
2126 static ssize_t show_bank(struct device *s, struct device_attribute *attr,
2127                          char *buf)
2128 {
2129         return sprintf(buf, "%llx\n", attr_to_bank(attr)->ctl);
2130 }
2131
2132 static ssize_t set_bank(struct device *s, struct device_attribute *attr,
2133                         const char *buf, size_t size)
2134 {
2135         u64 new;
2136
2137         if (kstrtou64(buf, 0, &new) < 0)
2138                 return -EINVAL;
2139
2140         attr_to_bank(attr)->ctl = new;
2141         mce_restart();
2142
2143         return size;
2144 }
2145
2146 static ssize_t
2147 show_trigger(struct device *s, struct device_attribute *attr, char *buf)
2148 {
2149         strcpy(buf, mce_helper);
2150         strcat(buf, "\n");
2151         return strlen(mce_helper) + 1;
2152 }
2153
2154 static ssize_t set_trigger(struct device *s, struct device_attribute *attr,
2155                                 const char *buf, size_t siz)
2156 {
2157         char *p;
2158
2159         strncpy(mce_helper, buf, sizeof(mce_helper));
2160         mce_helper[sizeof(mce_helper)-1] = 0;
2161         p = strchr(mce_helper, '\n');
2162
2163         if (p)
2164                 *p = 0;
2165
2166         return strlen(mce_helper) + !!p;
2167 }
2168
2169 static ssize_t set_ignore_ce(struct device *s,
2170                              struct device_attribute *attr,
2171                              const char *buf, size_t size)
2172 {
2173         u64 new;
2174
2175         if (kstrtou64(buf, 0, &new) < 0)
2176                 return -EINVAL;
2177
2178         if (mca_cfg.ignore_ce ^ !!new) {
2179                 if (new) {
2180                         /* disable ce features */
2181                         mce_timer_delete_all();
2182                         on_each_cpu(mce_disable_cmci, NULL, 1);
2183                         mca_cfg.ignore_ce = true;
2184                 } else {
2185                         /* enable ce features */
2186                         mca_cfg.ignore_ce = false;
2187                         on_each_cpu(mce_enable_ce, (void *)1, 1);
2188                 }
2189         }
2190         return size;
2191 }
2192
2193 static ssize_t set_cmci_disabled(struct device *s,
2194                                  struct device_attribute *attr,
2195                                  const char *buf, size_t size)
2196 {
2197         u64 new;
2198
2199         if (kstrtou64(buf, 0, &new) < 0)
2200                 return -EINVAL;
2201
2202         if (mca_cfg.cmci_disabled ^ !!new) {
2203                 if (new) {
2204                         /* disable cmci */
2205                         on_each_cpu(mce_disable_cmci, NULL, 1);
2206                         mca_cfg.cmci_disabled = true;
2207                 } else {
2208                         /* enable cmci */
2209                         mca_cfg.cmci_disabled = false;
2210                         on_each_cpu(mce_enable_ce, NULL, 1);
2211                 }
2212         }
2213         return size;
2214 }
2215
2216 static ssize_t store_int_with_restart(struct device *s,
2217                                       struct device_attribute *attr,
2218                                       const char *buf, size_t size)
2219 {
2220         ssize_t ret = device_store_int(s, attr, buf, size);
2221         mce_restart();
2222         return ret;
2223 }
2224
2225 static DEVICE_ATTR(trigger, 0644, show_trigger, set_trigger);
2226 static DEVICE_INT_ATTR(tolerant, 0644, mca_cfg.tolerant);
2227 static DEVICE_INT_ATTR(monarch_timeout, 0644, mca_cfg.monarch_timeout);
2228 static DEVICE_BOOL_ATTR(dont_log_ce, 0644, mca_cfg.dont_log_ce);
2229
2230 static struct dev_ext_attribute dev_attr_check_interval = {
2231         __ATTR(check_interval, 0644, device_show_int, store_int_with_restart),
2232         &check_interval
2233 };
2234
2235 static struct dev_ext_attribute dev_attr_ignore_ce = {
2236         __ATTR(ignore_ce, 0644, device_show_bool, set_ignore_ce),
2237         &mca_cfg.ignore_ce
2238 };
2239
2240 static struct dev_ext_attribute dev_attr_cmci_disabled = {
2241         __ATTR(cmci_disabled, 0644, device_show_bool, set_cmci_disabled),
2242         &mca_cfg.cmci_disabled
2243 };
2244
2245 static struct device_attribute *mce_device_attrs[] = {
2246         &dev_attr_tolerant.attr,
2247         &dev_attr_check_interval.attr,
2248         &dev_attr_trigger,
2249         &dev_attr_monarch_timeout.attr,
2250         &dev_attr_dont_log_ce.attr,
2251         &dev_attr_ignore_ce.attr,
2252         &dev_attr_cmci_disabled.attr,
2253         NULL
2254 };
2255
2256 static cpumask_var_t mce_device_initialized;
2257
2258 static void mce_device_release(struct device *dev)
2259 {
2260         kfree(dev);
2261 }
2262
2263 /* Per cpu device init. All of the cpus still share the same ctrl bank: */
2264 static int mce_device_create(unsigned int cpu)
2265 {
2266         struct device *dev;
2267         int err;
2268         int i, j;
2269
2270         if (!mce_available(&boot_cpu_data))
2271                 return -EIO;
2272
2273         dev = kzalloc(sizeof *dev, GFP_KERNEL);
2274         if (!dev)
2275                 return -ENOMEM;
2276         dev->id  = cpu;
2277         dev->bus = &mce_subsys;
2278         dev->release = &mce_device_release;
2279
2280         err = device_register(dev);
2281         if (err) {
2282                 put_device(dev);
2283                 return err;
2284         }
2285
2286         for (i = 0; mce_device_attrs[i]; i++) {
2287                 err = device_create_file(dev, mce_device_attrs[i]);
2288                 if (err)
2289                         goto error;
2290         }
2291         for (j = 0; j < mca_cfg.banks; j++) {
2292                 err = device_create_file(dev, &mce_banks[j].attr);
2293                 if (err)
2294                         goto error2;
2295         }
2296         cpumask_set_cpu(cpu, mce_device_initialized);
2297         per_cpu(mce_device, cpu) = dev;
2298
2299         return 0;
2300 error2:
2301         while (--j >= 0)
2302                 device_remove_file(dev, &mce_banks[j].attr);
2303 error:
2304         while (--i >= 0)
2305                 device_remove_file(dev, mce_device_attrs[i]);
2306
2307         device_unregister(dev);
2308
2309         return err;
2310 }
2311
2312 static void mce_device_remove(unsigned int cpu)
2313 {
2314         struct device *dev = per_cpu(mce_device, cpu);
2315         int i;
2316
2317         if (!cpumask_test_cpu(cpu, mce_device_initialized))
2318                 return;
2319
2320         for (i = 0; mce_device_attrs[i]; i++)
2321                 device_remove_file(dev, mce_device_attrs[i]);
2322
2323         for (i = 0; i < mca_cfg.banks; i++)
2324                 device_remove_file(dev, &mce_banks[i].attr);
2325
2326         device_unregister(dev);
2327         cpumask_clear_cpu(cpu, mce_device_initialized);
2328         per_cpu(mce_device, cpu) = NULL;
2329 }
2330
2331 /* Make sure there are no machine checks on offlined CPUs. */
2332 static void mce_disable_cpu(void *h)
2333 {
2334         unsigned long action = *(unsigned long *)h;
2335         int i;
2336
2337         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2338                 return;
2339
2340         if (!(action & CPU_TASKS_FROZEN))
2341                 cmci_clear();
2342         for (i = 0; i < mca_cfg.banks; i++) {
2343                 struct mce_bank *b = &mce_banks[i];
2344
2345                 if (b->init)
2346                         wrmsrl(MSR_IA32_MCx_CTL(i), 0);
2347         }
2348 }
2349
2350 static void mce_reenable_cpu(void *h)
2351 {
2352         unsigned long action = *(unsigned long *)h;
2353         int i;
2354
2355         if (!mce_available(raw_cpu_ptr(&cpu_info)))
2356                 return;
2357
2358         if (!(action & CPU_TASKS_FROZEN))
2359                 cmci_reenable();
2360         for (i = 0; i < mca_cfg.banks; i++) {
2361                 struct mce_bank *b = &mce_banks[i];
2362
2363                 if (b->init)
2364                         wrmsrl(MSR_IA32_MCx_CTL(i), b->ctl);
2365         }
2366 }
2367
2368 /* Get notified when a cpu comes on/off. Be hotplug friendly. */
2369 static int
2370 mce_cpu_callback(struct notifier_block *nfb, unsigned long action, void *hcpu)
2371 {
2372         unsigned int cpu = (unsigned long)hcpu;
2373         struct timer_list *t = &per_cpu(mce_timer, cpu);
2374
2375         switch (action & ~CPU_TASKS_FROZEN) {
2376         case CPU_ONLINE:
2377                 mce_device_create(cpu);
2378                 if (threshold_cpu_callback)
2379                         threshold_cpu_callback(action, cpu);
2380                 break;
2381         case CPU_DEAD:
2382                 if (threshold_cpu_callback)
2383                         threshold_cpu_callback(action, cpu);
2384                 mce_device_remove(cpu);
2385                 mce_intel_hcpu_update(cpu);
2386
2387                 /* intentionally ignoring frozen here */
2388                 if (!(action & CPU_TASKS_FROZEN))
2389                         cmci_rediscover();
2390                 break;
2391         case CPU_DOWN_PREPARE:
2392                 smp_call_function_single(cpu, mce_disable_cpu, &action, 1);
2393                 del_timer_sync(t);
2394                 break;
2395         case CPU_DOWN_FAILED:
2396                 smp_call_function_single(cpu, mce_reenable_cpu, &action, 1);
2397                 mce_start_timer(cpu, t);
2398                 break;
2399         }
2400
2401         return NOTIFY_OK;
2402 }
2403
2404 static struct notifier_block mce_cpu_notifier = {
2405         .notifier_call = mce_cpu_callback,
2406 };
2407
2408 static __init void mce_init_banks(void)
2409 {
2410         int i;
2411
2412         for (i = 0; i < mca_cfg.banks; i++) {
2413                 struct mce_bank *b = &mce_banks[i];
2414                 struct device_attribute *a = &b->attr;
2415
2416                 sysfs_attr_init(&a->attr);
2417                 a->attr.name    = b->attrname;
2418                 snprintf(b->attrname, ATTR_LEN, "bank%d", i);
2419
2420                 a->attr.mode    = 0644;
2421                 a->show         = show_bank;
2422                 a->store        = set_bank;
2423         }
2424 }
2425
2426 static __init int mcheck_init_device(void)
2427 {
2428         int err;
2429         int i = 0;
2430
2431         if (!mce_available(&boot_cpu_data)) {
2432                 err = -EIO;
2433                 goto err_out;
2434         }
2435
2436         if (!zalloc_cpumask_var(&mce_device_initialized, GFP_KERNEL)) {
2437                 err = -ENOMEM;
2438                 goto err_out;
2439         }
2440
2441         mce_init_banks();
2442
2443         err = subsys_system_register(&mce_subsys, NULL);
2444         if (err)
2445                 goto err_out_mem;
2446
2447         cpu_notifier_register_begin();
2448         for_each_online_cpu(i) {
2449                 err = mce_device_create(i);
2450                 if (err) {
2451                         /*
2452                          * Register notifier anyway (and do not unreg it) so
2453                          * that we don't leave undeleted timers, see notifier
2454                          * callback above.
2455                          */
2456                         __register_hotcpu_notifier(&mce_cpu_notifier);
2457                         cpu_notifier_register_done();
2458                         goto err_device_create;
2459                 }
2460         }
2461
2462         __register_hotcpu_notifier(&mce_cpu_notifier);
2463         cpu_notifier_register_done();
2464
2465         register_syscore_ops(&mce_syscore_ops);
2466
2467         /* register character device /dev/mcelog */
2468         err = misc_register(&mce_chrdev_device);
2469         if (err)
2470                 goto err_register;
2471
2472         return 0;
2473
2474 err_register:
2475         unregister_syscore_ops(&mce_syscore_ops);
2476
2477 err_device_create:
2478         /*
2479          * We didn't keep track of which devices were created above, but
2480          * even if we had, the set of online cpus might have changed.
2481          * Play safe and remove for every possible cpu, since
2482          * mce_device_remove() will do the right thing.
2483          */
2484         for_each_possible_cpu(i)
2485                 mce_device_remove(i);
2486
2487 err_out_mem:
2488         free_cpumask_var(mce_device_initialized);
2489
2490 err_out:
2491         pr_err("Unable to init device /dev/mcelog (rc: %d)\n", err);
2492
2493         return err;
2494 }
2495 device_initcall_sync(mcheck_init_device);
2496
2497 /*
2498  * Old style boot options parsing. Only for compatibility.
2499  */
2500 static int __init mcheck_disable(char *str)
2501 {
2502         mca_cfg.disabled = true;
2503         return 1;
2504 }
2505 __setup("nomce", mcheck_disable);
2506
2507 #ifdef CONFIG_DEBUG_FS
2508 struct dentry *mce_get_debugfs_dir(void)
2509 {
2510         static struct dentry *dmce;
2511
2512         if (!dmce)
2513                 dmce = debugfs_create_dir("mce", NULL);
2514
2515         return dmce;
2516 }
2517
2518 static void mce_reset(void)
2519 {
2520         cpu_missing = 0;
2521         atomic_set(&mce_fake_panicked, 0);
2522         atomic_set(&mce_executing, 0);
2523         atomic_set(&mce_callin, 0);
2524         atomic_set(&global_nwo, 0);
2525 }
2526
2527 static int fake_panic_get(void *data, u64 *val)
2528 {
2529         *val = fake_panic;
2530         return 0;
2531 }
2532
2533 static int fake_panic_set(void *data, u64 val)
2534 {
2535         mce_reset();
2536         fake_panic = val;
2537         return 0;
2538 }
2539
2540 DEFINE_SIMPLE_ATTRIBUTE(fake_panic_fops, fake_panic_get,
2541                         fake_panic_set, "%llu\n");
2542
2543 static int __init mcheck_debugfs_init(void)
2544 {
2545         struct dentry *dmce, *ffake_panic;
2546
2547         dmce = mce_get_debugfs_dir();
2548         if (!dmce)
2549                 return -ENOMEM;
2550         ffake_panic = debugfs_create_file("fake_panic", 0444, dmce, NULL,
2551                                           &fake_panic_fops);
2552         if (!ffake_panic)
2553                 return -ENOMEM;
2554
2555         return 0;
2556 }
2557 late_initcall(mcheck_debugfs_init);
2558 #endif