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