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