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