perf, intel: Try alternative OFFCORE encodings
[pandora-kernel.git] / arch / x86 / kernel / cpu / perf_event.c
1 /*
2  * Performance events x86 architecture code
3  *
4  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6  *  Copyright (C) 2009 Jaswinder Singh Rajput
7  *  Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
8  *  Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
9  *  Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
10  *  Copyright (C) 2009 Google, Inc., Stephane Eranian
11  *
12  *  For licencing details see kernel-base/COPYING
13  */
14
15 #include <linux/perf_event.h>
16 #include <linux/capability.h>
17 #include <linux/notifier.h>
18 #include <linux/hardirq.h>
19 #include <linux/kprobes.h>
20 #include <linux/module.h>
21 #include <linux/kdebug.h>
22 #include <linux/sched.h>
23 #include <linux/uaccess.h>
24 #include <linux/slab.h>
25 #include <linux/highmem.h>
26 #include <linux/cpu.h>
27 #include <linux/bitops.h>
28
29 #include <asm/apic.h>
30 #include <asm/stacktrace.h>
31 #include <asm/nmi.h>
32 #include <asm/compat.h>
33 #include <asm/smp.h>
34 #include <asm/alternative.h>
35
36 #if 0
37 #undef wrmsrl
38 #define wrmsrl(msr, val)                                        \
39 do {                                                            \
40         trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
41                         (unsigned long)(val));                  \
42         native_write_msr((msr), (u32)((u64)(val)),              \
43                         (u32)((u64)(val) >> 32));               \
44 } while (0)
45 #endif
46
47 /*
48  *          |   NHM/WSM    |      SNB     |
49  * register -------------------------------
50  *          |  HT  | no HT |  HT  | no HT |
51  *-----------------------------------------
52  * offcore  | core | core  | cpu  | core  |
53  * lbr_sel  | core | core  | cpu  | core  |
54  * ld_lat   | cpu  | core  | cpu  | core  |
55  *-----------------------------------------
56  *
57  * Given that there is a small number of shared regs,
58  * we can pre-allocate their slot in the per-cpu
59  * per-core reg tables.
60  */
61 enum extra_reg_type {
62         EXTRA_REG_NONE  = -1,   /* not used */
63
64         EXTRA_REG_RSP_0 = 0,    /* offcore_response_0 */
65         EXTRA_REG_RSP_1 = 1,    /* offcore_response_1 */
66
67         EXTRA_REG_MAX           /* number of entries needed */
68 };
69
70 /*
71  * best effort, GUP based copy_from_user() that assumes IRQ or NMI context
72  */
73 static unsigned long
74 copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
75 {
76         unsigned long offset, addr = (unsigned long)from;
77         unsigned long size, len = 0;
78         struct page *page;
79         void *map;
80         int ret;
81
82         do {
83                 ret = __get_user_pages_fast(addr, 1, 0, &page);
84                 if (!ret)
85                         break;
86
87                 offset = addr & (PAGE_SIZE - 1);
88                 size = min(PAGE_SIZE - offset, n - len);
89
90                 map = kmap_atomic(page);
91                 memcpy(to, map+offset, size);
92                 kunmap_atomic(map);
93                 put_page(page);
94
95                 len  += size;
96                 to   += size;
97                 addr += size;
98
99         } while (len < n);
100
101         return len;
102 }
103
104 struct event_constraint {
105         union {
106                 unsigned long   idxmsk[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
107                 u64             idxmsk64;
108         };
109         u64     code;
110         u64     cmask;
111         int     weight;
112 };
113
114 struct amd_nb {
115         int nb_id;  /* NorthBridge id */
116         int refcnt; /* reference count */
117         struct perf_event *owners[X86_PMC_IDX_MAX];
118         struct event_constraint event_constraints[X86_PMC_IDX_MAX];
119 };
120
121 struct intel_percore;
122
123 #define MAX_LBR_ENTRIES         16
124
125 struct cpu_hw_events {
126         /*
127          * Generic x86 PMC bits
128          */
129         struct perf_event       *events[X86_PMC_IDX_MAX]; /* in counter order */
130         unsigned long           active_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
131         unsigned long           running[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
132         int                     enabled;
133
134         int                     n_events;
135         int                     n_added;
136         int                     n_txn;
137         int                     assign[X86_PMC_IDX_MAX]; /* event to counter assignment */
138         u64                     tags[X86_PMC_IDX_MAX];
139         struct perf_event       *event_list[X86_PMC_IDX_MAX]; /* in enabled order */
140
141         unsigned int            group_flag;
142
143         /*
144          * Intel DebugStore bits
145          */
146         struct debug_store      *ds;
147         u64                     pebs_enabled;
148
149         /*
150          * Intel LBR bits
151          */
152         int                             lbr_users;
153         void                            *lbr_context;
154         struct perf_branch_stack        lbr_stack;
155         struct perf_branch_entry        lbr_entries[MAX_LBR_ENTRIES];
156
157         /*
158          * manage shared (per-core, per-cpu) registers
159          * used on Intel NHM/WSM/SNB
160          */
161         struct intel_shared_regs        *shared_regs;
162
163         /*
164          * AMD specific bits
165          */
166         struct amd_nb           *amd_nb;
167 };
168
169 #define __EVENT_CONSTRAINT(c, n, m, w) {\
170         { .idxmsk64 = (n) },            \
171         .code = (c),                    \
172         .cmask = (m),                   \
173         .weight = (w),                  \
174 }
175
176 #define EVENT_CONSTRAINT(c, n, m)       \
177         __EVENT_CONSTRAINT(c, n, m, HWEIGHT(n))
178
179 /*
180  * Constraint on the Event code.
181  */
182 #define INTEL_EVENT_CONSTRAINT(c, n)    \
183         EVENT_CONSTRAINT(c, n, ARCH_PERFMON_EVENTSEL_EVENT)
184
185 /*
186  * Constraint on the Event code + UMask + fixed-mask
187  *
188  * filter mask to validate fixed counter events.
189  * the following filters disqualify for fixed counters:
190  *  - inv
191  *  - edge
192  *  - cnt-mask
193  *  The other filters are supported by fixed counters.
194  *  The any-thread option is supported starting with v3.
195  */
196 #define FIXED_EVENT_CONSTRAINT(c, n)    \
197         EVENT_CONSTRAINT(c, (1ULL << (32+n)), X86_RAW_EVENT_MASK)
198
199 /*
200  * Constraint on the Event code + UMask
201  */
202 #define INTEL_UEVENT_CONSTRAINT(c, n)   \
203         EVENT_CONSTRAINT(c, n, INTEL_ARCH_EVENT_MASK)
204
205 #define EVENT_CONSTRAINT_END            \
206         EVENT_CONSTRAINT(0, 0, 0)
207
208 #define for_each_event_constraint(e, c) \
209         for ((e) = (c); (e)->weight; (e)++)
210
211 /*
212  * Per register state.
213  */
214 struct er_account {
215         raw_spinlock_t          lock;   /* per-core: protect structure */
216         u64                     config; /* extra MSR config */
217         u64                     reg;    /* extra MSR number */
218         atomic_t                ref;    /* reference count */
219 };
220
221 /*
222  * Extra registers for specific events.
223  *
224  * Some events need large masks and require external MSRs.
225  * Those extra MSRs end up being shared for all events on
226  * a PMU and sometimes between PMU of sibling HT threads.
227  * In either case, the kernel needs to handle conflicting
228  * accesses to those extra, shared, regs. The data structure
229  * to manage those registers is stored in cpu_hw_event.
230  */
231 struct extra_reg {
232         unsigned int            event;
233         unsigned int            msr;
234         u64                     config_mask;
235         u64                     valid_mask;
236         int                     idx;  /* per_xxx->regs[] reg index */
237 };
238
239 #define EVENT_EXTRA_REG(e, ms, m, vm, i) {      \
240         .event = (e),           \
241         .msr = (ms),            \
242         .config_mask = (m),     \
243         .valid_mask = (vm),     \
244         .idx = EXTRA_REG_##i    \
245         }
246
247 #define INTEL_EVENT_EXTRA_REG(event, msr, vm, idx)      \
248         EVENT_EXTRA_REG(event, msr, ARCH_PERFMON_EVENTSEL_EVENT, vm, idx)
249
250 #define EVENT_EXTRA_END EVENT_EXTRA_REG(0, 0, 0, 0, RSP_0)
251
252 union perf_capabilities {
253         struct {
254                 u64     lbr_format    : 6;
255                 u64     pebs_trap     : 1;
256                 u64     pebs_arch_reg : 1;
257                 u64     pebs_format   : 4;
258                 u64     smm_freeze    : 1;
259         };
260         u64     capabilities;
261 };
262
263 /*
264  * struct x86_pmu - generic x86 pmu
265  */
266 struct x86_pmu {
267         /*
268          * Generic x86 PMC bits
269          */
270         const char      *name;
271         int             version;
272         int             (*handle_irq)(struct pt_regs *);
273         void            (*disable_all)(void);
274         void            (*enable_all)(int added);
275         void            (*enable)(struct perf_event *);
276         void            (*disable)(struct perf_event *);
277         void            (*hw_watchdog_set_attr)(struct perf_event_attr *attr);
278         int             (*hw_config)(struct perf_event *event);
279         int             (*schedule_events)(struct cpu_hw_events *cpuc, int n, int *assign);
280         unsigned        eventsel;
281         unsigned        perfctr;
282         u64             (*event_map)(int);
283         int             max_events;
284         int             num_counters;
285         int             num_counters_fixed;
286         int             cntval_bits;
287         u64             cntval_mask;
288         int             apic;
289         u64             max_period;
290         struct event_constraint *
291                         (*get_event_constraints)(struct cpu_hw_events *cpuc,
292                                                  struct perf_event *event);
293
294         void            (*put_event_constraints)(struct cpu_hw_events *cpuc,
295                                                  struct perf_event *event);
296         struct event_constraint *event_constraints;
297         void            (*quirks)(void);
298         int             perfctr_second_write;
299
300         int             (*cpu_prepare)(int cpu);
301         void            (*cpu_starting)(int cpu);
302         void            (*cpu_dying)(int cpu);
303         void            (*cpu_dead)(int cpu);
304
305         /*
306          * Intel Arch Perfmon v2+
307          */
308         u64                     intel_ctrl;
309         union perf_capabilities intel_cap;
310
311         /*
312          * Intel DebugStore bits
313          */
314         int             bts, pebs;
315         int             bts_active, pebs_active;
316         int             pebs_record_size;
317         void            (*drain_pebs)(struct pt_regs *regs);
318         struct event_constraint *pebs_constraints;
319
320         /*
321          * Intel LBR
322          */
323         unsigned long   lbr_tos, lbr_from, lbr_to; /* MSR base regs       */
324         int             lbr_nr;                    /* hardware stack size */
325
326         /*
327          * Extra registers for events
328          */
329         struct extra_reg *extra_regs;
330         unsigned int er_flags;
331 };
332
333 #define ERF_NO_HT_SHARING       1
334 #define ERF_HAS_RSP_1           2
335
336 static struct x86_pmu x86_pmu __read_mostly;
337
338 static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
339         .enabled = 1,
340 };
341
342 static int x86_perf_event_set_period(struct perf_event *event);
343
344 /*
345  * Generalized hw caching related hw_event table, filled
346  * in on a per model basis. A value of 0 means
347  * 'not supported', -1 means 'hw_event makes no sense on
348  * this CPU', any other value means the raw hw_event
349  * ID.
350  */
351
352 #define C(x) PERF_COUNT_HW_CACHE_##x
353
354 static u64 __read_mostly hw_cache_event_ids
355                                 [PERF_COUNT_HW_CACHE_MAX]
356                                 [PERF_COUNT_HW_CACHE_OP_MAX]
357                                 [PERF_COUNT_HW_CACHE_RESULT_MAX];
358 static u64 __read_mostly hw_cache_extra_regs
359                                 [PERF_COUNT_HW_CACHE_MAX]
360                                 [PERF_COUNT_HW_CACHE_OP_MAX]
361                                 [PERF_COUNT_HW_CACHE_RESULT_MAX];
362
363 void hw_nmi_watchdog_set_attr(struct perf_event_attr *wd_attr)
364 {
365         if (x86_pmu.hw_watchdog_set_attr)
366                 x86_pmu.hw_watchdog_set_attr(wd_attr);
367 }
368
369 /*
370  * Propagate event elapsed time into the generic event.
371  * Can only be executed on the CPU where the event is active.
372  * Returns the delta events processed.
373  */
374 static u64
375 x86_perf_event_update(struct perf_event *event)
376 {
377         struct hw_perf_event *hwc = &event->hw;
378         int shift = 64 - x86_pmu.cntval_bits;
379         u64 prev_raw_count, new_raw_count;
380         int idx = hwc->idx;
381         s64 delta;
382
383         if (idx == X86_PMC_IDX_FIXED_BTS)
384                 return 0;
385
386         /*
387          * Careful: an NMI might modify the previous event value.
388          *
389          * Our tactic to handle this is to first atomically read and
390          * exchange a new raw count - then add that new-prev delta
391          * count to the generic event atomically:
392          */
393 again:
394         prev_raw_count = local64_read(&hwc->prev_count);
395         rdmsrl(hwc->event_base, new_raw_count);
396
397         if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
398                                         new_raw_count) != prev_raw_count)
399                 goto again;
400
401         /*
402          * Now we have the new raw value and have updated the prev
403          * timestamp already. We can now calculate the elapsed delta
404          * (event-)time and add that to the generic event.
405          *
406          * Careful, not all hw sign-extends above the physical width
407          * of the count.
408          */
409         delta = (new_raw_count << shift) - (prev_raw_count << shift);
410         delta >>= shift;
411
412         local64_add(delta, &event->count);
413         local64_sub(delta, &hwc->period_left);
414
415         return new_raw_count;
416 }
417
418 static inline int x86_pmu_addr_offset(int index)
419 {
420         int offset;
421
422         /* offset = X86_FEATURE_PERFCTR_CORE ? index << 1 : index */
423         alternative_io(ASM_NOP2,
424                        "shll $1, %%eax",
425                        X86_FEATURE_PERFCTR_CORE,
426                        "=a" (offset),
427                        "a"  (index));
428
429         return offset;
430 }
431
432 static inline unsigned int x86_pmu_config_addr(int index)
433 {
434         return x86_pmu.eventsel + x86_pmu_addr_offset(index);
435 }
436
437 static inline unsigned int x86_pmu_event_addr(int index)
438 {
439         return x86_pmu.perfctr + x86_pmu_addr_offset(index);
440 }
441
442 /*
443  * Find and validate any extra registers to set up.
444  */
445 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
446 {
447         struct hw_perf_event_extra *reg;
448         struct extra_reg *er;
449
450         reg = &event->hw.extra_reg;
451
452         if (!x86_pmu.extra_regs)
453                 return 0;
454
455         for (er = x86_pmu.extra_regs; er->msr; er++) {
456                 if (er->event != (config & er->config_mask))
457                         continue;
458                 if (event->attr.config1 & ~er->valid_mask)
459                         return -EINVAL;
460
461                 reg->idx = er->idx;
462                 reg->config = event->attr.config1;
463                 reg->reg = er->msr;
464                 break;
465         }
466         return 0;
467 }
468
469 static atomic_t active_events;
470 static DEFINE_MUTEX(pmc_reserve_mutex);
471
472 #ifdef CONFIG_X86_LOCAL_APIC
473
474 static bool reserve_pmc_hardware(void)
475 {
476         int i;
477
478         for (i = 0; i < x86_pmu.num_counters; i++) {
479                 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
480                         goto perfctr_fail;
481         }
482
483         for (i = 0; i < x86_pmu.num_counters; i++) {
484                 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
485                         goto eventsel_fail;
486         }
487
488         return true;
489
490 eventsel_fail:
491         for (i--; i >= 0; i--)
492                 release_evntsel_nmi(x86_pmu_config_addr(i));
493
494         i = x86_pmu.num_counters;
495
496 perfctr_fail:
497         for (i--; i >= 0; i--)
498                 release_perfctr_nmi(x86_pmu_event_addr(i));
499
500         return false;
501 }
502
503 static void release_pmc_hardware(void)
504 {
505         int i;
506
507         for (i = 0; i < x86_pmu.num_counters; i++) {
508                 release_perfctr_nmi(x86_pmu_event_addr(i));
509                 release_evntsel_nmi(x86_pmu_config_addr(i));
510         }
511 }
512
513 #else
514
515 static bool reserve_pmc_hardware(void) { return true; }
516 static void release_pmc_hardware(void) {}
517
518 #endif
519
520 static bool check_hw_exists(void)
521 {
522         u64 val, val_new = 0;
523         int i, reg, ret = 0;
524
525         /*
526          * Check to see if the BIOS enabled any of the counters, if so
527          * complain and bail.
528          */
529         for (i = 0; i < x86_pmu.num_counters; i++) {
530                 reg = x86_pmu_config_addr(i);
531                 ret = rdmsrl_safe(reg, &val);
532                 if (ret)
533                         goto msr_fail;
534                 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
535                         goto bios_fail;
536         }
537
538         if (x86_pmu.num_counters_fixed) {
539                 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
540                 ret = rdmsrl_safe(reg, &val);
541                 if (ret)
542                         goto msr_fail;
543                 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
544                         if (val & (0x03 << i*4))
545                                 goto bios_fail;
546                 }
547         }
548
549         /*
550          * Now write a value and read it back to see if it matches,
551          * this is needed to detect certain hardware emulators (qemu/kvm)
552          * that don't trap on the MSR access and always return 0s.
553          */
554         val = 0xabcdUL;
555         ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
556         ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
557         if (ret || val != val_new)
558                 goto msr_fail;
559
560         return true;
561
562 bios_fail:
563         /*
564          * We still allow the PMU driver to operate:
565          */
566         printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
567         printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
568
569         return true;
570
571 msr_fail:
572         printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
573
574         return false;
575 }
576
577 static void reserve_ds_buffers(void);
578 static void release_ds_buffers(void);
579
580 static void hw_perf_event_destroy(struct perf_event *event)
581 {
582         if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
583                 release_pmc_hardware();
584                 release_ds_buffers();
585                 mutex_unlock(&pmc_reserve_mutex);
586         }
587 }
588
589 static inline int x86_pmu_initialized(void)
590 {
591         return x86_pmu.handle_irq != NULL;
592 }
593
594 static inline int
595 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
596 {
597         struct perf_event_attr *attr = &event->attr;
598         unsigned int cache_type, cache_op, cache_result;
599         u64 config, val;
600
601         config = attr->config;
602
603         cache_type = (config >>  0) & 0xff;
604         if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
605                 return -EINVAL;
606
607         cache_op = (config >>  8) & 0xff;
608         if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
609                 return -EINVAL;
610
611         cache_result = (config >> 16) & 0xff;
612         if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
613                 return -EINVAL;
614
615         val = hw_cache_event_ids[cache_type][cache_op][cache_result];
616
617         if (val == 0)
618                 return -ENOENT;
619
620         if (val == -1)
621                 return -EINVAL;
622
623         hwc->config |= val;
624         attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
625         return x86_pmu_extra_regs(val, event);
626 }
627
628 static int x86_setup_perfctr(struct perf_event *event)
629 {
630         struct perf_event_attr *attr = &event->attr;
631         struct hw_perf_event *hwc = &event->hw;
632         u64 config;
633
634         if (!is_sampling_event(event)) {
635                 hwc->sample_period = x86_pmu.max_period;
636                 hwc->last_period = hwc->sample_period;
637                 local64_set(&hwc->period_left, hwc->sample_period);
638         } else {
639                 /*
640                  * If we have a PMU initialized but no APIC
641                  * interrupts, we cannot sample hardware
642                  * events (user-space has to fall back and
643                  * sample via a hrtimer based software event):
644                  */
645                 if (!x86_pmu.apic)
646                         return -EOPNOTSUPP;
647         }
648
649         /*
650          * Do not allow config1 (extended registers) to propagate,
651          * there's no sane user-space generalization yet:
652          */
653         if (attr->type == PERF_TYPE_RAW)
654                 return 0;
655
656         if (attr->type == PERF_TYPE_HW_CACHE)
657                 return set_ext_hw_attr(hwc, event);
658
659         if (attr->config >= x86_pmu.max_events)
660                 return -EINVAL;
661
662         /*
663          * The generic map:
664          */
665         config = x86_pmu.event_map(attr->config);
666
667         if (config == 0)
668                 return -ENOENT;
669
670         if (config == -1LL)
671                 return -EINVAL;
672
673         /*
674          * Branch tracing:
675          */
676         if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
677             !attr->freq && hwc->sample_period == 1) {
678                 /* BTS is not supported by this architecture. */
679                 if (!x86_pmu.bts_active)
680                         return -EOPNOTSUPP;
681
682                 /* BTS is currently only allowed for user-mode. */
683                 if (!attr->exclude_kernel)
684                         return -EOPNOTSUPP;
685         }
686
687         hwc->config |= config;
688
689         return 0;
690 }
691
692 static int x86_pmu_hw_config(struct perf_event *event)
693 {
694         if (event->attr.precise_ip) {
695                 int precise = 0;
696
697                 /* Support for constant skid */
698                 if (x86_pmu.pebs_active) {
699                         precise++;
700
701                         /* Support for IP fixup */
702                         if (x86_pmu.lbr_nr)
703                                 precise++;
704                 }
705
706                 if (event->attr.precise_ip > precise)
707                         return -EOPNOTSUPP;
708         }
709
710         /*
711          * Generate PMC IRQs:
712          * (keep 'enabled' bit clear for now)
713          */
714         event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
715
716         /*
717          * Count user and OS events unless requested not to
718          */
719         if (!event->attr.exclude_user)
720                 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
721         if (!event->attr.exclude_kernel)
722                 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
723
724         if (event->attr.type == PERF_TYPE_RAW)
725                 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
726
727         return x86_setup_perfctr(event);
728 }
729
730 /*
731  * Setup the hardware configuration for a given attr_type
732  */
733 static int __x86_pmu_event_init(struct perf_event *event)
734 {
735         int err;
736
737         if (!x86_pmu_initialized())
738                 return -ENODEV;
739
740         err = 0;
741         if (!atomic_inc_not_zero(&active_events)) {
742                 mutex_lock(&pmc_reserve_mutex);
743                 if (atomic_read(&active_events) == 0) {
744                         if (!reserve_pmc_hardware())
745                                 err = -EBUSY;
746                         else
747                                 reserve_ds_buffers();
748                 }
749                 if (!err)
750                         atomic_inc(&active_events);
751                 mutex_unlock(&pmc_reserve_mutex);
752         }
753         if (err)
754                 return err;
755
756         event->destroy = hw_perf_event_destroy;
757
758         event->hw.idx = -1;
759         event->hw.last_cpu = -1;
760         event->hw.last_tag = ~0ULL;
761
762         /* mark unused */
763         event->hw.extra_reg.idx = EXTRA_REG_NONE;
764
765         return x86_pmu.hw_config(event);
766 }
767
768 static void x86_pmu_disable_all(void)
769 {
770         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
771         int idx;
772
773         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
774                 u64 val;
775
776                 if (!test_bit(idx, cpuc->active_mask))
777                         continue;
778                 rdmsrl(x86_pmu_config_addr(idx), val);
779                 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
780                         continue;
781                 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
782                 wrmsrl(x86_pmu_config_addr(idx), val);
783         }
784 }
785
786 static void x86_pmu_disable(struct pmu *pmu)
787 {
788         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
789
790         if (!x86_pmu_initialized())
791                 return;
792
793         if (!cpuc->enabled)
794                 return;
795
796         cpuc->n_added = 0;
797         cpuc->enabled = 0;
798         barrier();
799
800         x86_pmu.disable_all();
801 }
802
803 static inline void __x86_pmu_enable_event(struct hw_perf_event *hwc,
804                                           u64 enable_mask)
805 {
806         if (hwc->extra_reg.reg)
807                 wrmsrl(hwc->extra_reg.reg, hwc->extra_reg.config);
808         wrmsrl(hwc->config_base, hwc->config | enable_mask);
809 }
810
811 static void x86_pmu_enable_all(int added)
812 {
813         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
814         int idx;
815
816         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
817                 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
818
819                 if (!test_bit(idx, cpuc->active_mask))
820                         continue;
821
822                 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
823         }
824 }
825
826 static struct pmu pmu;
827
828 static inline int is_x86_event(struct perf_event *event)
829 {
830         return event->pmu == &pmu;
831 }
832
833 static int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
834 {
835         struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
836         unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
837         int i, j, w, wmax, num = 0;
838         struct hw_perf_event *hwc;
839
840         bitmap_zero(used_mask, X86_PMC_IDX_MAX);
841
842         for (i = 0; i < n; i++) {
843                 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
844                 constraints[i] = c;
845         }
846
847         /*
848          * fastpath, try to reuse previous register
849          */
850         for (i = 0; i < n; i++) {
851                 hwc = &cpuc->event_list[i]->hw;
852                 c = constraints[i];
853
854                 /* never assigned */
855                 if (hwc->idx == -1)
856                         break;
857
858                 /* constraint still honored */
859                 if (!test_bit(hwc->idx, c->idxmsk))
860                         break;
861
862                 /* not already used */
863                 if (test_bit(hwc->idx, used_mask))
864                         break;
865
866                 __set_bit(hwc->idx, used_mask);
867                 if (assign)
868                         assign[i] = hwc->idx;
869         }
870         if (i == n)
871                 goto done;
872
873         /*
874          * begin slow path
875          */
876
877         bitmap_zero(used_mask, X86_PMC_IDX_MAX);
878
879         /*
880          * weight = number of possible counters
881          *
882          * 1    = most constrained, only works on one counter
883          * wmax = least constrained, works on any counter
884          *
885          * assign events to counters starting with most
886          * constrained events.
887          */
888         wmax = x86_pmu.num_counters;
889
890         /*
891          * when fixed event counters are present,
892          * wmax is incremented by 1 to account
893          * for one more choice
894          */
895         if (x86_pmu.num_counters_fixed)
896                 wmax++;
897
898         for (w = 1, num = n; num && w <= wmax; w++) {
899                 /* for each event */
900                 for (i = 0; num && i < n; i++) {
901                         c = constraints[i];
902                         hwc = &cpuc->event_list[i]->hw;
903
904                         if (c->weight != w)
905                                 continue;
906
907                         for_each_set_bit(j, c->idxmsk, X86_PMC_IDX_MAX) {
908                                 if (!test_bit(j, used_mask))
909                                         break;
910                         }
911
912                         if (j == X86_PMC_IDX_MAX)
913                                 break;
914
915                         __set_bit(j, used_mask);
916
917                         if (assign)
918                                 assign[i] = j;
919                         num--;
920                 }
921         }
922 done:
923         /*
924          * scheduling failed or is just a simulation,
925          * free resources if necessary
926          */
927         if (!assign || num) {
928                 for (i = 0; i < n; i++) {
929                         if (x86_pmu.put_event_constraints)
930                                 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
931                 }
932         }
933         return num ? -ENOSPC : 0;
934 }
935
936 /*
937  * dogrp: true if must collect siblings events (group)
938  * returns total number of events and error code
939  */
940 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
941 {
942         struct perf_event *event;
943         int n, max_count;
944
945         max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
946
947         /* current number of events already accepted */
948         n = cpuc->n_events;
949
950         if (is_x86_event(leader)) {
951                 if (n >= max_count)
952                         return -ENOSPC;
953                 cpuc->event_list[n] = leader;
954                 n++;
955         }
956         if (!dogrp)
957                 return n;
958
959         list_for_each_entry(event, &leader->sibling_list, group_entry) {
960                 if (!is_x86_event(event) ||
961                     event->state <= PERF_EVENT_STATE_OFF)
962                         continue;
963
964                 if (n >= max_count)
965                         return -ENOSPC;
966
967                 cpuc->event_list[n] = event;
968                 n++;
969         }
970         return n;
971 }
972
973 static inline void x86_assign_hw_event(struct perf_event *event,
974                                 struct cpu_hw_events *cpuc, int i)
975 {
976         struct hw_perf_event *hwc = &event->hw;
977
978         hwc->idx = cpuc->assign[i];
979         hwc->last_cpu = smp_processor_id();
980         hwc->last_tag = ++cpuc->tags[i];
981
982         if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
983                 hwc->config_base = 0;
984                 hwc->event_base = 0;
985         } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
986                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
987                 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
988         } else {
989                 hwc->config_base = x86_pmu_config_addr(hwc->idx);
990                 hwc->event_base  = x86_pmu_event_addr(hwc->idx);
991         }
992 }
993
994 static inline int match_prev_assignment(struct hw_perf_event *hwc,
995                                         struct cpu_hw_events *cpuc,
996                                         int i)
997 {
998         return hwc->idx == cpuc->assign[i] &&
999                 hwc->last_cpu == smp_processor_id() &&
1000                 hwc->last_tag == cpuc->tags[i];
1001 }
1002
1003 static void x86_pmu_start(struct perf_event *event, int flags);
1004 static void x86_pmu_stop(struct perf_event *event, int flags);
1005
1006 static void x86_pmu_enable(struct pmu *pmu)
1007 {
1008         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1009         struct perf_event *event;
1010         struct hw_perf_event *hwc;
1011         int i, added = cpuc->n_added;
1012
1013         if (!x86_pmu_initialized())
1014                 return;
1015
1016         if (cpuc->enabled)
1017                 return;
1018
1019         if (cpuc->n_added) {
1020                 int n_running = cpuc->n_events - cpuc->n_added;
1021                 /*
1022                  * apply assignment obtained either from
1023                  * hw_perf_group_sched_in() or x86_pmu_enable()
1024                  *
1025                  * step1: save events moving to new counters
1026                  * step2: reprogram moved events into new counters
1027                  */
1028                 for (i = 0; i < n_running; i++) {
1029                         event = cpuc->event_list[i];
1030                         hwc = &event->hw;
1031
1032                         /*
1033                          * we can avoid reprogramming counter if:
1034                          * - assigned same counter as last time
1035                          * - running on same CPU as last time
1036                          * - no other event has used the counter since
1037                          */
1038                         if (hwc->idx == -1 ||
1039                             match_prev_assignment(hwc, cpuc, i))
1040                                 continue;
1041
1042                         /*
1043                          * Ensure we don't accidentally enable a stopped
1044                          * counter simply because we rescheduled.
1045                          */
1046                         if (hwc->state & PERF_HES_STOPPED)
1047                                 hwc->state |= PERF_HES_ARCH;
1048
1049                         x86_pmu_stop(event, PERF_EF_UPDATE);
1050                 }
1051
1052                 for (i = 0; i < cpuc->n_events; i++) {
1053                         event = cpuc->event_list[i];
1054                         hwc = &event->hw;
1055
1056                         if (!match_prev_assignment(hwc, cpuc, i))
1057                                 x86_assign_hw_event(event, cpuc, i);
1058                         else if (i < n_running)
1059                                 continue;
1060
1061                         if (hwc->state & PERF_HES_ARCH)
1062                                 continue;
1063
1064                         x86_pmu_start(event, PERF_EF_RELOAD);
1065                 }
1066                 cpuc->n_added = 0;
1067                 perf_events_lapic_init();
1068         }
1069
1070         cpuc->enabled = 1;
1071         barrier();
1072
1073         x86_pmu.enable_all(added);
1074 }
1075
1076 static inline void x86_pmu_disable_event(struct perf_event *event)
1077 {
1078         struct hw_perf_event *hwc = &event->hw;
1079
1080         wrmsrl(hwc->config_base, hwc->config);
1081 }
1082
1083 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1084
1085 /*
1086  * Set the next IRQ period, based on the hwc->period_left value.
1087  * To be called with the event disabled in hw:
1088  */
1089 static int
1090 x86_perf_event_set_period(struct perf_event *event)
1091 {
1092         struct hw_perf_event *hwc = &event->hw;
1093         s64 left = local64_read(&hwc->period_left);
1094         s64 period = hwc->sample_period;
1095         int ret = 0, idx = hwc->idx;
1096
1097         if (idx == X86_PMC_IDX_FIXED_BTS)
1098                 return 0;
1099
1100         /*
1101          * If we are way outside a reasonable range then just skip forward:
1102          */
1103         if (unlikely(left <= -period)) {
1104                 left = period;
1105                 local64_set(&hwc->period_left, left);
1106                 hwc->last_period = period;
1107                 ret = 1;
1108         }
1109
1110         if (unlikely(left <= 0)) {
1111                 left += period;
1112                 local64_set(&hwc->period_left, left);
1113                 hwc->last_period = period;
1114                 ret = 1;
1115         }
1116         /*
1117          * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1118          */
1119         if (unlikely(left < 2))
1120                 left = 2;
1121
1122         if (left > x86_pmu.max_period)
1123                 left = x86_pmu.max_period;
1124
1125         per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1126
1127         /*
1128          * The hw event starts counting from this event offset,
1129          * mark it to be able to extra future deltas:
1130          */
1131         local64_set(&hwc->prev_count, (u64)-left);
1132
1133         wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1134
1135         /*
1136          * Due to erratum on certan cpu we need
1137          * a second write to be sure the register
1138          * is updated properly
1139          */
1140         if (x86_pmu.perfctr_second_write) {
1141                 wrmsrl(hwc->event_base,
1142                         (u64)(-left) & x86_pmu.cntval_mask);
1143         }
1144
1145         perf_event_update_userpage(event);
1146
1147         return ret;
1148 }
1149
1150 static void x86_pmu_enable_event(struct perf_event *event)
1151 {
1152         if (__this_cpu_read(cpu_hw_events.enabled))
1153                 __x86_pmu_enable_event(&event->hw,
1154                                        ARCH_PERFMON_EVENTSEL_ENABLE);
1155 }
1156
1157 /*
1158  * Add a single event to the PMU.
1159  *
1160  * The event is added to the group of enabled events
1161  * but only if it can be scehduled with existing events.
1162  */
1163 static int x86_pmu_add(struct perf_event *event, int flags)
1164 {
1165         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1166         struct hw_perf_event *hwc;
1167         int assign[X86_PMC_IDX_MAX];
1168         int n, n0, ret;
1169
1170         hwc = &event->hw;
1171
1172         perf_pmu_disable(event->pmu);
1173         n0 = cpuc->n_events;
1174         ret = n = collect_events(cpuc, event, false);
1175         if (ret < 0)
1176                 goto out;
1177
1178         hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1179         if (!(flags & PERF_EF_START))
1180                 hwc->state |= PERF_HES_ARCH;
1181
1182         /*
1183          * If group events scheduling transaction was started,
1184          * skip the schedulability test here, it will be performed
1185          * at commit time (->commit_txn) as a whole
1186          */
1187         if (cpuc->group_flag & PERF_EVENT_TXN)
1188                 goto done_collect;
1189
1190         ret = x86_pmu.schedule_events(cpuc, n, assign);
1191         if (ret)
1192                 goto out;
1193         /*
1194          * copy new assignment, now we know it is possible
1195          * will be used by hw_perf_enable()
1196          */
1197         memcpy(cpuc->assign, assign, n*sizeof(int));
1198
1199 done_collect:
1200         cpuc->n_events = n;
1201         cpuc->n_added += n - n0;
1202         cpuc->n_txn += n - n0;
1203
1204         ret = 0;
1205 out:
1206         perf_pmu_enable(event->pmu);
1207         return ret;
1208 }
1209
1210 static void x86_pmu_start(struct perf_event *event, int flags)
1211 {
1212         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1213         int idx = event->hw.idx;
1214
1215         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1216                 return;
1217
1218         if (WARN_ON_ONCE(idx == -1))
1219                 return;
1220
1221         if (flags & PERF_EF_RELOAD) {
1222                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1223                 x86_perf_event_set_period(event);
1224         }
1225
1226         event->hw.state = 0;
1227
1228         cpuc->events[idx] = event;
1229         __set_bit(idx, cpuc->active_mask);
1230         __set_bit(idx, cpuc->running);
1231         x86_pmu.enable(event);
1232         perf_event_update_userpage(event);
1233 }
1234
1235 void perf_event_print_debug(void)
1236 {
1237         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1238         u64 pebs;
1239         struct cpu_hw_events *cpuc;
1240         unsigned long flags;
1241         int cpu, idx;
1242
1243         if (!x86_pmu.num_counters)
1244                 return;
1245
1246         local_irq_save(flags);
1247
1248         cpu = smp_processor_id();
1249         cpuc = &per_cpu(cpu_hw_events, cpu);
1250
1251         if (x86_pmu.version >= 2) {
1252                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1253                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1254                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1255                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1256                 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1257
1258                 pr_info("\n");
1259                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
1260                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
1261                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
1262                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
1263                 pr_info("CPU#%d: pebs:       %016llx\n", cpu, pebs);
1264         }
1265         pr_info("CPU#%d: active:     %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1266
1267         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1268                 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1269                 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1270
1271                 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1272
1273                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
1274                         cpu, idx, pmc_ctrl);
1275                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
1276                         cpu, idx, pmc_count);
1277                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
1278                         cpu, idx, prev_left);
1279         }
1280         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1281                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1282
1283                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1284                         cpu, idx, pmc_count);
1285         }
1286         local_irq_restore(flags);
1287 }
1288
1289 static void x86_pmu_stop(struct perf_event *event, int flags)
1290 {
1291         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1292         struct hw_perf_event *hwc = &event->hw;
1293
1294         if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1295                 x86_pmu.disable(event);
1296                 cpuc->events[hwc->idx] = NULL;
1297                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1298                 hwc->state |= PERF_HES_STOPPED;
1299         }
1300
1301         if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1302                 /*
1303                  * Drain the remaining delta count out of a event
1304                  * that we are disabling:
1305                  */
1306                 x86_perf_event_update(event);
1307                 hwc->state |= PERF_HES_UPTODATE;
1308         }
1309 }
1310
1311 static void x86_pmu_del(struct perf_event *event, int flags)
1312 {
1313         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1314         int i;
1315
1316         /*
1317          * If we're called during a txn, we don't need to do anything.
1318          * The events never got scheduled and ->cancel_txn will truncate
1319          * the event_list.
1320          */
1321         if (cpuc->group_flag & PERF_EVENT_TXN)
1322                 return;
1323
1324         x86_pmu_stop(event, PERF_EF_UPDATE);
1325
1326         for (i = 0; i < cpuc->n_events; i++) {
1327                 if (event == cpuc->event_list[i]) {
1328
1329                         if (x86_pmu.put_event_constraints)
1330                                 x86_pmu.put_event_constraints(cpuc, event);
1331
1332                         while (++i < cpuc->n_events)
1333                                 cpuc->event_list[i-1] = cpuc->event_list[i];
1334
1335                         --cpuc->n_events;
1336                         break;
1337                 }
1338         }
1339         perf_event_update_userpage(event);
1340 }
1341
1342 static int x86_pmu_handle_irq(struct pt_regs *regs)
1343 {
1344         struct perf_sample_data data;
1345         struct cpu_hw_events *cpuc;
1346         struct perf_event *event;
1347         int idx, handled = 0;
1348         u64 val;
1349
1350         perf_sample_data_init(&data, 0);
1351
1352         cpuc = &__get_cpu_var(cpu_hw_events);
1353
1354         /*
1355          * Some chipsets need to unmask the LVTPC in a particular spot
1356          * inside the nmi handler.  As a result, the unmasking was pushed
1357          * into all the nmi handlers.
1358          *
1359          * This generic handler doesn't seem to have any issues where the
1360          * unmasking occurs so it was left at the top.
1361          */
1362         apic_write(APIC_LVTPC, APIC_DM_NMI);
1363
1364         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1365                 if (!test_bit(idx, cpuc->active_mask)) {
1366                         /*
1367                          * Though we deactivated the counter some cpus
1368                          * might still deliver spurious interrupts still
1369                          * in flight. Catch them:
1370                          */
1371                         if (__test_and_clear_bit(idx, cpuc->running))
1372                                 handled++;
1373                         continue;
1374                 }
1375
1376                 event = cpuc->events[idx];
1377
1378                 val = x86_perf_event_update(event);
1379                 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1380                         continue;
1381
1382                 /*
1383                  * event overflow
1384                  */
1385                 handled++;
1386                 data.period     = event->hw.last_period;
1387
1388                 if (!x86_perf_event_set_period(event))
1389                         continue;
1390
1391                 if (perf_event_overflow(event, &data, regs))
1392                         x86_pmu_stop(event, 0);
1393         }
1394
1395         if (handled)
1396                 inc_irq_stat(apic_perf_irqs);
1397
1398         return handled;
1399 }
1400
1401 void perf_events_lapic_init(void)
1402 {
1403         if (!x86_pmu.apic || !x86_pmu_initialized())
1404                 return;
1405
1406         /*
1407          * Always use NMI for PMU
1408          */
1409         apic_write(APIC_LVTPC, APIC_DM_NMI);
1410 }
1411
1412 struct pmu_nmi_state {
1413         unsigned int    marked;
1414         int             handled;
1415 };
1416
1417 static DEFINE_PER_CPU(struct pmu_nmi_state, pmu_nmi);
1418
1419 static int __kprobes
1420 perf_event_nmi_handler(struct notifier_block *self,
1421                          unsigned long cmd, void *__args)
1422 {
1423         struct die_args *args = __args;
1424         unsigned int this_nmi;
1425         int handled;
1426
1427         if (!atomic_read(&active_events))
1428                 return NOTIFY_DONE;
1429
1430         switch (cmd) {
1431         case DIE_NMI:
1432                 break;
1433         case DIE_NMIUNKNOWN:
1434                 this_nmi = percpu_read(irq_stat.__nmi_count);
1435                 if (this_nmi != __this_cpu_read(pmu_nmi.marked))
1436                         /* let the kernel handle the unknown nmi */
1437                         return NOTIFY_DONE;
1438                 /*
1439                  * This one is a PMU back-to-back nmi. Two events
1440                  * trigger 'simultaneously' raising two back-to-back
1441                  * NMIs. If the first NMI handles both, the latter
1442                  * will be empty and daze the CPU. So, we drop it to
1443                  * avoid false-positive 'unknown nmi' messages.
1444                  */
1445                 return NOTIFY_STOP;
1446         default:
1447                 return NOTIFY_DONE;
1448         }
1449
1450         handled = x86_pmu.handle_irq(args->regs);
1451         if (!handled)
1452                 return NOTIFY_DONE;
1453
1454         this_nmi = percpu_read(irq_stat.__nmi_count);
1455         if ((handled > 1) ||
1456                 /* the next nmi could be a back-to-back nmi */
1457             ((__this_cpu_read(pmu_nmi.marked) == this_nmi) &&
1458              (__this_cpu_read(pmu_nmi.handled) > 1))) {
1459                 /*
1460                  * We could have two subsequent back-to-back nmis: The
1461                  * first handles more than one counter, the 2nd
1462                  * handles only one counter and the 3rd handles no
1463                  * counter.
1464                  *
1465                  * This is the 2nd nmi because the previous was
1466                  * handling more than one counter. We will mark the
1467                  * next (3rd) and then drop it if unhandled.
1468                  */
1469                 __this_cpu_write(pmu_nmi.marked, this_nmi + 1);
1470                 __this_cpu_write(pmu_nmi.handled, handled);
1471         }
1472
1473         return NOTIFY_STOP;
1474 }
1475
1476 static __read_mostly struct notifier_block perf_event_nmi_notifier = {
1477         .notifier_call          = perf_event_nmi_handler,
1478         .next                   = NULL,
1479         .priority               = NMI_LOCAL_LOW_PRIOR,
1480 };
1481
1482 static struct event_constraint unconstrained;
1483 static struct event_constraint emptyconstraint;
1484
1485 static struct event_constraint *
1486 x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
1487 {
1488         struct event_constraint *c;
1489
1490         if (x86_pmu.event_constraints) {
1491                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1492                         if ((event->hw.config & c->cmask) == c->code)
1493                                 return c;
1494                 }
1495         }
1496
1497         return &unconstrained;
1498 }
1499
1500 #include "perf_event_amd.c"
1501 #include "perf_event_p6.c"
1502 #include "perf_event_p4.c"
1503 #include "perf_event_intel_lbr.c"
1504 #include "perf_event_intel_ds.c"
1505 #include "perf_event_intel.c"
1506
1507 static int __cpuinit
1508 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1509 {
1510         unsigned int cpu = (long)hcpu;
1511         int ret = NOTIFY_OK;
1512
1513         switch (action & ~CPU_TASKS_FROZEN) {
1514         case CPU_UP_PREPARE:
1515                 if (x86_pmu.cpu_prepare)
1516                         ret = x86_pmu.cpu_prepare(cpu);
1517                 break;
1518
1519         case CPU_STARTING:
1520                 if (x86_pmu.cpu_starting)
1521                         x86_pmu.cpu_starting(cpu);
1522                 break;
1523
1524         case CPU_DYING:
1525                 if (x86_pmu.cpu_dying)
1526                         x86_pmu.cpu_dying(cpu);
1527                 break;
1528
1529         case CPU_UP_CANCELED:
1530         case CPU_DEAD:
1531                 if (x86_pmu.cpu_dead)
1532                         x86_pmu.cpu_dead(cpu);
1533                 break;
1534
1535         default:
1536                 break;
1537         }
1538
1539         return ret;
1540 }
1541
1542 static void __init pmu_check_apic(void)
1543 {
1544         if (cpu_has_apic)
1545                 return;
1546
1547         x86_pmu.apic = 0;
1548         pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1549         pr_info("no hardware sampling interrupt available.\n");
1550 }
1551
1552 static int __init init_hw_perf_events(void)
1553 {
1554         struct event_constraint *c;
1555         int err;
1556
1557         pr_info("Performance Events: ");
1558
1559         switch (boot_cpu_data.x86_vendor) {
1560         case X86_VENDOR_INTEL:
1561                 err = intel_pmu_init();
1562                 break;
1563         case X86_VENDOR_AMD:
1564                 err = amd_pmu_init();
1565                 break;
1566         default:
1567                 return 0;
1568         }
1569         if (err != 0) {
1570                 pr_cont("no PMU driver, software events only.\n");
1571                 return 0;
1572         }
1573
1574         pmu_check_apic();
1575
1576         /* sanity check that the hardware exists or is emulated */
1577         if (!check_hw_exists())
1578                 return 0;
1579
1580         pr_cont("%s PMU driver.\n", x86_pmu.name);
1581
1582         if (x86_pmu.quirks)
1583                 x86_pmu.quirks();
1584
1585         if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1586                 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1587                      x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1588                 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1589         }
1590         x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1591
1592         if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1593                 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1594                      x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1595                 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1596         }
1597
1598         x86_pmu.intel_ctrl |=
1599                 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1600
1601         perf_events_lapic_init();
1602         register_die_notifier(&perf_event_nmi_notifier);
1603
1604         unconstrained = (struct event_constraint)
1605                 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1606                                    0, x86_pmu.num_counters);
1607
1608         if (x86_pmu.event_constraints) {
1609                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1610                         if (c->cmask != X86_RAW_EVENT_MASK)
1611                                 continue;
1612
1613                         c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1614                         c->weight += x86_pmu.num_counters;
1615                 }
1616         }
1617
1618         pr_info("... version:                %d\n",     x86_pmu.version);
1619         pr_info("... bit width:              %d\n",     x86_pmu.cntval_bits);
1620         pr_info("... generic registers:      %d\n",     x86_pmu.num_counters);
1621         pr_info("... value mask:             %016Lx\n", x86_pmu.cntval_mask);
1622         pr_info("... max period:             %016Lx\n", x86_pmu.max_period);
1623         pr_info("... fixed-purpose events:   %d\n",     x86_pmu.num_counters_fixed);
1624         pr_info("... event mask:             %016Lx\n", x86_pmu.intel_ctrl);
1625
1626         perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1627         perf_cpu_notifier(x86_pmu_notifier);
1628
1629         return 0;
1630 }
1631 early_initcall(init_hw_perf_events);
1632
1633 static inline void x86_pmu_read(struct perf_event *event)
1634 {
1635         x86_perf_event_update(event);
1636 }
1637
1638 /*
1639  * Start group events scheduling transaction
1640  * Set the flag to make pmu::enable() not perform the
1641  * schedulability test, it will be performed at commit time
1642  */
1643 static void x86_pmu_start_txn(struct pmu *pmu)
1644 {
1645         perf_pmu_disable(pmu);
1646         __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1647         __this_cpu_write(cpu_hw_events.n_txn, 0);
1648 }
1649
1650 /*
1651  * Stop group events scheduling transaction
1652  * Clear the flag and pmu::enable() will perform the
1653  * schedulability test.
1654  */
1655 static void x86_pmu_cancel_txn(struct pmu *pmu)
1656 {
1657         __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1658         /*
1659          * Truncate the collected events.
1660          */
1661         __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1662         __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1663         perf_pmu_enable(pmu);
1664 }
1665
1666 /*
1667  * Commit group events scheduling transaction
1668  * Perform the group schedulability test as a whole
1669  * Return 0 if success
1670  */
1671 static int x86_pmu_commit_txn(struct pmu *pmu)
1672 {
1673         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1674         int assign[X86_PMC_IDX_MAX];
1675         int n, ret;
1676
1677         n = cpuc->n_events;
1678
1679         if (!x86_pmu_initialized())
1680                 return -EAGAIN;
1681
1682         ret = x86_pmu.schedule_events(cpuc, n, assign);
1683         if (ret)
1684                 return ret;
1685
1686         /*
1687          * copy new assignment, now we know it is possible
1688          * will be used by hw_perf_enable()
1689          */
1690         memcpy(cpuc->assign, assign, n*sizeof(int));
1691
1692         cpuc->group_flag &= ~PERF_EVENT_TXN;
1693         perf_pmu_enable(pmu);
1694         return 0;
1695 }
1696 /*
1697  * a fake_cpuc is used to validate event groups. Due to
1698  * the extra reg logic, we need to also allocate a fake
1699  * per_core and per_cpu structure. Otherwise, group events
1700  * using extra reg may conflict without the kernel being
1701  * able to catch this when the last event gets added to
1702  * the group.
1703  */
1704 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1705 {
1706         kfree(cpuc->shared_regs);
1707         kfree(cpuc);
1708 }
1709
1710 static struct cpu_hw_events *allocate_fake_cpuc(void)
1711 {
1712         struct cpu_hw_events *cpuc;
1713         int cpu = raw_smp_processor_id();
1714
1715         cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1716         if (!cpuc)
1717                 return ERR_PTR(-ENOMEM);
1718
1719         /* only needed, if we have extra_regs */
1720         if (x86_pmu.extra_regs) {
1721                 cpuc->shared_regs = allocate_shared_regs(cpu);
1722                 if (!cpuc->shared_regs)
1723                         goto error;
1724         }
1725         return cpuc;
1726 error:
1727         free_fake_cpuc(cpuc);
1728         return ERR_PTR(-ENOMEM);
1729 }
1730
1731 /*
1732  * validate that we can schedule this event
1733  */
1734 static int validate_event(struct perf_event *event)
1735 {
1736         struct cpu_hw_events *fake_cpuc;
1737         struct event_constraint *c;
1738         int ret = 0;
1739
1740         fake_cpuc = allocate_fake_cpuc();
1741         if (IS_ERR(fake_cpuc))
1742                 return PTR_ERR(fake_cpuc);
1743
1744         c = x86_pmu.get_event_constraints(fake_cpuc, event);
1745
1746         if (!c || !c->weight)
1747                 ret = -ENOSPC;
1748
1749         if (x86_pmu.put_event_constraints)
1750                 x86_pmu.put_event_constraints(fake_cpuc, event);
1751
1752         free_fake_cpuc(fake_cpuc);
1753
1754         return ret;
1755 }
1756
1757 /*
1758  * validate a single event group
1759  *
1760  * validation include:
1761  *      - check events are compatible which each other
1762  *      - events do not compete for the same counter
1763  *      - number of events <= number of counters
1764  *
1765  * validation ensures the group can be loaded onto the
1766  * PMU if it was the only group available.
1767  */
1768 static int validate_group(struct perf_event *event)
1769 {
1770         struct perf_event *leader = event->group_leader;
1771         struct cpu_hw_events *fake_cpuc;
1772         int ret = -ENOSPC, n;
1773
1774         fake_cpuc = allocate_fake_cpuc();
1775         if (IS_ERR(fake_cpuc))
1776                 return PTR_ERR(fake_cpuc);
1777         /*
1778          * the event is not yet connected with its
1779          * siblings therefore we must first collect
1780          * existing siblings, then add the new event
1781          * before we can simulate the scheduling
1782          */
1783         n = collect_events(fake_cpuc, leader, true);
1784         if (n < 0)
1785                 goto out;
1786
1787         fake_cpuc->n_events = n;
1788         n = collect_events(fake_cpuc, event, false);
1789         if (n < 0)
1790                 goto out;
1791
1792         fake_cpuc->n_events = n;
1793
1794         ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1795
1796 out:
1797         free_fake_cpuc(fake_cpuc);
1798         return ret;
1799 }
1800
1801 static int x86_pmu_event_init(struct perf_event *event)
1802 {
1803         struct pmu *tmp;
1804         int err;
1805
1806         switch (event->attr.type) {
1807         case PERF_TYPE_RAW:
1808         case PERF_TYPE_HARDWARE:
1809         case PERF_TYPE_HW_CACHE:
1810                 break;
1811
1812         default:
1813                 return -ENOENT;
1814         }
1815
1816         err = __x86_pmu_event_init(event);
1817         if (!err) {
1818                 /*
1819                  * we temporarily connect event to its pmu
1820                  * such that validate_group() can classify
1821                  * it as an x86 event using is_x86_event()
1822                  */
1823                 tmp = event->pmu;
1824                 event->pmu = &pmu;
1825
1826                 if (event->group_leader != event)
1827                         err = validate_group(event);
1828                 else
1829                         err = validate_event(event);
1830
1831                 event->pmu = tmp;
1832         }
1833         if (err) {
1834                 if (event->destroy)
1835                         event->destroy(event);
1836         }
1837
1838         return err;
1839 }
1840
1841 static struct pmu pmu = {
1842         .pmu_enable     = x86_pmu_enable,
1843         .pmu_disable    = x86_pmu_disable,
1844
1845         .event_init     = x86_pmu_event_init,
1846
1847         .add            = x86_pmu_add,
1848         .del            = x86_pmu_del,
1849         .start          = x86_pmu_start,
1850         .stop           = x86_pmu_stop,
1851         .read           = x86_pmu_read,
1852
1853         .start_txn      = x86_pmu_start_txn,
1854         .cancel_txn     = x86_pmu_cancel_txn,
1855         .commit_txn     = x86_pmu_commit_txn,
1856 };
1857
1858 /*
1859  * callchain support
1860  */
1861
1862 static int backtrace_stack(void *data, char *name)
1863 {
1864         return 0;
1865 }
1866
1867 static void backtrace_address(void *data, unsigned long addr, int reliable)
1868 {
1869         struct perf_callchain_entry *entry = data;
1870
1871         perf_callchain_store(entry, addr);
1872 }
1873
1874 static const struct stacktrace_ops backtrace_ops = {
1875         .stack                  = backtrace_stack,
1876         .address                = backtrace_address,
1877         .walk_stack             = print_context_stack_bp,
1878 };
1879
1880 void
1881 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1882 {
1883         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1884                 /* TODO: We don't support guest os callchain now */
1885                 return;
1886         }
1887
1888         perf_callchain_store(entry, regs->ip);
1889
1890         dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1891 }
1892
1893 #ifdef CONFIG_COMPAT
1894 static inline int
1895 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1896 {
1897         /* 32-bit process in 64-bit kernel. */
1898         struct stack_frame_ia32 frame;
1899         const void __user *fp;
1900
1901         if (!test_thread_flag(TIF_IA32))
1902                 return 0;
1903
1904         fp = compat_ptr(regs->bp);
1905         while (entry->nr < PERF_MAX_STACK_DEPTH) {
1906                 unsigned long bytes;
1907                 frame.next_frame     = 0;
1908                 frame.return_address = 0;
1909
1910                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1911                 if (bytes != sizeof(frame))
1912                         break;
1913
1914                 if (fp < compat_ptr(regs->sp))
1915                         break;
1916
1917                 perf_callchain_store(entry, frame.return_address);
1918                 fp = compat_ptr(frame.next_frame);
1919         }
1920         return 1;
1921 }
1922 #else
1923 static inline int
1924 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1925 {
1926     return 0;
1927 }
1928 #endif
1929
1930 void
1931 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1932 {
1933         struct stack_frame frame;
1934         const void __user *fp;
1935
1936         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1937                 /* TODO: We don't support guest os callchain now */
1938                 return;
1939         }
1940
1941         fp = (void __user *)regs->bp;
1942
1943         perf_callchain_store(entry, regs->ip);
1944
1945         if (perf_callchain_user32(regs, entry))
1946                 return;
1947
1948         while (entry->nr < PERF_MAX_STACK_DEPTH) {
1949                 unsigned long bytes;
1950                 frame.next_frame             = NULL;
1951                 frame.return_address = 0;
1952
1953                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1954                 if (bytes != sizeof(frame))
1955                         break;
1956
1957                 if ((unsigned long)fp < regs->sp)
1958                         break;
1959
1960                 perf_callchain_store(entry, frame.return_address);
1961                 fp = frame.next_frame;
1962         }
1963 }
1964
1965 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1966 {
1967         unsigned long ip;
1968
1969         if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1970                 ip = perf_guest_cbs->get_guest_ip();
1971         else
1972                 ip = instruction_pointer(regs);
1973
1974         return ip;
1975 }
1976
1977 unsigned long perf_misc_flags(struct pt_regs *regs)
1978 {
1979         int misc = 0;
1980
1981         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1982                 if (perf_guest_cbs->is_user_mode())
1983                         misc |= PERF_RECORD_MISC_GUEST_USER;
1984                 else
1985                         misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1986         } else {
1987                 if (user_mode(regs))
1988                         misc |= PERF_RECORD_MISC_USER;
1989                 else
1990                         misc |= PERF_RECORD_MISC_KERNEL;
1991         }
1992
1993         if (regs->flags & PERF_EFLAGS_EXACT)
1994                 misc |= PERF_RECORD_MISC_EXACT_IP;
1995
1996         return misc;
1997 }