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