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