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