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