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