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