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