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