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