perf_counter, x86: remove unused function argument in intel_pmu_get_status()
[cascardo/linux.git] / arch / x86 / kernel / cpu / perf_counter.c
1 /*
2  * Performance counter x86 architecture code
3  *
4  *  Copyright(C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright(C) 2008 Red Hat, Inc., Ingo Molnar
6  *  Copyright(C) 2009 Jaswinder Singh Rajput
7  *  Copyright(C) 2009 Advanced Micro Devices, Inc., Robert Richter
8  *
9  *  For licencing details see kernel-base/COPYING
10  */
11
12 #include <linux/perf_counter.h>
13 #include <linux/capability.h>
14 #include <linux/notifier.h>
15 #include <linux/hardirq.h>
16 #include <linux/kprobes.h>
17 #include <linux/module.h>
18 #include <linux/kdebug.h>
19 #include <linux/sched.h>
20 #include <linux/uaccess.h>
21
22 #include <asm/apic.h>
23 #include <asm/stacktrace.h>
24 #include <asm/nmi.h>
25
26 static u64 perf_counter_mask __read_mostly;
27
28 struct cpu_hw_counters {
29         struct perf_counter     *counters[X86_PMC_IDX_MAX];
30         unsigned long           used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
31         unsigned long           active[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
32         unsigned long           interrupts;
33         u64                     throttle_ctrl;
34         int                     enabled;
35 };
36
37 /*
38  * struct x86_pmu - generic x86 pmu
39  */
40 struct x86_pmu {
41         const char      *name;
42         int             version;
43         int             (*handle_irq)(struct pt_regs *, int);
44         u64             (*save_disable_all)(void);
45         void            (*restore_all)(u64);
46         void            (*enable)(struct hw_perf_counter *, int);
47         void            (*disable)(struct hw_perf_counter *, int);
48         unsigned        eventsel;
49         unsigned        perfctr;
50         u64             (*event_map)(int);
51         u64             (*raw_event)(u64);
52         int             max_events;
53         int             num_counters;
54         int             num_counters_fixed;
55         int             counter_bits;
56         u64             counter_mask;
57         u64             max_period;
58 };
59
60 static struct x86_pmu x86_pmu __read_mostly;
61
62 static DEFINE_PER_CPU(struct cpu_hw_counters, cpu_hw_counters) = {
63         .enabled = 1,
64 };
65
66 /*
67  * Intel PerfMon v3. Used on Core2 and later.
68  */
69 static const u64 intel_perfmon_event_map[] =
70 {
71   [PERF_COUNT_CPU_CYCLES]               = 0x003c,
72   [PERF_COUNT_INSTRUCTIONS]             = 0x00c0,
73   [PERF_COUNT_CACHE_REFERENCES]         = 0x4f2e,
74   [PERF_COUNT_CACHE_MISSES]             = 0x412e,
75   [PERF_COUNT_BRANCH_INSTRUCTIONS]      = 0x00c4,
76   [PERF_COUNT_BRANCH_MISSES]            = 0x00c5,
77   [PERF_COUNT_BUS_CYCLES]               = 0x013c,
78 };
79
80 static u64 intel_pmu_event_map(int event)
81 {
82         return intel_perfmon_event_map[event];
83 }
84
85 static u64 intel_pmu_raw_event(u64 event)
86 {
87 #define CORE_EVNTSEL_EVENT_MASK         0x000000FFULL
88 #define CORE_EVNTSEL_UNIT_MASK          0x0000FF00ULL
89 #define CORE_EVNTSEL_COUNTER_MASK       0xFF000000ULL
90
91 #define CORE_EVNTSEL_MASK               \
92         (CORE_EVNTSEL_EVENT_MASK |      \
93          CORE_EVNTSEL_UNIT_MASK  |      \
94          CORE_EVNTSEL_COUNTER_MASK)
95
96         return event & CORE_EVNTSEL_MASK;
97 }
98
99 /*
100  * AMD Performance Monitor K7 and later.
101  */
102 static const u64 amd_perfmon_event_map[] =
103 {
104   [PERF_COUNT_CPU_CYCLES]               = 0x0076,
105   [PERF_COUNT_INSTRUCTIONS]             = 0x00c0,
106   [PERF_COUNT_CACHE_REFERENCES]         = 0x0080,
107   [PERF_COUNT_CACHE_MISSES]             = 0x0081,
108   [PERF_COUNT_BRANCH_INSTRUCTIONS]      = 0x00c4,
109   [PERF_COUNT_BRANCH_MISSES]            = 0x00c5,
110 };
111
112 static u64 amd_pmu_event_map(int event)
113 {
114         return amd_perfmon_event_map[event];
115 }
116
117 static u64 amd_pmu_raw_event(u64 event)
118 {
119 #define K7_EVNTSEL_EVENT_MASK   0x7000000FFULL
120 #define K7_EVNTSEL_UNIT_MASK    0x00000FF00ULL
121 #define K7_EVNTSEL_COUNTER_MASK 0x0FF000000ULL
122
123 #define K7_EVNTSEL_MASK                 \
124         (K7_EVNTSEL_EVENT_MASK |        \
125          K7_EVNTSEL_UNIT_MASK  |        \
126          K7_EVNTSEL_COUNTER_MASK)
127
128         return event & K7_EVNTSEL_MASK;
129 }
130
131 /*
132  * Propagate counter elapsed time into the generic counter.
133  * Can only be executed on the CPU where the counter is active.
134  * Returns the delta events processed.
135  */
136 static u64
137 x86_perf_counter_update(struct perf_counter *counter,
138                         struct hw_perf_counter *hwc, int idx)
139 {
140         u64 prev_raw_count, new_raw_count, delta;
141
142         /*
143          * Careful: an NMI might modify the previous counter value.
144          *
145          * Our tactic to handle this is to first atomically read and
146          * exchange a new raw count - then add that new-prev delta
147          * count to the generic counter atomically:
148          */
149 again:
150         prev_raw_count = atomic64_read(&hwc->prev_count);
151         rdmsrl(hwc->counter_base + idx, new_raw_count);
152
153         if (atomic64_cmpxchg(&hwc->prev_count, prev_raw_count,
154                                         new_raw_count) != prev_raw_count)
155                 goto again;
156
157         /*
158          * Now we have the new raw value and have updated the prev
159          * timestamp already. We can now calculate the elapsed delta
160          * (counter-)time and add that to the generic counter.
161          *
162          * Careful, not all hw sign-extends above the physical width
163          * of the count, so we do that by clipping the delta to 32 bits:
164          */
165         delta = (u64)(u32)((s32)new_raw_count - (s32)prev_raw_count);
166
167         atomic64_add(delta, &counter->count);
168         atomic64_sub(delta, &hwc->period_left);
169
170         return new_raw_count;
171 }
172
173 static atomic_t num_counters;
174 static DEFINE_MUTEX(pmc_reserve_mutex);
175
176 static bool reserve_pmc_hardware(void)
177 {
178         int i;
179
180         if (nmi_watchdog == NMI_LOCAL_APIC)
181                 disable_lapic_nmi_watchdog();
182
183         for (i = 0; i < x86_pmu.num_counters; i++) {
184                 if (!reserve_perfctr_nmi(x86_pmu.perfctr + i))
185                         goto perfctr_fail;
186         }
187
188         for (i = 0; i < x86_pmu.num_counters; i++) {
189                 if (!reserve_evntsel_nmi(x86_pmu.eventsel + i))
190                         goto eventsel_fail;
191         }
192
193         return true;
194
195 eventsel_fail:
196         for (i--; i >= 0; i--)
197                 release_evntsel_nmi(x86_pmu.eventsel + i);
198
199         i = x86_pmu.num_counters;
200
201 perfctr_fail:
202         for (i--; i >= 0; i--)
203                 release_perfctr_nmi(x86_pmu.perfctr + i);
204
205         if (nmi_watchdog == NMI_LOCAL_APIC)
206                 enable_lapic_nmi_watchdog();
207
208         return false;
209 }
210
211 static void release_pmc_hardware(void)
212 {
213         int i;
214
215         for (i = 0; i < x86_pmu.num_counters; i++) {
216                 release_perfctr_nmi(x86_pmu.perfctr + i);
217                 release_evntsel_nmi(x86_pmu.eventsel + i);
218         }
219
220         if (nmi_watchdog == NMI_LOCAL_APIC)
221                 enable_lapic_nmi_watchdog();
222 }
223
224 static void hw_perf_counter_destroy(struct perf_counter *counter)
225 {
226         if (atomic_dec_and_mutex_lock(&num_counters, &pmc_reserve_mutex)) {
227                 release_pmc_hardware();
228                 mutex_unlock(&pmc_reserve_mutex);
229         }
230 }
231
232 static inline int x86_pmu_initialized(void)
233 {
234         return x86_pmu.handle_irq != NULL;
235 }
236
237 /*
238  * Setup the hardware configuration for a given hw_event_type
239  */
240 static int __hw_perf_counter_init(struct perf_counter *counter)
241 {
242         struct perf_counter_hw_event *hw_event = &counter->hw_event;
243         struct hw_perf_counter *hwc = &counter->hw;
244         int err;
245
246         if (!x86_pmu_initialized())
247                 return -ENODEV;
248
249         err = 0;
250         if (atomic_inc_not_zero(&num_counters)) {
251                 mutex_lock(&pmc_reserve_mutex);
252                 if (atomic_read(&num_counters) == 0 && !reserve_pmc_hardware())
253                         err = -EBUSY;
254                 else
255                         atomic_inc(&num_counters);
256                 mutex_unlock(&pmc_reserve_mutex);
257         }
258         if (err)
259                 return err;
260
261         /*
262          * Generate PMC IRQs:
263          * (keep 'enabled' bit clear for now)
264          */
265         hwc->config = ARCH_PERFMON_EVENTSEL_INT;
266
267         /*
268          * Count user and OS events unless requested not to.
269          */
270         if (!hw_event->exclude_user)
271                 hwc->config |= ARCH_PERFMON_EVENTSEL_USR;
272         if (!hw_event->exclude_kernel)
273                 hwc->config |= ARCH_PERFMON_EVENTSEL_OS;
274
275         /*
276          * If privileged enough, allow NMI events:
277          */
278         hwc->nmi = 0;
279         if (capable(CAP_SYS_ADMIN) && hw_event->nmi)
280                 hwc->nmi = 1;
281
282         hwc->irq_period         = hw_event->irq_period;
283         if ((s64)hwc->irq_period <= 0 || hwc->irq_period > x86_pmu.max_period)
284                 hwc->irq_period = x86_pmu.max_period;
285
286         atomic64_set(&hwc->period_left, hwc->irq_period);
287
288         /*
289          * Raw event type provide the config in the event structure
290          */
291         if (perf_event_raw(hw_event)) {
292                 hwc->config |= x86_pmu.raw_event(perf_event_config(hw_event));
293         } else {
294                 if (perf_event_id(hw_event) >= x86_pmu.max_events)
295                         return -EINVAL;
296                 /*
297                  * The generic map:
298                  */
299                 hwc->config |= x86_pmu.event_map(perf_event_id(hw_event));
300         }
301
302         counter->destroy = hw_perf_counter_destroy;
303
304         return 0;
305 }
306
307 static u64 intel_pmu_save_disable_all(void)
308 {
309         u64 ctrl;
310
311         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
312         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
313
314         return ctrl;
315 }
316
317 static u64 amd_pmu_save_disable_all(void)
318 {
319         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
320         int enabled, idx;
321
322         enabled = cpuc->enabled;
323         cpuc->enabled = 0;
324         /*
325          * ensure we write the disable before we start disabling the
326          * counters proper, so that amd_pmu_enable_counter() does the
327          * right thing.
328          */
329         barrier();
330
331         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
332                 u64 val;
333
334                 if (!test_bit(idx, cpuc->active))
335                         continue;
336                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
337                 if (!(val & ARCH_PERFMON_EVENTSEL0_ENABLE))
338                         continue;
339                 val &= ~ARCH_PERFMON_EVENTSEL0_ENABLE;
340                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
341         }
342
343         return enabled;
344 }
345
346 u64 hw_perf_save_disable(void)
347 {
348         if (!x86_pmu_initialized())
349                 return 0;
350         return x86_pmu.save_disable_all();
351 }
352 /*
353  * Exported because of ACPI idle
354  */
355 EXPORT_SYMBOL_GPL(hw_perf_save_disable);
356
357 static void intel_pmu_restore_all(u64 ctrl)
358 {
359         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
360 }
361
362 static void amd_pmu_restore_all(u64 ctrl)
363 {
364         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
365         int idx;
366
367         cpuc->enabled = ctrl;
368         barrier();
369         if (!ctrl)
370                 return;
371
372         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
373                 u64 val;
374
375                 if (!test_bit(idx, cpuc->active))
376                         continue;
377                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
378                 if (val & ARCH_PERFMON_EVENTSEL0_ENABLE)
379                         continue;
380                 val |= ARCH_PERFMON_EVENTSEL0_ENABLE;
381                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
382         }
383 }
384
385 void hw_perf_restore(u64 ctrl)
386 {
387         if (!x86_pmu_initialized())
388                 return;
389         x86_pmu.restore_all(ctrl);
390 }
391 /*
392  * Exported because of ACPI idle
393  */
394 EXPORT_SYMBOL_GPL(hw_perf_restore);
395
396 static inline u64 intel_pmu_get_status(void)
397 {
398         u64 status;
399
400         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
401
402         return status;
403 }
404
405 static inline void intel_pmu_ack_status(u64 ack)
406 {
407         wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
408 }
409
410 static inline void x86_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
411 {
412         int err;
413         err = checking_wrmsrl(hwc->config_base + idx,
414                               hwc->config | ARCH_PERFMON_EVENTSEL0_ENABLE);
415 }
416
417 static inline void x86_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
418 {
419         int err;
420         err = checking_wrmsrl(hwc->config_base + idx,
421                               hwc->config);
422 }
423
424 static inline void
425 intel_pmu_disable_fixed(struct hw_perf_counter *hwc, int __idx)
426 {
427         int idx = __idx - X86_PMC_IDX_FIXED;
428         u64 ctrl_val, mask;
429         int err;
430
431         mask = 0xfULL << (idx * 4);
432
433         rdmsrl(hwc->config_base, ctrl_val);
434         ctrl_val &= ~mask;
435         err = checking_wrmsrl(hwc->config_base, ctrl_val);
436 }
437
438 static inline void
439 intel_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
440 {
441         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
442                 intel_pmu_disable_fixed(hwc, idx);
443                 return;
444         }
445
446         x86_pmu_disable_counter(hwc, idx);
447 }
448
449 static inline void
450 amd_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
451 {
452         x86_pmu_disable_counter(hwc, idx);
453 }
454
455 static DEFINE_PER_CPU(u64, prev_left[X86_PMC_IDX_MAX]);
456
457 /*
458  * Set the next IRQ period, based on the hwc->period_left value.
459  * To be called with the counter disabled in hw:
460  */
461 static void
462 x86_perf_counter_set_period(struct perf_counter *counter,
463                              struct hw_perf_counter *hwc, int idx)
464 {
465         s64 left = atomic64_read(&hwc->period_left);
466         s64 period = hwc->irq_period;
467         int err;
468
469         /*
470          * If we are way outside a reasoable range then just skip forward:
471          */
472         if (unlikely(left <= -period)) {
473                 left = period;
474                 atomic64_set(&hwc->period_left, left);
475         }
476
477         if (unlikely(left <= 0)) {
478                 left += period;
479                 atomic64_set(&hwc->period_left, left);
480         }
481
482         per_cpu(prev_left[idx], smp_processor_id()) = left;
483
484         /*
485          * The hw counter starts counting from this counter offset,
486          * mark it to be able to extra future deltas:
487          */
488         atomic64_set(&hwc->prev_count, (u64)-left);
489
490         err = checking_wrmsrl(hwc->counter_base + idx,
491                              (u64)(-left) & x86_pmu.counter_mask);
492 }
493
494 static inline void
495 intel_pmu_enable_fixed(struct hw_perf_counter *hwc, int __idx)
496 {
497         int idx = __idx - X86_PMC_IDX_FIXED;
498         u64 ctrl_val, bits, mask;
499         int err;
500
501         /*
502          * Enable IRQ generation (0x8),
503          * and enable ring-3 counting (0x2) and ring-0 counting (0x1)
504          * if requested:
505          */
506         bits = 0x8ULL;
507         if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
508                 bits |= 0x2;
509         if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
510                 bits |= 0x1;
511         bits <<= (idx * 4);
512         mask = 0xfULL << (idx * 4);
513
514         rdmsrl(hwc->config_base, ctrl_val);
515         ctrl_val &= ~mask;
516         ctrl_val |= bits;
517         err = checking_wrmsrl(hwc->config_base, ctrl_val);
518 }
519
520 static void intel_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
521 {
522         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
523                 intel_pmu_enable_fixed(hwc, idx);
524                 return;
525         }
526
527         x86_pmu_enable_counter(hwc, idx);
528 }
529
530 static void amd_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
531 {
532         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
533
534         if (cpuc->enabled)
535                 x86_pmu_enable_counter(hwc, idx);
536         else
537                 x86_pmu_disable_counter(hwc, idx);
538 }
539
540 static int
541 fixed_mode_idx(struct perf_counter *counter, struct hw_perf_counter *hwc)
542 {
543         unsigned int event;
544
545         if (!x86_pmu.num_counters_fixed)
546                 return -1;
547
548         if (unlikely(hwc->nmi))
549                 return -1;
550
551         event = hwc->config & ARCH_PERFMON_EVENT_MASK;
552
553         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_INSTRUCTIONS)))
554                 return X86_PMC_IDX_FIXED_INSTRUCTIONS;
555         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_CPU_CYCLES)))
556                 return X86_PMC_IDX_FIXED_CPU_CYCLES;
557         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_BUS_CYCLES)))
558                 return X86_PMC_IDX_FIXED_BUS_CYCLES;
559
560         return -1;
561 }
562
563 /*
564  * Find a PMC slot for the freshly enabled / scheduled in counter:
565  */
566 static int x86_pmu_enable(struct perf_counter *counter)
567 {
568         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
569         struct hw_perf_counter *hwc = &counter->hw;
570         int idx;
571
572         idx = fixed_mode_idx(counter, hwc);
573         if (idx >= 0) {
574                 /*
575                  * Try to get the fixed counter, if that is already taken
576                  * then try to get a generic counter:
577                  */
578                 if (test_and_set_bit(idx, cpuc->used))
579                         goto try_generic;
580
581                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
582                 /*
583                  * We set it so that counter_base + idx in wrmsr/rdmsr maps to
584                  * MSR_ARCH_PERFMON_FIXED_CTR0 ... CTR2:
585                  */
586                 hwc->counter_base =
587                         MSR_ARCH_PERFMON_FIXED_CTR0 - X86_PMC_IDX_FIXED;
588                 hwc->idx = idx;
589         } else {
590                 idx = hwc->idx;
591                 /* Try to get the previous generic counter again */
592                 if (test_and_set_bit(idx, cpuc->used)) {
593 try_generic:
594                         idx = find_first_zero_bit(cpuc->used,
595                                                   x86_pmu.num_counters);
596                         if (idx == x86_pmu.num_counters)
597                                 return -EAGAIN;
598
599                         set_bit(idx, cpuc->used);
600                         hwc->idx = idx;
601                 }
602                 hwc->config_base  = x86_pmu.eventsel;
603                 hwc->counter_base = x86_pmu.perfctr;
604         }
605
606         perf_counters_lapic_init(hwc->nmi);
607
608         x86_pmu.disable(hwc, idx);
609
610         cpuc->counters[idx] = counter;
611         set_bit(idx, cpuc->active);
612
613         x86_perf_counter_set_period(counter, hwc, idx);
614         x86_pmu.enable(hwc, idx);
615
616         return 0;
617 }
618
619 void perf_counter_print_debug(void)
620 {
621         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
622         struct cpu_hw_counters *cpuc;
623         int cpu, idx;
624
625         if (!x86_pmu.num_counters)
626                 return;
627
628         local_irq_disable();
629
630         cpu = smp_processor_id();
631         cpuc = &per_cpu(cpu_hw_counters, cpu);
632
633         if (x86_pmu.version >= 2) {
634                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
635                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
636                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
637                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
638
639                 pr_info("\n");
640                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
641                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
642                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
643                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
644         }
645         pr_info("CPU#%d: used:       %016llx\n", cpu, *(u64 *)cpuc->used);
646
647         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
648                 rdmsrl(x86_pmu.eventsel + idx, pmc_ctrl);
649                 rdmsrl(x86_pmu.perfctr  + idx, pmc_count);
650
651                 prev_left = per_cpu(prev_left[idx], cpu);
652
653                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
654                         cpu, idx, pmc_ctrl);
655                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
656                         cpu, idx, pmc_count);
657                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
658                         cpu, idx, prev_left);
659         }
660         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
661                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
662
663                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
664                         cpu, idx, pmc_count);
665         }
666         local_irq_enable();
667 }
668
669 static void x86_pmu_disable(struct perf_counter *counter)
670 {
671         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
672         struct hw_perf_counter *hwc = &counter->hw;
673         int idx = hwc->idx;
674
675         /*
676          * Must be done before we disable, otherwise the nmi handler
677          * could reenable again:
678          */
679         clear_bit(idx, cpuc->active);
680         x86_pmu.disable(hwc, idx);
681
682         /*
683          * Make sure the cleared pointer becomes visible before we
684          * (potentially) free the counter:
685          */
686         barrier();
687
688         /*
689          * Drain the remaining delta count out of a counter
690          * that we are disabling:
691          */
692         x86_perf_counter_update(counter, hwc, idx);
693         cpuc->counters[idx] = NULL;
694         clear_bit(idx, cpuc->used);
695 }
696
697 /*
698  * Save and restart an expired counter. Called by NMI contexts,
699  * so it has to be careful about preempting normal counter ops:
700  */
701 static void intel_pmu_save_and_restart(struct perf_counter *counter)
702 {
703         struct hw_perf_counter *hwc = &counter->hw;
704         int idx = hwc->idx;
705
706         x86_perf_counter_update(counter, hwc, idx);
707         x86_perf_counter_set_period(counter, hwc, idx);
708
709         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
710                 intel_pmu_enable_counter(hwc, idx);
711 }
712
713 /*
714  * Maximum interrupt frequency of 100KHz per CPU
715  */
716 #define PERFMON_MAX_INTERRUPTS (100000/HZ)
717
718 /*
719  * This handler is triggered by the local APIC, so the APIC IRQ handling
720  * rules apply:
721  */
722 static int intel_pmu_handle_irq(struct pt_regs *regs, int nmi)
723 {
724         int bit, cpu = smp_processor_id();
725         u64 ack, status;
726         struct cpu_hw_counters *cpuc = &per_cpu(cpu_hw_counters, cpu);
727         int ret = 0;
728
729         cpuc->throttle_ctrl = intel_pmu_save_disable_all();
730
731         status = intel_pmu_get_status();
732         if (!status)
733                 goto out;
734
735         ret = 1;
736 again:
737         inc_irq_stat(apic_perf_irqs);
738         ack = status;
739         for_each_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
740                 struct perf_counter *counter = cpuc->counters[bit];
741
742                 clear_bit(bit, (unsigned long *) &status);
743                 if (!test_bit(bit, cpuc->active))
744                         continue;
745
746                 intel_pmu_save_and_restart(counter);
747                 if (perf_counter_overflow(counter, nmi, regs, 0))
748                         intel_pmu_disable_counter(&counter->hw, bit);
749         }
750
751         intel_pmu_ack_status(ack);
752
753         /*
754          * Repeat if there is more work to be done:
755          */
756         status = intel_pmu_get_status();
757         if (status)
758                 goto again;
759 out:
760         /*
761          * Restore - do not reenable when global enable is off or throttled:
762          */
763         if (++cpuc->interrupts < PERFMON_MAX_INTERRUPTS)
764                 intel_pmu_restore_all(cpuc->throttle_ctrl);
765
766         return ret;
767 }
768
769 static int amd_pmu_handle_irq(struct pt_regs *regs, int nmi)
770 {
771         int cpu = smp_processor_id();
772         struct cpu_hw_counters *cpuc = &per_cpu(cpu_hw_counters, cpu);
773         u64 val;
774         int handled = 0;
775         struct perf_counter *counter;
776         struct hw_perf_counter *hwc;
777         int idx;
778
779         ++cpuc->interrupts;
780         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
781                 if (!test_bit(idx, cpuc->active))
782                         continue;
783                 counter = cpuc->counters[idx];
784                 hwc = &counter->hw;
785                 val = x86_perf_counter_update(counter, hwc, idx);
786                 if (val & (1ULL << (x86_pmu.counter_bits - 1)))
787                         continue;
788                 /* counter overflow */
789                 x86_perf_counter_set_period(counter, hwc, idx);
790                 handled = 1;
791                 inc_irq_stat(apic_perf_irqs);
792                 if (perf_counter_overflow(counter, nmi, regs, 0))
793                         amd_pmu_disable_counter(hwc, idx);
794                 else if (cpuc->interrupts >= PERFMON_MAX_INTERRUPTS)
795                         /*
796                          * do not reenable when throttled, but reload
797                          * the register
798                          */
799                         amd_pmu_disable_counter(hwc, idx);
800                 else if (counter->state == PERF_COUNTER_STATE_ACTIVE)
801                         amd_pmu_enable_counter(hwc, idx);
802         }
803         return handled;
804 }
805
806 void perf_counter_unthrottle(void)
807 {
808         struct cpu_hw_counters *cpuc;
809
810         if (!x86_pmu_initialized())
811                 return;
812
813         cpuc = &__get_cpu_var(cpu_hw_counters);
814         if (cpuc->interrupts >= PERFMON_MAX_INTERRUPTS) {
815                 if (printk_ratelimit())
816                         printk(KERN_WARNING "PERFMON: max interrupts exceeded!\n");
817                 hw_perf_restore(cpuc->throttle_ctrl);
818         }
819         cpuc->interrupts = 0;
820 }
821
822 void smp_perf_counter_interrupt(struct pt_regs *regs)
823 {
824         irq_enter();
825         apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
826         ack_APIC_irq();
827         x86_pmu.handle_irq(regs, 0);
828         irq_exit();
829 }
830
831 void smp_perf_pending_interrupt(struct pt_regs *regs)
832 {
833         irq_enter();
834         ack_APIC_irq();
835         inc_irq_stat(apic_pending_irqs);
836         perf_counter_do_pending();
837         irq_exit();
838 }
839
840 void set_perf_counter_pending(void)
841 {
842         apic->send_IPI_self(LOCAL_PENDING_VECTOR);
843 }
844
845 void perf_counters_lapic_init(int nmi)
846 {
847         u32 apic_val;
848
849         if (!x86_pmu_initialized())
850                 return;
851
852         /*
853          * Enable the performance counter vector in the APIC LVT:
854          */
855         apic_val = apic_read(APIC_LVTERR);
856
857         apic_write(APIC_LVTERR, apic_val | APIC_LVT_MASKED);
858         if (nmi)
859                 apic_write(APIC_LVTPC, APIC_DM_NMI);
860         else
861                 apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
862         apic_write(APIC_LVTERR, apic_val);
863 }
864
865 static int __kprobes
866 perf_counter_nmi_handler(struct notifier_block *self,
867                          unsigned long cmd, void *__args)
868 {
869         struct die_args *args = __args;
870         struct pt_regs *regs;
871         int ret;
872
873         switch (cmd) {
874         case DIE_NMI:
875         case DIE_NMI_IPI:
876                 break;
877
878         default:
879                 return NOTIFY_DONE;
880         }
881
882         regs = args->regs;
883
884         apic_write(APIC_LVTPC, APIC_DM_NMI);
885         ret = x86_pmu.handle_irq(regs, 1);
886
887         return ret ? NOTIFY_STOP : NOTIFY_OK;
888 }
889
890 static __read_mostly struct notifier_block perf_counter_nmi_notifier = {
891         .notifier_call          = perf_counter_nmi_handler,
892         .next                   = NULL,
893         .priority               = 1
894 };
895
896 static struct x86_pmu intel_pmu = {
897         .name                   = "Intel",
898         .handle_irq             = intel_pmu_handle_irq,
899         .save_disable_all       = intel_pmu_save_disable_all,
900         .restore_all            = intel_pmu_restore_all,
901         .enable                 = intel_pmu_enable_counter,
902         .disable                = intel_pmu_disable_counter,
903         .eventsel               = MSR_ARCH_PERFMON_EVENTSEL0,
904         .perfctr                = MSR_ARCH_PERFMON_PERFCTR0,
905         .event_map              = intel_pmu_event_map,
906         .raw_event              = intel_pmu_raw_event,
907         .max_events             = ARRAY_SIZE(intel_perfmon_event_map),
908         /*
909          * Intel PMCs cannot be accessed sanely above 32 bit width,
910          * so we install an artificial 1<<31 period regardless of
911          * the generic counter period:
912          */
913         .max_period             = (1ULL << 31) - 1,
914 };
915
916 static struct x86_pmu amd_pmu = {
917         .name                   = "AMD",
918         .handle_irq             = amd_pmu_handle_irq,
919         .save_disable_all       = amd_pmu_save_disable_all,
920         .restore_all            = amd_pmu_restore_all,
921         .enable                 = amd_pmu_enable_counter,
922         .disable                = amd_pmu_disable_counter,
923         .eventsel               = MSR_K7_EVNTSEL0,
924         .perfctr                = MSR_K7_PERFCTR0,
925         .event_map              = amd_pmu_event_map,
926         .raw_event              = amd_pmu_raw_event,
927         .max_events             = ARRAY_SIZE(amd_perfmon_event_map),
928         .num_counters           = 4,
929         .counter_bits           = 48,
930         .counter_mask           = (1ULL << 48) - 1,
931         /* use highest bit to detect overflow */
932         .max_period             = (1ULL << 47) - 1,
933 };
934
935 static int intel_pmu_init(void)
936 {
937         union cpuid10_edx edx;
938         union cpuid10_eax eax;
939         unsigned int unused;
940         unsigned int ebx;
941         int version;
942
943         if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
944                 return -ENODEV;
945
946         /*
947          * Check whether the Architectural PerfMon supports
948          * Branch Misses Retired Event or not.
949          */
950         cpuid(10, &eax.full, &ebx, &unused, &edx.full);
951         if (eax.split.mask_length <= ARCH_PERFMON_BRANCH_MISSES_RETIRED)
952                 return -ENODEV;
953
954         version = eax.split.version_id;
955         if (version < 2)
956                 return -ENODEV;
957
958         x86_pmu = intel_pmu;
959         x86_pmu.version = version;
960         x86_pmu.num_counters = eax.split.num_counters;
961         x86_pmu.num_counters_fixed = edx.split.num_counters_fixed;
962         x86_pmu.counter_bits = eax.split.bit_width;
963         x86_pmu.counter_mask = (1ULL << eax.split.bit_width) - 1;
964
965         return 0;
966 }
967
968 static int amd_pmu_init(void)
969 {
970         x86_pmu = amd_pmu;
971         return 0;
972 }
973
974 void __init init_hw_perf_counters(void)
975 {
976         int err;
977
978         switch (boot_cpu_data.x86_vendor) {
979         case X86_VENDOR_INTEL:
980                 err = intel_pmu_init();
981                 break;
982         case X86_VENDOR_AMD:
983                 err = amd_pmu_init();
984                 break;
985         default:
986                 return;
987         }
988         if (err != 0)
989                 return;
990
991         pr_info("%s Performance Monitoring support detected.\n", x86_pmu.name);
992         pr_info("... version:         %d\n", x86_pmu.version);
993         pr_info("... bit width:       %d\n", x86_pmu.counter_bits);
994
995         pr_info("... num counters:    %d\n", x86_pmu.num_counters);
996         if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
997                 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
998                 WARN(1, KERN_ERR "hw perf counters %d > max(%d), clipping!",
999                      x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1000         }
1001         perf_counter_mask = (1 << x86_pmu.num_counters) - 1;
1002         perf_max_counters = x86_pmu.num_counters;
1003
1004         pr_info("... value mask:      %016Lx\n", x86_pmu.counter_mask);
1005         pr_info("... max period:      %016Lx\n", x86_pmu.max_period);
1006
1007         if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1008                 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1009                 WARN(1, KERN_ERR "hw perf counters fixed %d > max(%d), clipping!",
1010                      x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1011         }
1012         pr_info("... fixed counters:  %d\n", x86_pmu.num_counters_fixed);
1013
1014         perf_counter_mask |=
1015                 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1016
1017         pr_info("... counter mask:    %016Lx\n", perf_counter_mask);
1018
1019         perf_counters_lapic_init(0);
1020         register_die_notifier(&perf_counter_nmi_notifier);
1021 }
1022
1023 static inline void x86_pmu_read(struct perf_counter *counter)
1024 {
1025         x86_perf_counter_update(counter, &counter->hw, counter->hw.idx);
1026 }
1027
1028 static const struct pmu pmu = {
1029         .enable         = x86_pmu_enable,
1030         .disable        = x86_pmu_disable,
1031         .read           = x86_pmu_read,
1032 };
1033
1034 const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
1035 {
1036         int err;
1037
1038         err = __hw_perf_counter_init(counter);
1039         if (err)
1040                 return ERR_PTR(err);
1041
1042         return &pmu;
1043 }
1044
1045 /*
1046  * callchain support
1047  */
1048
1049 static inline
1050 void callchain_store(struct perf_callchain_entry *entry, unsigned long ip)
1051 {
1052         if (entry->nr < MAX_STACK_DEPTH)
1053                 entry->ip[entry->nr++] = ip;
1054 }
1055
1056 static DEFINE_PER_CPU(struct perf_callchain_entry, irq_entry);
1057 static DEFINE_PER_CPU(struct perf_callchain_entry, nmi_entry);
1058
1059
1060 static void
1061 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1062 {
1063         /* Ignore warnings */
1064 }
1065
1066 static void backtrace_warning(void *data, char *msg)
1067 {
1068         /* Ignore warnings */
1069 }
1070
1071 static int backtrace_stack(void *data, char *name)
1072 {
1073         /* Don't bother with IRQ stacks for now */
1074         return -1;
1075 }
1076
1077 static void backtrace_address(void *data, unsigned long addr, int reliable)
1078 {
1079         struct perf_callchain_entry *entry = data;
1080
1081         if (reliable)
1082                 callchain_store(entry, addr);
1083 }
1084
1085 static const struct stacktrace_ops backtrace_ops = {
1086         .warning                = backtrace_warning,
1087         .warning_symbol         = backtrace_warning_symbol,
1088         .stack                  = backtrace_stack,
1089         .address                = backtrace_address,
1090 };
1091
1092 static void
1093 perf_callchain_kernel(struct pt_regs *regs, struct perf_callchain_entry *entry)
1094 {
1095         unsigned long bp;
1096         char *stack;
1097         int nr = entry->nr;
1098
1099         callchain_store(entry, instruction_pointer(regs));
1100
1101         stack = ((char *)regs + sizeof(struct pt_regs));
1102 #ifdef CONFIG_FRAME_POINTER
1103         bp = frame_pointer(regs);
1104 #else
1105         bp = 0;
1106 #endif
1107
1108         dump_trace(NULL, regs, (void *)stack, bp, &backtrace_ops, entry);
1109
1110         entry->kernel = entry->nr - nr;
1111 }
1112
1113
1114 struct stack_frame {
1115         const void __user       *next_fp;
1116         unsigned long           return_address;
1117 };
1118
1119 static int copy_stack_frame(const void __user *fp, struct stack_frame *frame)
1120 {
1121         int ret;
1122
1123         if (!access_ok(VERIFY_READ, fp, sizeof(*frame)))
1124                 return 0;
1125
1126         ret = 1;
1127         pagefault_disable();
1128         if (__copy_from_user_inatomic(frame, fp, sizeof(*frame)))
1129                 ret = 0;
1130         pagefault_enable();
1131
1132         return ret;
1133 }
1134
1135 static void
1136 perf_callchain_user(struct pt_regs *regs, struct perf_callchain_entry *entry)
1137 {
1138         struct stack_frame frame;
1139         const void __user *fp;
1140         int nr = entry->nr;
1141
1142         regs = (struct pt_regs *)current->thread.sp0 - 1;
1143         fp   = (void __user *)regs->bp;
1144
1145         callchain_store(entry, regs->ip);
1146
1147         while (entry->nr < MAX_STACK_DEPTH) {
1148                 frame.next_fp        = NULL;
1149                 frame.return_address = 0;
1150
1151                 if (!copy_stack_frame(fp, &frame))
1152                         break;
1153
1154                 if ((unsigned long)fp < user_stack_pointer(regs))
1155                         break;
1156
1157                 callchain_store(entry, frame.return_address);
1158                 fp = frame.next_fp;
1159         }
1160
1161         entry->user = entry->nr - nr;
1162 }
1163
1164 static void
1165 perf_do_callchain(struct pt_regs *regs, struct perf_callchain_entry *entry)
1166 {
1167         int is_user;
1168
1169         if (!regs)
1170                 return;
1171
1172         is_user = user_mode(regs);
1173
1174         if (!current || current->pid == 0)
1175                 return;
1176
1177         if (is_user && current->state != TASK_RUNNING)
1178                 return;
1179
1180         if (!is_user)
1181                 perf_callchain_kernel(regs, entry);
1182
1183         if (current->mm)
1184                 perf_callchain_user(regs, entry);
1185 }
1186
1187 struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1188 {
1189         struct perf_callchain_entry *entry;
1190
1191         if (in_nmi())
1192                 entry = &__get_cpu_var(nmi_entry);
1193         else
1194                 entry = &__get_cpu_var(irq_entry);
1195
1196         entry->nr = 0;
1197         entry->hv = 0;
1198         entry->kernel = 0;
1199         entry->user = 0;
1200
1201         perf_do_callchain(regs, entry);
1202
1203         return entry;
1204 }