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