Merge branch 'master' of ssh://master.kernel.org/pub/scm/linux/kernel/git/kaber/nf-2.6
[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
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         /*
504          * We still allow the PMU driver to operate:
505          */
506         printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
507         printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
508
509         return true;
510
511 msr_fail:
512         printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
513
514         return false;
515 }
516
517 static void reserve_ds_buffers(void);
518 static void release_ds_buffers(void);
519
520 static void hw_perf_event_destroy(struct perf_event *event)
521 {
522         if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
523                 release_pmc_hardware();
524                 release_ds_buffers();
525                 mutex_unlock(&pmc_reserve_mutex);
526         }
527 }
528
529 static inline int x86_pmu_initialized(void)
530 {
531         return x86_pmu.handle_irq != NULL;
532 }
533
534 static inline int
535 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
536 {
537         struct perf_event_attr *attr = &event->attr;
538         unsigned int cache_type, cache_op, cache_result;
539         u64 config, val;
540
541         config = attr->config;
542
543         cache_type = (config >>  0) & 0xff;
544         if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
545                 return -EINVAL;
546
547         cache_op = (config >>  8) & 0xff;
548         if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
549                 return -EINVAL;
550
551         cache_result = (config >> 16) & 0xff;
552         if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
553                 return -EINVAL;
554
555         val = hw_cache_event_ids[cache_type][cache_op][cache_result];
556
557         if (val == 0)
558                 return -ENOENT;
559
560         if (val == -1)
561                 return -EINVAL;
562
563         hwc->config |= val;
564         attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
565         return x86_pmu_extra_regs(val, event);
566 }
567
568 static int x86_setup_perfctr(struct perf_event *event)
569 {
570         struct perf_event_attr *attr = &event->attr;
571         struct hw_perf_event *hwc = &event->hw;
572         u64 config;
573
574         if (!is_sampling_event(event)) {
575                 hwc->sample_period = x86_pmu.max_period;
576                 hwc->last_period = hwc->sample_period;
577                 local64_set(&hwc->period_left, hwc->sample_period);
578         } else {
579                 /*
580                  * If we have a PMU initialized but no APIC
581                  * interrupts, we cannot sample hardware
582                  * events (user-space has to fall back and
583                  * sample via a hrtimer based software event):
584                  */
585                 if (!x86_pmu.apic)
586                         return -EOPNOTSUPP;
587         }
588
589         if (attr->type == PERF_TYPE_RAW)
590                 return x86_pmu_extra_regs(event->attr.config, event);
591
592         if (attr->type == PERF_TYPE_HW_CACHE)
593                 return set_ext_hw_attr(hwc, event);
594
595         if (attr->config >= x86_pmu.max_events)
596                 return -EINVAL;
597
598         /*
599          * The generic map:
600          */
601         config = x86_pmu.event_map(attr->config);
602
603         if (config == 0)
604                 return -ENOENT;
605
606         if (config == -1LL)
607                 return -EINVAL;
608
609         /*
610          * Branch tracing:
611          */
612         if ((attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS) &&
613             (hwc->sample_period == 1)) {
614                 /* BTS is not supported by this architecture. */
615                 if (!x86_pmu.bts_active)
616                         return -EOPNOTSUPP;
617
618                 /* BTS is currently only allowed for user-mode. */
619                 if (!attr->exclude_kernel)
620                         return -EOPNOTSUPP;
621         }
622
623         hwc->config |= config;
624
625         return 0;
626 }
627
628 static int x86_pmu_hw_config(struct perf_event *event)
629 {
630         if (event->attr.precise_ip) {
631                 int precise = 0;
632
633                 /* Support for constant skid */
634                 if (x86_pmu.pebs_active) {
635                         precise++;
636
637                         /* Support for IP fixup */
638                         if (x86_pmu.lbr_nr)
639                                 precise++;
640                 }
641
642                 if (event->attr.precise_ip > precise)
643                         return -EOPNOTSUPP;
644         }
645
646         /*
647          * Generate PMC IRQs:
648          * (keep 'enabled' bit clear for now)
649          */
650         event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
651
652         /*
653          * Count user and OS events unless requested not to
654          */
655         if (!event->attr.exclude_user)
656                 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
657         if (!event->attr.exclude_kernel)
658                 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
659
660         if (event->attr.type == PERF_TYPE_RAW)
661                 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
662
663         return x86_setup_perfctr(event);
664 }
665
666 /*
667  * Setup the hardware configuration for a given attr_type
668  */
669 static int __x86_pmu_event_init(struct perf_event *event)
670 {
671         int err;
672
673         if (!x86_pmu_initialized())
674                 return -ENODEV;
675
676         err = 0;
677         if (!atomic_inc_not_zero(&active_events)) {
678                 mutex_lock(&pmc_reserve_mutex);
679                 if (atomic_read(&active_events) == 0) {
680                         if (!reserve_pmc_hardware())
681                                 err = -EBUSY;
682                         else
683                                 reserve_ds_buffers();
684                 }
685                 if (!err)
686                         atomic_inc(&active_events);
687                 mutex_unlock(&pmc_reserve_mutex);
688         }
689         if (err)
690                 return err;
691
692         event->destroy = hw_perf_event_destroy;
693
694         event->hw.idx = -1;
695         event->hw.last_cpu = -1;
696         event->hw.last_tag = ~0ULL;
697
698         return x86_pmu.hw_config(event);
699 }
700
701 static void x86_pmu_disable_all(void)
702 {
703         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
704         int idx;
705
706         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
707                 u64 val;
708
709                 if (!test_bit(idx, cpuc->active_mask))
710                         continue;
711                 rdmsrl(x86_pmu_config_addr(idx), val);
712                 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
713                         continue;
714                 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
715                 wrmsrl(x86_pmu_config_addr(idx), val);
716         }
717 }
718
719 static void x86_pmu_disable(struct pmu *pmu)
720 {
721         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
722
723         if (!x86_pmu_initialized())
724                 return;
725
726         if (!cpuc->enabled)
727                 return;
728
729         cpuc->n_added = 0;
730         cpuc->enabled = 0;
731         barrier();
732
733         x86_pmu.disable_all();
734 }
735
736 static inline void __x86_pmu_enable_event(struct hw_perf_event *hwc,
737                                           u64 enable_mask)
738 {
739         if (hwc->extra_reg)
740                 wrmsrl(hwc->extra_reg, hwc->extra_config);
741         wrmsrl(hwc->config_base, hwc->config | enable_mask);
742 }
743
744 static void x86_pmu_enable_all(int added)
745 {
746         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
747         int idx;
748
749         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
750                 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
751
752                 if (!test_bit(idx, cpuc->active_mask))
753                         continue;
754
755                 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
756         }
757 }
758
759 static struct pmu pmu;
760
761 static inline int is_x86_event(struct perf_event *event)
762 {
763         return event->pmu == &pmu;
764 }
765
766 static int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
767 {
768         struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
769         unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
770         int i, j, w, wmax, num = 0;
771         struct hw_perf_event *hwc;
772
773         bitmap_zero(used_mask, X86_PMC_IDX_MAX);
774
775         for (i = 0; i < n; i++) {
776                 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
777                 constraints[i] = c;
778         }
779
780         /*
781          * fastpath, try to reuse previous register
782          */
783         for (i = 0; i < n; i++) {
784                 hwc = &cpuc->event_list[i]->hw;
785                 c = constraints[i];
786
787                 /* never assigned */
788                 if (hwc->idx == -1)
789                         break;
790
791                 /* constraint still honored */
792                 if (!test_bit(hwc->idx, c->idxmsk))
793                         break;
794
795                 /* not already used */
796                 if (test_bit(hwc->idx, used_mask))
797                         break;
798
799                 __set_bit(hwc->idx, used_mask);
800                 if (assign)
801                         assign[i] = hwc->idx;
802         }
803         if (i == n)
804                 goto done;
805
806         /*
807          * begin slow path
808          */
809
810         bitmap_zero(used_mask, X86_PMC_IDX_MAX);
811
812         /*
813          * weight = number of possible counters
814          *
815          * 1    = most constrained, only works on one counter
816          * wmax = least constrained, works on any counter
817          *
818          * assign events to counters starting with most
819          * constrained events.
820          */
821         wmax = x86_pmu.num_counters;
822
823         /*
824          * when fixed event counters are present,
825          * wmax is incremented by 1 to account
826          * for one more choice
827          */
828         if (x86_pmu.num_counters_fixed)
829                 wmax++;
830
831         for (w = 1, num = n; num && w <= wmax; w++) {
832                 /* for each event */
833                 for (i = 0; num && i < n; i++) {
834                         c = constraints[i];
835                         hwc = &cpuc->event_list[i]->hw;
836
837                         if (c->weight != w)
838                                 continue;
839
840                         for_each_set_bit(j, c->idxmsk, X86_PMC_IDX_MAX) {
841                                 if (!test_bit(j, used_mask))
842                                         break;
843                         }
844
845                         if (j == X86_PMC_IDX_MAX)
846                                 break;
847
848                         __set_bit(j, used_mask);
849
850                         if (assign)
851                                 assign[i] = j;
852                         num--;
853                 }
854         }
855 done:
856         /*
857          * scheduling failed or is just a simulation,
858          * free resources if necessary
859          */
860         if (!assign || num) {
861                 for (i = 0; i < n; i++) {
862                         if (x86_pmu.put_event_constraints)
863                                 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
864                 }
865         }
866         return num ? -ENOSPC : 0;
867 }
868
869 /*
870  * dogrp: true if must collect siblings events (group)
871  * returns total number of events and error code
872  */
873 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
874 {
875         struct perf_event *event;
876         int n, max_count;
877
878         max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
879
880         /* current number of events already accepted */
881         n = cpuc->n_events;
882
883         if (is_x86_event(leader)) {
884                 if (n >= max_count)
885                         return -ENOSPC;
886                 cpuc->event_list[n] = leader;
887                 n++;
888         }
889         if (!dogrp)
890                 return n;
891
892         list_for_each_entry(event, &leader->sibling_list, group_entry) {
893                 if (!is_x86_event(event) ||
894                     event->state <= PERF_EVENT_STATE_OFF)
895                         continue;
896
897                 if (n >= max_count)
898                         return -ENOSPC;
899
900                 cpuc->event_list[n] = event;
901                 n++;
902         }
903         return n;
904 }
905
906 static inline void x86_assign_hw_event(struct perf_event *event,
907                                 struct cpu_hw_events *cpuc, int i)
908 {
909         struct hw_perf_event *hwc = &event->hw;
910
911         hwc->idx = cpuc->assign[i];
912         hwc->last_cpu = smp_processor_id();
913         hwc->last_tag = ++cpuc->tags[i];
914
915         if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
916                 hwc->config_base = 0;
917                 hwc->event_base = 0;
918         } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
919                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
920                 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
921         } else {
922                 hwc->config_base = x86_pmu_config_addr(hwc->idx);
923                 hwc->event_base  = x86_pmu_event_addr(hwc->idx);
924         }
925 }
926
927 static inline int match_prev_assignment(struct hw_perf_event *hwc,
928                                         struct cpu_hw_events *cpuc,
929                                         int i)
930 {
931         return hwc->idx == cpuc->assign[i] &&
932                 hwc->last_cpu == smp_processor_id() &&
933                 hwc->last_tag == cpuc->tags[i];
934 }
935
936 static void x86_pmu_start(struct perf_event *event, int flags);
937 static void x86_pmu_stop(struct perf_event *event, int flags);
938
939 static void x86_pmu_enable(struct pmu *pmu)
940 {
941         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
942         struct perf_event *event;
943         struct hw_perf_event *hwc;
944         int i, added = cpuc->n_added;
945
946         if (!x86_pmu_initialized())
947                 return;
948
949         if (cpuc->enabled)
950                 return;
951
952         if (cpuc->n_added) {
953                 int n_running = cpuc->n_events - cpuc->n_added;
954                 /*
955                  * apply assignment obtained either from
956                  * hw_perf_group_sched_in() or x86_pmu_enable()
957                  *
958                  * step1: save events moving to new counters
959                  * step2: reprogram moved events into new counters
960                  */
961                 for (i = 0; i < n_running; i++) {
962                         event = cpuc->event_list[i];
963                         hwc = &event->hw;
964
965                         /*
966                          * we can avoid reprogramming counter if:
967                          * - assigned same counter as last time
968                          * - running on same CPU as last time
969                          * - no other event has used the counter since
970                          */
971                         if (hwc->idx == -1 ||
972                             match_prev_assignment(hwc, cpuc, i))
973                                 continue;
974
975                         /*
976                          * Ensure we don't accidentally enable a stopped
977                          * counter simply because we rescheduled.
978                          */
979                         if (hwc->state & PERF_HES_STOPPED)
980                                 hwc->state |= PERF_HES_ARCH;
981
982                         x86_pmu_stop(event, PERF_EF_UPDATE);
983                 }
984
985                 for (i = 0; i < cpuc->n_events; i++) {
986                         event = cpuc->event_list[i];
987                         hwc = &event->hw;
988
989                         if (!match_prev_assignment(hwc, cpuc, i))
990                                 x86_assign_hw_event(event, cpuc, i);
991                         else if (i < n_running)
992                                 continue;
993
994                         if (hwc->state & PERF_HES_ARCH)
995                                 continue;
996
997                         x86_pmu_start(event, PERF_EF_RELOAD);
998                 }
999                 cpuc->n_added = 0;
1000                 perf_events_lapic_init();
1001         }
1002
1003         cpuc->enabled = 1;
1004         barrier();
1005
1006         x86_pmu.enable_all(added);
1007 }
1008
1009 static inline void x86_pmu_disable_event(struct perf_event *event)
1010 {
1011         struct hw_perf_event *hwc = &event->hw;
1012
1013         wrmsrl(hwc->config_base, hwc->config);
1014 }
1015
1016 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1017
1018 /*
1019  * Set the next IRQ period, based on the hwc->period_left value.
1020  * To be called with the event disabled in hw:
1021  */
1022 static int
1023 x86_perf_event_set_period(struct perf_event *event)
1024 {
1025         struct hw_perf_event *hwc = &event->hw;
1026         s64 left = local64_read(&hwc->period_left);
1027         s64 period = hwc->sample_period;
1028         int ret = 0, idx = hwc->idx;
1029
1030         if (idx == X86_PMC_IDX_FIXED_BTS)
1031                 return 0;
1032
1033         /*
1034          * If we are way outside a reasonable range then just skip forward:
1035          */
1036         if (unlikely(left <= -period)) {
1037                 left = period;
1038                 local64_set(&hwc->period_left, left);
1039                 hwc->last_period = period;
1040                 ret = 1;
1041         }
1042
1043         if (unlikely(left <= 0)) {
1044                 left += period;
1045                 local64_set(&hwc->period_left, left);
1046                 hwc->last_period = period;
1047                 ret = 1;
1048         }
1049         /*
1050          * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1051          */
1052         if (unlikely(left < 2))
1053                 left = 2;
1054
1055         if (left > x86_pmu.max_period)
1056                 left = x86_pmu.max_period;
1057
1058         per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1059
1060         /*
1061          * The hw event starts counting from this event offset,
1062          * mark it to be able to extra future deltas:
1063          */
1064         local64_set(&hwc->prev_count, (u64)-left);
1065
1066         wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1067
1068         /*
1069          * Due to erratum on certan cpu we need
1070          * a second write to be sure the register
1071          * is updated properly
1072          */
1073         if (x86_pmu.perfctr_second_write) {
1074                 wrmsrl(hwc->event_base,
1075                         (u64)(-left) & x86_pmu.cntval_mask);
1076         }
1077
1078         perf_event_update_userpage(event);
1079
1080         return ret;
1081 }
1082
1083 static void x86_pmu_enable_event(struct perf_event *event)
1084 {
1085         if (__this_cpu_read(cpu_hw_events.enabled))
1086                 __x86_pmu_enable_event(&event->hw,
1087                                        ARCH_PERFMON_EVENTSEL_ENABLE);
1088 }
1089
1090 /*
1091  * Add a single event to the PMU.
1092  *
1093  * The event is added to the group of enabled events
1094  * but only if it can be scehduled with existing events.
1095  */
1096 static int x86_pmu_add(struct perf_event *event, int flags)
1097 {
1098         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1099         struct hw_perf_event *hwc;
1100         int assign[X86_PMC_IDX_MAX];
1101         int n, n0, ret;
1102
1103         hwc = &event->hw;
1104
1105         perf_pmu_disable(event->pmu);
1106         n0 = cpuc->n_events;
1107         ret = n = collect_events(cpuc, event, false);
1108         if (ret < 0)
1109                 goto out;
1110
1111         hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1112         if (!(flags & PERF_EF_START))
1113                 hwc->state |= PERF_HES_ARCH;
1114
1115         /*
1116          * If group events scheduling transaction was started,
1117          * skip the schedulability test here, it will be performed
1118          * at commit time (->commit_txn) as a whole
1119          */
1120         if (cpuc->group_flag & PERF_EVENT_TXN)
1121                 goto done_collect;
1122
1123         ret = x86_pmu.schedule_events(cpuc, n, assign);
1124         if (ret)
1125                 goto out;
1126         /*
1127          * copy new assignment, now we know it is possible
1128          * will be used by hw_perf_enable()
1129          */
1130         memcpy(cpuc->assign, assign, n*sizeof(int));
1131
1132 done_collect:
1133         cpuc->n_events = n;
1134         cpuc->n_added += n - n0;
1135         cpuc->n_txn += n - n0;
1136
1137         ret = 0;
1138 out:
1139         perf_pmu_enable(event->pmu);
1140         return ret;
1141 }
1142
1143 static void x86_pmu_start(struct perf_event *event, int flags)
1144 {
1145         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1146         int idx = event->hw.idx;
1147
1148         if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1149                 return;
1150
1151         if (WARN_ON_ONCE(idx == -1))
1152                 return;
1153
1154         if (flags & PERF_EF_RELOAD) {
1155                 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1156                 x86_perf_event_set_period(event);
1157         }
1158
1159         event->hw.state = 0;
1160
1161         cpuc->events[idx] = event;
1162         __set_bit(idx, cpuc->active_mask);
1163         __set_bit(idx, cpuc->running);
1164         x86_pmu.enable(event);
1165         perf_event_update_userpage(event);
1166 }
1167
1168 void perf_event_print_debug(void)
1169 {
1170         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1171         u64 pebs;
1172         struct cpu_hw_events *cpuc;
1173         unsigned long flags;
1174         int cpu, idx;
1175
1176         if (!x86_pmu.num_counters)
1177                 return;
1178
1179         local_irq_save(flags);
1180
1181         cpu = smp_processor_id();
1182         cpuc = &per_cpu(cpu_hw_events, cpu);
1183
1184         if (x86_pmu.version >= 2) {
1185                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1186                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1187                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1188                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1189                 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1190
1191                 pr_info("\n");
1192                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
1193                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
1194                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
1195                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
1196                 pr_info("CPU#%d: pebs:       %016llx\n", cpu, pebs);
1197         }
1198         pr_info("CPU#%d: active:     %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1199
1200         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1201                 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1202                 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1203
1204                 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1205
1206                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
1207                         cpu, idx, pmc_ctrl);
1208                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
1209                         cpu, idx, pmc_count);
1210                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
1211                         cpu, idx, prev_left);
1212         }
1213         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1214                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1215
1216                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1217                         cpu, idx, pmc_count);
1218         }
1219         local_irq_restore(flags);
1220 }
1221
1222 static void x86_pmu_stop(struct perf_event *event, int flags)
1223 {
1224         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1225         struct hw_perf_event *hwc = &event->hw;
1226
1227         if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1228                 x86_pmu.disable(event);
1229                 cpuc->events[hwc->idx] = NULL;
1230                 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1231                 hwc->state |= PERF_HES_STOPPED;
1232         }
1233
1234         if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1235                 /*
1236                  * Drain the remaining delta count out of a event
1237                  * that we are disabling:
1238                  */
1239                 x86_perf_event_update(event);
1240                 hwc->state |= PERF_HES_UPTODATE;
1241         }
1242 }
1243
1244 static void x86_pmu_del(struct perf_event *event, int flags)
1245 {
1246         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1247         int i;
1248
1249         /*
1250          * If we're called during a txn, we don't need to do anything.
1251          * The events never got scheduled and ->cancel_txn will truncate
1252          * the event_list.
1253          */
1254         if (cpuc->group_flag & PERF_EVENT_TXN)
1255                 return;
1256
1257         x86_pmu_stop(event, PERF_EF_UPDATE);
1258
1259         for (i = 0; i < cpuc->n_events; i++) {
1260                 if (event == cpuc->event_list[i]) {
1261
1262                         if (x86_pmu.put_event_constraints)
1263                                 x86_pmu.put_event_constraints(cpuc, event);
1264
1265                         while (++i < cpuc->n_events)
1266                                 cpuc->event_list[i-1] = cpuc->event_list[i];
1267
1268                         --cpuc->n_events;
1269                         break;
1270                 }
1271         }
1272         perf_event_update_userpage(event);
1273 }
1274
1275 static int x86_pmu_handle_irq(struct pt_regs *regs)
1276 {
1277         struct perf_sample_data data;
1278         struct cpu_hw_events *cpuc;
1279         struct perf_event *event;
1280         int idx, handled = 0;
1281         u64 val;
1282
1283         perf_sample_data_init(&data, 0);
1284
1285         cpuc = &__get_cpu_var(cpu_hw_events);
1286
1287         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1288                 if (!test_bit(idx, cpuc->active_mask)) {
1289                         /*
1290                          * Though we deactivated the counter some cpus
1291                          * might still deliver spurious interrupts still
1292                          * in flight. Catch them:
1293                          */
1294                         if (__test_and_clear_bit(idx, cpuc->running))
1295                                 handled++;
1296                         continue;
1297                 }
1298
1299                 event = cpuc->events[idx];
1300
1301                 val = x86_perf_event_update(event);
1302                 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1303                         continue;
1304
1305                 /*
1306                  * event overflow
1307                  */
1308                 handled++;
1309                 data.period     = event->hw.last_period;
1310
1311                 if (!x86_perf_event_set_period(event))
1312                         continue;
1313
1314                 if (perf_event_overflow(event, 1, &data, regs))
1315                         x86_pmu_stop(event, 0);
1316         }
1317
1318         if (handled)
1319                 inc_irq_stat(apic_perf_irqs);
1320
1321         return handled;
1322 }
1323
1324 void perf_events_lapic_init(void)
1325 {
1326         if (!x86_pmu.apic || !x86_pmu_initialized())
1327                 return;
1328
1329         /*
1330          * Always use NMI for PMU
1331          */
1332         apic_write(APIC_LVTPC, APIC_DM_NMI);
1333 }
1334
1335 struct pmu_nmi_state {
1336         unsigned int    marked;
1337         int             handled;
1338 };
1339
1340 static DEFINE_PER_CPU(struct pmu_nmi_state, pmu_nmi);
1341
1342 static int __kprobes
1343 perf_event_nmi_handler(struct notifier_block *self,
1344                          unsigned long cmd, void *__args)
1345 {
1346         struct die_args *args = __args;
1347         unsigned int this_nmi;
1348         int handled;
1349
1350         if (!atomic_read(&active_events))
1351                 return NOTIFY_DONE;
1352
1353         switch (cmd) {
1354         case DIE_NMI:
1355                 break;
1356         case DIE_NMIUNKNOWN:
1357                 this_nmi = percpu_read(irq_stat.__nmi_count);
1358                 if (this_nmi != __this_cpu_read(pmu_nmi.marked))
1359                         /* let the kernel handle the unknown nmi */
1360                         return NOTIFY_DONE;
1361                 /*
1362                  * This one is a PMU back-to-back nmi. Two events
1363                  * trigger 'simultaneously' raising two back-to-back
1364                  * NMIs. If the first NMI handles both, the latter
1365                  * will be empty and daze the CPU. So, we drop it to
1366                  * avoid false-positive 'unknown nmi' messages.
1367                  */
1368                 return NOTIFY_STOP;
1369         default:
1370                 return NOTIFY_DONE;
1371         }
1372
1373         apic_write(APIC_LVTPC, APIC_DM_NMI);
1374
1375         handled = x86_pmu.handle_irq(args->regs);
1376         if (!handled)
1377                 return NOTIFY_DONE;
1378
1379         this_nmi = percpu_read(irq_stat.__nmi_count);
1380         if ((handled > 1) ||
1381                 /* the next nmi could be a back-to-back nmi */
1382             ((__this_cpu_read(pmu_nmi.marked) == this_nmi) &&
1383              (__this_cpu_read(pmu_nmi.handled) > 1))) {
1384                 /*
1385                  * We could have two subsequent back-to-back nmis: The
1386                  * first handles more than one counter, the 2nd
1387                  * handles only one counter and the 3rd handles no
1388                  * counter.
1389                  *
1390                  * This is the 2nd nmi because the previous was
1391                  * handling more than one counter. We will mark the
1392                  * next (3rd) and then drop it if unhandled.
1393                  */
1394                 __this_cpu_write(pmu_nmi.marked, this_nmi + 1);
1395                 __this_cpu_write(pmu_nmi.handled, handled);
1396         }
1397
1398         return NOTIFY_STOP;
1399 }
1400
1401 static __read_mostly struct notifier_block perf_event_nmi_notifier = {
1402         .notifier_call          = perf_event_nmi_handler,
1403         .next                   = NULL,
1404         .priority               = NMI_LOCAL_LOW_PRIOR,
1405 };
1406
1407 static struct event_constraint unconstrained;
1408 static struct event_constraint emptyconstraint;
1409
1410 static struct event_constraint *
1411 x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
1412 {
1413         struct event_constraint *c;
1414
1415         if (x86_pmu.event_constraints) {
1416                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1417                         if ((event->hw.config & c->cmask) == c->code)
1418                                 return c;
1419                 }
1420         }
1421
1422         return &unconstrained;
1423 }
1424
1425 #include "perf_event_amd.c"
1426 #include "perf_event_p6.c"
1427 #include "perf_event_p4.c"
1428 #include "perf_event_intel_lbr.c"
1429 #include "perf_event_intel_ds.c"
1430 #include "perf_event_intel.c"
1431
1432 static int __cpuinit
1433 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1434 {
1435         unsigned int cpu = (long)hcpu;
1436         int ret = NOTIFY_OK;
1437
1438         switch (action & ~CPU_TASKS_FROZEN) {
1439         case CPU_UP_PREPARE:
1440                 if (x86_pmu.cpu_prepare)
1441                         ret = x86_pmu.cpu_prepare(cpu);
1442                 break;
1443
1444         case CPU_STARTING:
1445                 if (x86_pmu.cpu_starting)
1446                         x86_pmu.cpu_starting(cpu);
1447                 break;
1448
1449         case CPU_DYING:
1450                 if (x86_pmu.cpu_dying)
1451                         x86_pmu.cpu_dying(cpu);
1452                 break;
1453
1454         case CPU_UP_CANCELED:
1455         case CPU_DEAD:
1456                 if (x86_pmu.cpu_dead)
1457                         x86_pmu.cpu_dead(cpu);
1458                 break;
1459
1460         default:
1461                 break;
1462         }
1463
1464         return ret;
1465 }
1466
1467 static void __init pmu_check_apic(void)
1468 {
1469         if (cpu_has_apic)
1470                 return;
1471
1472         x86_pmu.apic = 0;
1473         pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1474         pr_info("no hardware sampling interrupt available.\n");
1475 }
1476
1477 static int __init init_hw_perf_events(void)
1478 {
1479         struct event_constraint *c;
1480         int err;
1481
1482         pr_info("Performance Events: ");
1483
1484         switch (boot_cpu_data.x86_vendor) {
1485         case X86_VENDOR_INTEL:
1486                 err = intel_pmu_init();
1487                 break;
1488         case X86_VENDOR_AMD:
1489                 err = amd_pmu_init();
1490                 break;
1491         default:
1492                 return 0;
1493         }
1494         if (err != 0) {
1495                 pr_cont("no PMU driver, software events only.\n");
1496                 return 0;
1497         }
1498
1499         pmu_check_apic();
1500
1501         /* sanity check that the hardware exists or is emulated */
1502         if (!check_hw_exists())
1503                 return 0;
1504
1505         pr_cont("%s PMU driver.\n", x86_pmu.name);
1506
1507         if (x86_pmu.quirks)
1508                 x86_pmu.quirks();
1509
1510         if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1511                 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1512                      x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1513                 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1514         }
1515         x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1516
1517         if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1518                 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1519                      x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1520                 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1521         }
1522
1523         x86_pmu.intel_ctrl |=
1524                 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1525
1526         perf_events_lapic_init();
1527         register_die_notifier(&perf_event_nmi_notifier);
1528
1529         unconstrained = (struct event_constraint)
1530                 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1531                                    0, x86_pmu.num_counters);
1532
1533         if (x86_pmu.event_constraints) {
1534                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1535                         if (c->cmask != X86_RAW_EVENT_MASK)
1536                                 continue;
1537
1538                         c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1539                         c->weight += x86_pmu.num_counters;
1540                 }
1541         }
1542
1543         pr_info("... version:                %d\n",     x86_pmu.version);
1544         pr_info("... bit width:              %d\n",     x86_pmu.cntval_bits);
1545         pr_info("... generic registers:      %d\n",     x86_pmu.num_counters);
1546         pr_info("... value mask:             %016Lx\n", x86_pmu.cntval_mask);
1547         pr_info("... max period:             %016Lx\n", x86_pmu.max_period);
1548         pr_info("... fixed-purpose events:   %d\n",     x86_pmu.num_counters_fixed);
1549         pr_info("... event mask:             %016Lx\n", x86_pmu.intel_ctrl);
1550
1551         perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1552         perf_cpu_notifier(x86_pmu_notifier);
1553
1554         return 0;
1555 }
1556 early_initcall(init_hw_perf_events);
1557
1558 static inline void x86_pmu_read(struct perf_event *event)
1559 {
1560         x86_perf_event_update(event);
1561 }
1562
1563 /*
1564  * Start group events scheduling transaction
1565  * Set the flag to make pmu::enable() not perform the
1566  * schedulability test, it will be performed at commit time
1567  */
1568 static void x86_pmu_start_txn(struct pmu *pmu)
1569 {
1570         perf_pmu_disable(pmu);
1571         __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1572         __this_cpu_write(cpu_hw_events.n_txn, 0);
1573 }
1574
1575 /*
1576  * Stop group events scheduling transaction
1577  * Clear the flag and pmu::enable() will perform the
1578  * schedulability test.
1579  */
1580 static void x86_pmu_cancel_txn(struct pmu *pmu)
1581 {
1582         __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1583         /*
1584          * Truncate the collected events.
1585          */
1586         __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1587         __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1588         perf_pmu_enable(pmu);
1589 }
1590
1591 /*
1592  * Commit group events scheduling transaction
1593  * Perform the group schedulability test as a whole
1594  * Return 0 if success
1595  */
1596 static int x86_pmu_commit_txn(struct pmu *pmu)
1597 {
1598         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1599         int assign[X86_PMC_IDX_MAX];
1600         int n, ret;
1601
1602         n = cpuc->n_events;
1603
1604         if (!x86_pmu_initialized())
1605                 return -EAGAIN;
1606
1607         ret = x86_pmu.schedule_events(cpuc, n, assign);
1608         if (ret)
1609                 return ret;
1610
1611         /*
1612          * copy new assignment, now we know it is possible
1613          * will be used by hw_perf_enable()
1614          */
1615         memcpy(cpuc->assign, assign, n*sizeof(int));
1616
1617         cpuc->group_flag &= ~PERF_EVENT_TXN;
1618         perf_pmu_enable(pmu);
1619         return 0;
1620 }
1621
1622 /*
1623  * validate that we can schedule this event
1624  */
1625 static int validate_event(struct perf_event *event)
1626 {
1627         struct cpu_hw_events *fake_cpuc;
1628         struct event_constraint *c;
1629         int ret = 0;
1630
1631         fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1632         if (!fake_cpuc)
1633                 return -ENOMEM;
1634
1635         c = x86_pmu.get_event_constraints(fake_cpuc, event);
1636
1637         if (!c || !c->weight)
1638                 ret = -ENOSPC;
1639
1640         if (x86_pmu.put_event_constraints)
1641                 x86_pmu.put_event_constraints(fake_cpuc, event);
1642
1643         kfree(fake_cpuc);
1644
1645         return ret;
1646 }
1647
1648 /*
1649  * validate a single event group
1650  *
1651  * validation include:
1652  *      - check events are compatible which each other
1653  *      - events do not compete for the same counter
1654  *      - number of events <= number of counters
1655  *
1656  * validation ensures the group can be loaded onto the
1657  * PMU if it was the only group available.
1658  */
1659 static int validate_group(struct perf_event *event)
1660 {
1661         struct perf_event *leader = event->group_leader;
1662         struct cpu_hw_events *fake_cpuc;
1663         int ret, n;
1664
1665         ret = -ENOMEM;
1666         fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1667         if (!fake_cpuc)
1668                 goto out;
1669
1670         /*
1671          * the event is not yet connected with its
1672          * siblings therefore we must first collect
1673          * existing siblings, then add the new event
1674          * before we can simulate the scheduling
1675          */
1676         ret = -ENOSPC;
1677         n = collect_events(fake_cpuc, leader, true);
1678         if (n < 0)
1679                 goto out_free;
1680
1681         fake_cpuc->n_events = n;
1682         n = collect_events(fake_cpuc, event, false);
1683         if (n < 0)
1684                 goto out_free;
1685
1686         fake_cpuc->n_events = n;
1687
1688         ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1689
1690 out_free:
1691         kfree(fake_cpuc);
1692 out:
1693         return ret;
1694 }
1695
1696 static int x86_pmu_event_init(struct perf_event *event)
1697 {
1698         struct pmu *tmp;
1699         int err;
1700
1701         switch (event->attr.type) {
1702         case PERF_TYPE_RAW:
1703         case PERF_TYPE_HARDWARE:
1704         case PERF_TYPE_HW_CACHE:
1705                 break;
1706
1707         default:
1708                 return -ENOENT;
1709         }
1710
1711         err = __x86_pmu_event_init(event);
1712         if (!err) {
1713                 /*
1714                  * we temporarily connect event to its pmu
1715                  * such that validate_group() can classify
1716                  * it as an x86 event using is_x86_event()
1717                  */
1718                 tmp = event->pmu;
1719                 event->pmu = &pmu;
1720
1721                 if (event->group_leader != event)
1722                         err = validate_group(event);
1723                 else
1724                         err = validate_event(event);
1725
1726                 event->pmu = tmp;
1727         }
1728         if (err) {
1729                 if (event->destroy)
1730                         event->destroy(event);
1731         }
1732
1733         return err;
1734 }
1735
1736 static struct pmu pmu = {
1737         .pmu_enable     = x86_pmu_enable,
1738         .pmu_disable    = x86_pmu_disable,
1739
1740         .event_init     = x86_pmu_event_init,
1741
1742         .add            = x86_pmu_add,
1743         .del            = x86_pmu_del,
1744         .start          = x86_pmu_start,
1745         .stop           = x86_pmu_stop,
1746         .read           = x86_pmu_read,
1747
1748         .start_txn      = x86_pmu_start_txn,
1749         .cancel_txn     = x86_pmu_cancel_txn,
1750         .commit_txn     = x86_pmu_commit_txn,
1751 };
1752
1753 /*
1754  * callchain support
1755  */
1756
1757 static void
1758 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1759 {
1760         /* Ignore warnings */
1761 }
1762
1763 static void backtrace_warning(void *data, char *msg)
1764 {
1765         /* Ignore warnings */
1766 }
1767
1768 static int backtrace_stack(void *data, char *name)
1769 {
1770         return 0;
1771 }
1772
1773 static void backtrace_address(void *data, unsigned long addr, int reliable)
1774 {
1775         struct perf_callchain_entry *entry = data;
1776
1777         perf_callchain_store(entry, addr);
1778 }
1779
1780 static const struct stacktrace_ops backtrace_ops = {
1781         .warning                = backtrace_warning,
1782         .warning_symbol         = backtrace_warning_symbol,
1783         .stack                  = backtrace_stack,
1784         .address                = backtrace_address,
1785         .walk_stack             = print_context_stack_bp,
1786 };
1787
1788 void
1789 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1790 {
1791         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1792                 /* TODO: We don't support guest os callchain now */
1793                 return;
1794         }
1795
1796         perf_callchain_store(entry, regs->ip);
1797
1798         dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1799 }
1800
1801 #ifdef CONFIG_COMPAT
1802 static inline int
1803 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1804 {
1805         /* 32-bit process in 64-bit kernel. */
1806         struct stack_frame_ia32 frame;
1807         const void __user *fp;
1808
1809         if (!test_thread_flag(TIF_IA32))
1810                 return 0;
1811
1812         fp = compat_ptr(regs->bp);
1813         while (entry->nr < PERF_MAX_STACK_DEPTH) {
1814                 unsigned long bytes;
1815                 frame.next_frame     = 0;
1816                 frame.return_address = 0;
1817
1818                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1819                 if (bytes != sizeof(frame))
1820                         break;
1821
1822                 if (fp < compat_ptr(regs->sp))
1823                         break;
1824
1825                 perf_callchain_store(entry, frame.return_address);
1826                 fp = compat_ptr(frame.next_frame);
1827         }
1828         return 1;
1829 }
1830 #else
1831 static inline int
1832 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1833 {
1834     return 0;
1835 }
1836 #endif
1837
1838 void
1839 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1840 {
1841         struct stack_frame frame;
1842         const void __user *fp;
1843
1844         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1845                 /* TODO: We don't support guest os callchain now */
1846                 return;
1847         }
1848
1849         fp = (void __user *)regs->bp;
1850
1851         perf_callchain_store(entry, regs->ip);
1852
1853         if (perf_callchain_user32(regs, entry))
1854                 return;
1855
1856         while (entry->nr < PERF_MAX_STACK_DEPTH) {
1857                 unsigned long bytes;
1858                 frame.next_frame             = NULL;
1859                 frame.return_address = 0;
1860
1861                 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1862                 if (bytes != sizeof(frame))
1863                         break;
1864
1865                 if ((unsigned long)fp < regs->sp)
1866                         break;
1867
1868                 perf_callchain_store(entry, frame.return_address);
1869                 fp = frame.next_frame;
1870         }
1871 }
1872
1873 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1874 {
1875         unsigned long ip;
1876
1877         if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1878                 ip = perf_guest_cbs->get_guest_ip();
1879         else
1880                 ip = instruction_pointer(regs);
1881
1882         return ip;
1883 }
1884
1885 unsigned long perf_misc_flags(struct pt_regs *regs)
1886 {
1887         int misc = 0;
1888
1889         if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1890                 if (perf_guest_cbs->is_user_mode())
1891                         misc |= PERF_RECORD_MISC_GUEST_USER;
1892                 else
1893                         misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1894         } else {
1895                 if (user_mode(regs))
1896                         misc |= PERF_RECORD_MISC_USER;
1897                 else
1898                         misc |= PERF_RECORD_MISC_KERNEL;
1899         }
1900
1901         if (regs->flags & PERF_EFLAGS_EXACT)
1902                 misc |= PERF_RECORD_MISC_EXACT_IP;
1903
1904         return misc;
1905 }