x86, perf: Fix NULL deref on not assigned x86_pmu
[pandora-kernel.git] / arch / x86 / kernel / cpu / perf_event.c
1 /*
2  * Performance events x86 architecture code
3  *
4  *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6  *  Copyright (C) 2009 Jaswinder Singh Rajput
7  *  Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
8  *  Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
9  *  Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
10  *  Copyright (C) 2009 Google, Inc., Stephane Eranian
11  *
12  *  For licencing details see kernel-base/COPYING
13  */
14
15 #include <linux/perf_event.h>
16 #include <linux/capability.h>
17 #include <linux/notifier.h>
18 #include <linux/hardirq.h>
19 #include <linux/kprobes.h>
20 #include <linux/module.h>
21 #include <linux/kdebug.h>
22 #include <linux/sched.h>
23 #include <linux/uaccess.h>
24 #include <linux/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
802                         event = cpuc->event_list[i];
803                         hwc = &event->hw;
804
805                         /*
806                          * we can avoid reprogramming counter if:
807                          * - assigned same counter as last time
808                          * - running on same CPU as last time
809                          * - no other event has used the counter since
810                          */
811                         if (hwc->idx == -1 ||
812                             match_prev_assignment(hwc, cpuc, i))
813                                 continue;
814
815                         x86_pmu_stop(event);
816
817                         hwc->idx = -1;
818                 }
819
820                 for (i = 0; i < cpuc->n_events; i++) {
821
822                         event = cpuc->event_list[i];
823                         hwc = &event->hw;
824
825                         if (i < n_running &&
826                             match_prev_assignment(hwc, cpuc, i))
827                                 continue;
828
829                         if (hwc->idx == -1)
830                                 x86_assign_hw_event(event, cpuc, i);
831
832                         x86_pmu_start(event);
833                 }
834                 cpuc->n_added = 0;
835                 perf_events_lapic_init();
836         }
837
838         cpuc->enabled = 1;
839         barrier();
840
841         x86_pmu.enable_all();
842 }
843
844 static inline void __x86_pmu_enable_event(struct hw_perf_event *hwc)
845 {
846         wrmsrl(hwc->config_base + hwc->idx,
847                               hwc->config | ARCH_PERFMON_EVENTSEL_ENABLE);
848 }
849
850 static inline void x86_pmu_disable_event(struct perf_event *event)
851 {
852         struct hw_perf_event *hwc = &event->hw;
853
854         wrmsrl(hwc->config_base + hwc->idx, hwc->config);
855 }
856
857 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
858
859 /*
860  * Set the next IRQ period, based on the hwc->period_left value.
861  * To be called with the event disabled in hw:
862  */
863 static int
864 x86_perf_event_set_period(struct perf_event *event)
865 {
866         struct hw_perf_event *hwc = &event->hw;
867         s64 left = atomic64_read(&hwc->period_left);
868         s64 period = hwc->sample_period;
869         int ret = 0, idx = hwc->idx;
870
871         if (idx == X86_PMC_IDX_FIXED_BTS)
872                 return 0;
873
874         /*
875          * If we are way outside a reasonable range then just skip forward:
876          */
877         if (unlikely(left <= -period)) {
878                 left = period;
879                 atomic64_set(&hwc->period_left, left);
880                 hwc->last_period = period;
881                 ret = 1;
882         }
883
884         if (unlikely(left <= 0)) {
885                 left += period;
886                 atomic64_set(&hwc->period_left, left);
887                 hwc->last_period = period;
888                 ret = 1;
889         }
890         /*
891          * Quirk: certain CPUs dont like it if just 1 hw_event is left:
892          */
893         if (unlikely(left < 2))
894                 left = 2;
895
896         if (left > x86_pmu.max_period)
897                 left = x86_pmu.max_period;
898
899         per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
900
901         /*
902          * The hw event starts counting from this event offset,
903          * mark it to be able to extra future deltas:
904          */
905         atomic64_set(&hwc->prev_count, (u64)-left);
906
907         wrmsrl(hwc->event_base + idx,
908                         (u64)(-left) & x86_pmu.event_mask);
909
910         perf_event_update_userpage(event);
911
912         return ret;
913 }
914
915 static void x86_pmu_enable_event(struct perf_event *event)
916 {
917         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
918         if (cpuc->enabled)
919                 __x86_pmu_enable_event(&event->hw);
920 }
921
922 /*
923  * activate a single event
924  *
925  * The event is added to the group of enabled events
926  * but only if it can be scehduled with existing events.
927  *
928  * Called with PMU disabled. If successful and return value 1,
929  * then guaranteed to call perf_enable() and hw_perf_enable()
930  */
931 static int x86_pmu_enable(struct perf_event *event)
932 {
933         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
934         struct hw_perf_event *hwc;
935         int assign[X86_PMC_IDX_MAX];
936         int n, n0, ret;
937
938         hwc = &event->hw;
939
940         n0 = cpuc->n_events;
941         n = collect_events(cpuc, event, false);
942         if (n < 0)
943                 return n;
944
945         ret = x86_pmu.schedule_events(cpuc, n, assign);
946         if (ret)
947                 return ret;
948         /*
949          * copy new assignment, now we know it is possible
950          * will be used by hw_perf_enable()
951          */
952         memcpy(cpuc->assign, assign, n*sizeof(int));
953
954         cpuc->n_events = n;
955         cpuc->n_added += n - n0;
956
957         return 0;
958 }
959
960 static int x86_pmu_start(struct perf_event *event)
961 {
962         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
963         int idx = event->hw.idx;
964
965         if (idx == -1)
966                 return -EAGAIN;
967
968         x86_perf_event_set_period(event);
969         cpuc->events[idx] = event;
970         __set_bit(idx, cpuc->active_mask);
971         x86_pmu.enable(event);
972         perf_event_update_userpage(event);
973
974         return 0;
975 }
976
977 static void x86_pmu_unthrottle(struct perf_event *event)
978 {
979         int ret = x86_pmu_start(event);
980         WARN_ON_ONCE(ret);
981 }
982
983 void perf_event_print_debug(void)
984 {
985         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
986         u64 pebs;
987         struct cpu_hw_events *cpuc;
988         unsigned long flags;
989         int cpu, idx;
990
991         if (!x86_pmu.num_events)
992                 return;
993
994         local_irq_save(flags);
995
996         cpu = smp_processor_id();
997         cpuc = &per_cpu(cpu_hw_events, cpu);
998
999         if (x86_pmu.version >= 2) {
1000                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1001                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1002                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1003                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1004                 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1005
1006                 pr_info("\n");
1007                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
1008                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
1009                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
1010                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
1011                 pr_info("CPU#%d: pebs:       %016llx\n", cpu, pebs);
1012         }
1013         pr_info("CPU#%d: active:     %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1014
1015         for (idx = 0; idx < x86_pmu.num_events; idx++) {
1016                 rdmsrl(x86_pmu.eventsel + idx, pmc_ctrl);
1017                 rdmsrl(x86_pmu.perfctr  + idx, pmc_count);
1018
1019                 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1020
1021                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
1022                         cpu, idx, pmc_ctrl);
1023                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
1024                         cpu, idx, pmc_count);
1025                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
1026                         cpu, idx, prev_left);
1027         }
1028         for (idx = 0; idx < x86_pmu.num_events_fixed; idx++) {
1029                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1030
1031                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1032                         cpu, idx, pmc_count);
1033         }
1034         local_irq_restore(flags);
1035 }
1036
1037 static void x86_pmu_stop(struct perf_event *event)
1038 {
1039         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1040         struct hw_perf_event *hwc = &event->hw;
1041         int idx = hwc->idx;
1042
1043         if (!__test_and_clear_bit(idx, cpuc->active_mask))
1044                 return;
1045
1046         x86_pmu.disable(event);
1047
1048         /*
1049          * Drain the remaining delta count out of a event
1050          * that we are disabling:
1051          */
1052         x86_perf_event_update(event);
1053
1054         cpuc->events[idx] = NULL;
1055 }
1056
1057 static void x86_pmu_disable(struct perf_event *event)
1058 {
1059         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1060         int i;
1061
1062         x86_pmu_stop(event);
1063
1064         for (i = 0; i < cpuc->n_events; i++) {
1065                 if (event == cpuc->event_list[i]) {
1066
1067                         if (x86_pmu.put_event_constraints)
1068                                 x86_pmu.put_event_constraints(cpuc, event);
1069
1070                         while (++i < cpuc->n_events)
1071                                 cpuc->event_list[i-1] = cpuc->event_list[i];
1072
1073                         --cpuc->n_events;
1074                         break;
1075                 }
1076         }
1077         perf_event_update_userpage(event);
1078 }
1079
1080 static int x86_pmu_handle_irq(struct pt_regs *regs)
1081 {
1082         struct perf_sample_data data;
1083         struct cpu_hw_events *cpuc;
1084         struct perf_event *event;
1085         struct hw_perf_event *hwc;
1086         int idx, handled = 0;
1087         u64 val;
1088
1089         perf_sample_data_init(&data, 0);
1090
1091         cpuc = &__get_cpu_var(cpu_hw_events);
1092
1093         for (idx = 0; idx < x86_pmu.num_events; idx++) {
1094                 if (!test_bit(idx, cpuc->active_mask))
1095                         continue;
1096
1097                 event = cpuc->events[idx];
1098                 hwc = &event->hw;
1099
1100                 val = x86_perf_event_update(event);
1101                 if (val & (1ULL << (x86_pmu.event_bits - 1)))
1102                         continue;
1103
1104                 /*
1105                  * event overflow
1106                  */
1107                 handled         = 1;
1108                 data.period     = event->hw.last_period;
1109
1110                 if (!x86_perf_event_set_period(event))
1111                         continue;
1112
1113                 if (perf_event_overflow(event, 1, &data, regs))
1114                         x86_pmu_stop(event);
1115         }
1116
1117         if (handled)
1118                 inc_irq_stat(apic_perf_irqs);
1119
1120         return handled;
1121 }
1122
1123 void smp_perf_pending_interrupt(struct pt_regs *regs)
1124 {
1125         irq_enter();
1126         ack_APIC_irq();
1127         inc_irq_stat(apic_pending_irqs);
1128         perf_event_do_pending();
1129         irq_exit();
1130 }
1131
1132 void set_perf_event_pending(void)
1133 {
1134 #ifdef CONFIG_X86_LOCAL_APIC
1135         if (!x86_pmu.apic || !x86_pmu_initialized())
1136                 return;
1137
1138         apic->send_IPI_self(LOCAL_PENDING_VECTOR);
1139 #endif
1140 }
1141
1142 void perf_events_lapic_init(void)
1143 {
1144 #ifdef CONFIG_X86_LOCAL_APIC
1145         if (!x86_pmu.apic || !x86_pmu_initialized())
1146                 return;
1147
1148         /*
1149          * Always use NMI for PMU
1150          */
1151         apic_write(APIC_LVTPC, APIC_DM_NMI);
1152 #endif
1153 }
1154
1155 static int __kprobes
1156 perf_event_nmi_handler(struct notifier_block *self,
1157                          unsigned long cmd, void *__args)
1158 {
1159         struct die_args *args = __args;
1160         struct pt_regs *regs;
1161
1162         if (!atomic_read(&active_events))
1163                 return NOTIFY_DONE;
1164
1165         switch (cmd) {
1166         case DIE_NMI:
1167         case DIE_NMI_IPI:
1168                 break;
1169
1170         default:
1171                 return NOTIFY_DONE;
1172         }
1173
1174         regs = args->regs;
1175
1176 #ifdef CONFIG_X86_LOCAL_APIC
1177         apic_write(APIC_LVTPC, APIC_DM_NMI);
1178 #endif
1179         /*
1180          * Can't rely on the handled return value to say it was our NMI, two
1181          * events could trigger 'simultaneously' raising two back-to-back NMIs.
1182          *
1183          * If the first NMI handles both, the latter will be empty and daze
1184          * the CPU.
1185          */
1186         x86_pmu.handle_irq(regs);
1187
1188         return NOTIFY_STOP;
1189 }
1190
1191 static __read_mostly struct notifier_block perf_event_nmi_notifier = {
1192         .notifier_call          = perf_event_nmi_handler,
1193         .next                   = NULL,
1194         .priority               = 1
1195 };
1196
1197 static struct event_constraint unconstrained;
1198 static struct event_constraint emptyconstraint;
1199
1200 static struct event_constraint *
1201 x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
1202 {
1203         struct event_constraint *c;
1204
1205         if (x86_pmu.event_constraints) {
1206                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1207                         if ((event->hw.config & c->cmask) == c->code)
1208                                 return c;
1209                 }
1210         }
1211
1212         return &unconstrained;
1213 }
1214
1215 static int x86_event_sched_in(struct perf_event *event,
1216                           struct perf_cpu_context *cpuctx)
1217 {
1218         int ret = 0;
1219
1220         event->state = PERF_EVENT_STATE_ACTIVE;
1221         event->oncpu = smp_processor_id();
1222         event->tstamp_running += event->ctx->time - event->tstamp_stopped;
1223
1224         if (!is_x86_event(event))
1225                 ret = event->pmu->enable(event);
1226
1227         if (!ret && !is_software_event(event))
1228                 cpuctx->active_oncpu++;
1229
1230         if (!ret && event->attr.exclusive)
1231                 cpuctx->exclusive = 1;
1232
1233         return ret;
1234 }
1235
1236 static void x86_event_sched_out(struct perf_event *event,
1237                             struct perf_cpu_context *cpuctx)
1238 {
1239         event->state = PERF_EVENT_STATE_INACTIVE;
1240         event->oncpu = -1;
1241
1242         if (!is_x86_event(event))
1243                 event->pmu->disable(event);
1244
1245         event->tstamp_running -= event->ctx->time - event->tstamp_stopped;
1246
1247         if (!is_software_event(event))
1248                 cpuctx->active_oncpu--;
1249
1250         if (event->attr.exclusive || !cpuctx->active_oncpu)
1251                 cpuctx->exclusive = 0;
1252 }
1253
1254 /*
1255  * Called to enable a whole group of events.
1256  * Returns 1 if the group was enabled, or -EAGAIN if it could not be.
1257  * Assumes the caller has disabled interrupts and has
1258  * frozen the PMU with hw_perf_save_disable.
1259  *
1260  * called with PMU disabled. If successful and return value 1,
1261  * then guaranteed to call perf_enable() and hw_perf_enable()
1262  */
1263 int hw_perf_group_sched_in(struct perf_event *leader,
1264                struct perf_cpu_context *cpuctx,
1265                struct perf_event_context *ctx)
1266 {
1267         struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1268         struct perf_event *sub;
1269         int assign[X86_PMC_IDX_MAX];
1270         int n0, n1, ret;
1271
1272         if (!x86_pmu_initialized())
1273                 return 0;
1274
1275         /* n0 = total number of events */
1276         n0 = collect_events(cpuc, leader, true);
1277         if (n0 < 0)
1278                 return n0;
1279
1280         ret = x86_pmu.schedule_events(cpuc, n0, assign);
1281         if (ret)
1282                 return ret;
1283
1284         ret = x86_event_sched_in(leader, cpuctx);
1285         if (ret)
1286                 return ret;
1287
1288         n1 = 1;
1289         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
1290                 if (sub->state > PERF_EVENT_STATE_OFF) {
1291                         ret = x86_event_sched_in(sub, cpuctx);
1292                         if (ret)
1293                                 goto undo;
1294                         ++n1;
1295                 }
1296         }
1297         /*
1298          * copy new assignment, now we know it is possible
1299          * will be used by hw_perf_enable()
1300          */
1301         memcpy(cpuc->assign, assign, n0*sizeof(int));
1302
1303         cpuc->n_events  = n0;
1304         cpuc->n_added  += n1;
1305         ctx->nr_active += n1;
1306
1307         /*
1308          * 1 means successful and events are active
1309          * This is not quite true because we defer
1310          * actual activation until hw_perf_enable() but
1311          * this way we* ensure caller won't try to enable
1312          * individual events
1313          */
1314         return 1;
1315 undo:
1316         x86_event_sched_out(leader, cpuctx);
1317         n0  = 1;
1318         list_for_each_entry(sub, &leader->sibling_list, group_entry) {
1319                 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
1320                         x86_event_sched_out(sub, cpuctx);
1321                         if (++n0 == n1)
1322                                 break;
1323                 }
1324         }
1325         return ret;
1326 }
1327
1328 #include "perf_event_amd.c"
1329 #include "perf_event_p6.c"
1330 #include "perf_event_p4.c"
1331 #include "perf_event_intel_lbr.c"
1332 #include "perf_event_intel_ds.c"
1333 #include "perf_event_intel.c"
1334
1335 static int __cpuinit
1336 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1337 {
1338         unsigned int cpu = (long)hcpu;
1339
1340         switch (action & ~CPU_TASKS_FROZEN) {
1341         case CPU_UP_PREPARE:
1342                 if (x86_pmu.cpu_prepare)
1343                         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_DEAD:
1357                 if (x86_pmu.cpu_dead)
1358                         x86_pmu.cpu_dead(cpu);
1359                 break;
1360
1361         default:
1362                 break;
1363         }
1364
1365         return NOTIFY_OK;
1366 }
1367
1368 static void __init pmu_check_apic(void)
1369 {
1370         if (cpu_has_apic)
1371                 return;
1372
1373         x86_pmu.apic = 0;
1374         pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1375         pr_info("no hardware sampling interrupt available.\n");
1376 }
1377
1378 void __init init_hw_perf_events(void)
1379 {
1380         struct event_constraint *c;
1381         int err;
1382
1383         pr_info("Performance Events: ");
1384
1385         switch (boot_cpu_data.x86_vendor) {
1386         case X86_VENDOR_INTEL:
1387                 err = intel_pmu_init();
1388                 break;
1389         case X86_VENDOR_AMD:
1390                 err = amd_pmu_init();
1391                 break;
1392         default:
1393                 return;
1394         }
1395         if (err != 0) {
1396                 pr_cont("no PMU driver, software events only.\n");
1397                 return;
1398         }
1399
1400         pmu_check_apic();
1401
1402         pr_cont("%s PMU driver.\n", x86_pmu.name);
1403
1404         if (x86_pmu.quirks)
1405                 x86_pmu.quirks();
1406
1407         if (x86_pmu.num_events > X86_PMC_MAX_GENERIC) {
1408                 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1409                      x86_pmu.num_events, X86_PMC_MAX_GENERIC);
1410                 x86_pmu.num_events = X86_PMC_MAX_GENERIC;
1411         }
1412         perf_event_mask = (1 << x86_pmu.num_events) - 1;
1413         perf_max_events = x86_pmu.num_events;
1414
1415         if (x86_pmu.num_events_fixed > X86_PMC_MAX_FIXED) {
1416                 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1417                      x86_pmu.num_events_fixed, X86_PMC_MAX_FIXED);
1418                 x86_pmu.num_events_fixed = X86_PMC_MAX_FIXED;
1419         }
1420
1421         perf_event_mask |=
1422                 ((1LL << x86_pmu.num_events_fixed)-1) << X86_PMC_IDX_FIXED;
1423         x86_pmu.intel_ctrl = perf_event_mask;
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_events) - 1,
1430                                    0, x86_pmu.num_events);
1431
1432         if (x86_pmu.event_constraints) {
1433                 for_each_event_constraint(c, x86_pmu.event_constraints) {
1434                         if (c->cmask != INTEL_ARCH_FIXED_MASK)
1435                                 continue;
1436
1437                         c->idxmsk64 |= (1ULL << x86_pmu.num_events) - 1;
1438                         c->weight += x86_pmu.num_events;
1439                 }
1440         }
1441
1442         pr_info("... version:                %d\n",     x86_pmu.version);
1443         pr_info("... bit width:              %d\n",     x86_pmu.event_bits);
1444         pr_info("... generic registers:      %d\n",     x86_pmu.num_events);
1445         pr_info("... value mask:             %016Lx\n", x86_pmu.event_mask);
1446         pr_info("... max period:             %016Lx\n", x86_pmu.max_period);
1447         pr_info("... fixed-purpose events:   %d\n",     x86_pmu.num_events_fixed);
1448         pr_info("... event mask:             %016Lx\n", perf_event_mask);
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         if (reliable)
1608                 callchain_store(entry, addr);
1609 }
1610
1611 static const struct stacktrace_ops backtrace_ops = {
1612         .warning                = backtrace_warning,
1613         .warning_symbol         = backtrace_warning_symbol,
1614         .stack                  = backtrace_stack,
1615         .address                = backtrace_address,
1616         .walk_stack             = print_context_stack_bp,
1617 };
1618
1619 #include "../dumpstack.h"
1620
1621 static void
1622 perf_callchain_kernel(struct pt_regs *regs, struct perf_callchain_entry *entry)
1623 {
1624         callchain_store(entry, PERF_CONTEXT_KERNEL);
1625         callchain_store(entry, regs->ip);
1626
1627         dump_trace(NULL, regs, NULL, regs->bp, &backtrace_ops, entry);
1628 }
1629
1630 static int copy_stack_frame(const void __user *fp, struct stack_frame *frame)
1631 {
1632         unsigned long bytes;
1633
1634         bytes = copy_from_user_nmi(frame, fp, sizeof(*frame));
1635
1636         return bytes == sizeof(*frame);
1637 }
1638
1639 static void
1640 perf_callchain_user(struct pt_regs *regs, struct perf_callchain_entry *entry)
1641 {
1642         struct stack_frame frame;
1643         const void __user *fp;
1644
1645         if (!user_mode(regs))
1646                 regs = task_pt_regs(current);
1647
1648         fp = (void __user *)regs->bp;
1649
1650         callchain_store(entry, PERF_CONTEXT_USER);
1651         callchain_store(entry, regs->ip);
1652
1653         while (entry->nr < PERF_MAX_STACK_DEPTH) {
1654                 frame.next_frame             = NULL;
1655                 frame.return_address = 0;
1656
1657                 if (!copy_stack_frame(fp, &frame))
1658                         break;
1659
1660                 if ((unsigned long)fp < regs->sp)
1661                         break;
1662
1663                 callchain_store(entry, frame.return_address);
1664                 fp = frame.next_frame;
1665         }
1666 }
1667
1668 static void
1669 perf_do_callchain(struct pt_regs *regs, struct perf_callchain_entry *entry)
1670 {
1671         int is_user;
1672
1673         if (!regs)
1674                 return;
1675
1676         is_user = user_mode(regs);
1677
1678         if (is_user && current->state != TASK_RUNNING)
1679                 return;
1680
1681         if (!is_user)
1682                 perf_callchain_kernel(regs, entry);
1683
1684         if (current->mm)
1685                 perf_callchain_user(regs, entry);
1686 }
1687
1688 struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1689 {
1690         struct perf_callchain_entry *entry;
1691
1692         if (in_nmi())
1693                 entry = &__get_cpu_var(pmc_nmi_entry);
1694         else
1695                 entry = &__get_cpu_var(pmc_irq_entry);
1696
1697         entry->nr = 0;
1698
1699         perf_do_callchain(regs, entry);
1700
1701         return entry;
1702 }