]> git.karo-electronics.de Git - mv-sheeva.git/blob - arch/x86/kernel/cpu/perf_counter.c
perf_counter: Rework the perf counter disable/enable
[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         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         void            (*disable_all)(void);
45         void            (*enable_all)(void);
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         u64             intel_ctrl;
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 void intel_pmu_disable_all(void)
315 {
316         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, 0);
317 }
318
319 static void amd_pmu_disable_all(void)
320 {
321         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
322         int idx;
323
324         if (!cpuc->enabled)
325                 return;
326
327         cpuc->enabled = 0;
328         /*
329          * ensure we write the disable before we start disabling the
330          * counters proper, so that amd_pmu_enable_counter() does the
331          * right thing.
332          */
333         barrier();
334
335         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
336                 u64 val;
337
338                 if (!test_bit(idx, cpuc->active_mask))
339                         continue;
340                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
341                 if (!(val & ARCH_PERFMON_EVENTSEL0_ENABLE))
342                         continue;
343                 val &= ~ARCH_PERFMON_EVENTSEL0_ENABLE;
344                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
345         }
346 }
347
348 void hw_perf_disable(void)
349 {
350         if (!x86_pmu_initialized())
351                 return;
352         return x86_pmu.disable_all();
353 }
354
355 static void intel_pmu_enable_all(void)
356 {
357         wrmsrl(MSR_CORE_PERF_GLOBAL_CTRL, x86_pmu.intel_ctrl);
358 }
359
360 static void amd_pmu_enable_all(void)
361 {
362         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
363         int idx;
364
365         if (cpuc->enabled)
366                 return;
367
368         cpuc->enabled = 1;
369         barrier();
370
371         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
372                 u64 val;
373
374                 if (!test_bit(idx, cpuc->active_mask))
375                         continue;
376                 rdmsrl(MSR_K7_EVNTSEL0 + idx, val);
377                 if (val & ARCH_PERFMON_EVENTSEL0_ENABLE)
378                         continue;
379                 val |= ARCH_PERFMON_EVENTSEL0_ENABLE;
380                 wrmsrl(MSR_K7_EVNTSEL0 + idx, val);
381         }
382 }
383
384 void hw_perf_enable(void)
385 {
386         if (!x86_pmu_initialized())
387                 return;
388         x86_pmu.enable_all();
389 }
390
391 static inline u64 intel_pmu_get_status(void)
392 {
393         u64 status;
394
395         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
396
397         return status;
398 }
399
400 static inline void intel_pmu_ack_status(u64 ack)
401 {
402         wrmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack);
403 }
404
405 static inline void x86_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
406 {
407         int err;
408         err = checking_wrmsrl(hwc->config_base + idx,
409                               hwc->config | ARCH_PERFMON_EVENTSEL0_ENABLE);
410 }
411
412 static inline void x86_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
413 {
414         int err;
415         err = checking_wrmsrl(hwc->config_base + idx,
416                               hwc->config);
417 }
418
419 static inline void
420 intel_pmu_disable_fixed(struct hw_perf_counter *hwc, int __idx)
421 {
422         int idx = __idx - X86_PMC_IDX_FIXED;
423         u64 ctrl_val, mask;
424         int err;
425
426         mask = 0xfULL << (idx * 4);
427
428         rdmsrl(hwc->config_base, ctrl_val);
429         ctrl_val &= ~mask;
430         err = checking_wrmsrl(hwc->config_base, ctrl_val);
431 }
432
433 static inline void
434 intel_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
435 {
436         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
437                 intel_pmu_disable_fixed(hwc, idx);
438                 return;
439         }
440
441         x86_pmu_disable_counter(hwc, idx);
442 }
443
444 static inline void
445 amd_pmu_disable_counter(struct hw_perf_counter *hwc, int idx)
446 {
447         x86_pmu_disable_counter(hwc, idx);
448 }
449
450 static DEFINE_PER_CPU(u64, prev_left[X86_PMC_IDX_MAX]);
451
452 /*
453  * Set the next IRQ period, based on the hwc->period_left value.
454  * To be called with the counter disabled in hw:
455  */
456 static void
457 x86_perf_counter_set_period(struct perf_counter *counter,
458                              struct hw_perf_counter *hwc, int idx)
459 {
460         s64 left = atomic64_read(&hwc->period_left);
461         s64 period = hwc->irq_period;
462         int err;
463
464         /*
465          * If we are way outside a reasoable range then just skip forward:
466          */
467         if (unlikely(left <= -period)) {
468                 left = period;
469                 atomic64_set(&hwc->period_left, left);
470         }
471
472         if (unlikely(left <= 0)) {
473                 left += period;
474                 atomic64_set(&hwc->period_left, left);
475         }
476
477         per_cpu(prev_left[idx], smp_processor_id()) = left;
478
479         /*
480          * The hw counter starts counting from this counter offset,
481          * mark it to be able to extra future deltas:
482          */
483         atomic64_set(&hwc->prev_count, (u64)-left);
484
485         err = checking_wrmsrl(hwc->counter_base + idx,
486                              (u64)(-left) & x86_pmu.counter_mask);
487 }
488
489 static inline void
490 intel_pmu_enable_fixed(struct hw_perf_counter *hwc, int __idx)
491 {
492         int idx = __idx - X86_PMC_IDX_FIXED;
493         u64 ctrl_val, bits, mask;
494         int err;
495
496         /*
497          * Enable IRQ generation (0x8),
498          * and enable ring-3 counting (0x2) and ring-0 counting (0x1)
499          * if requested:
500          */
501         bits = 0x8ULL;
502         if (hwc->config & ARCH_PERFMON_EVENTSEL_USR)
503                 bits |= 0x2;
504         if (hwc->config & ARCH_PERFMON_EVENTSEL_OS)
505                 bits |= 0x1;
506         bits <<= (idx * 4);
507         mask = 0xfULL << (idx * 4);
508
509         rdmsrl(hwc->config_base, ctrl_val);
510         ctrl_val &= ~mask;
511         ctrl_val |= bits;
512         err = checking_wrmsrl(hwc->config_base, ctrl_val);
513 }
514
515 static void intel_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
516 {
517         if (unlikely(hwc->config_base == MSR_ARCH_PERFMON_FIXED_CTR_CTRL)) {
518                 intel_pmu_enable_fixed(hwc, idx);
519                 return;
520         }
521
522         x86_pmu_enable_counter(hwc, idx);
523 }
524
525 static void amd_pmu_enable_counter(struct hw_perf_counter *hwc, int idx)
526 {
527         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
528
529         if (cpuc->enabled)
530                 x86_pmu_enable_counter(hwc, idx);
531         else
532                 x86_pmu_disable_counter(hwc, idx);
533 }
534
535 static int
536 fixed_mode_idx(struct perf_counter *counter, struct hw_perf_counter *hwc)
537 {
538         unsigned int event;
539
540         if (!x86_pmu.num_counters_fixed)
541                 return -1;
542
543         if (unlikely(hwc->nmi))
544                 return -1;
545
546         event = hwc->config & ARCH_PERFMON_EVENT_MASK;
547
548         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_INSTRUCTIONS)))
549                 return X86_PMC_IDX_FIXED_INSTRUCTIONS;
550         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_CPU_CYCLES)))
551                 return X86_PMC_IDX_FIXED_CPU_CYCLES;
552         if (unlikely(event == x86_pmu.event_map(PERF_COUNT_BUS_CYCLES)))
553                 return X86_PMC_IDX_FIXED_BUS_CYCLES;
554
555         return -1;
556 }
557
558 /*
559  * Find a PMC slot for the freshly enabled / scheduled in counter:
560  */
561 static int x86_pmu_enable(struct perf_counter *counter)
562 {
563         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
564         struct hw_perf_counter *hwc = &counter->hw;
565         int idx;
566
567         idx = fixed_mode_idx(counter, hwc);
568         if (idx >= 0) {
569                 /*
570                  * Try to get the fixed counter, if that is already taken
571                  * then try to get a generic counter:
572                  */
573                 if (test_and_set_bit(idx, cpuc->used_mask))
574                         goto try_generic;
575
576                 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
577                 /*
578                  * We set it so that counter_base + idx in wrmsr/rdmsr maps to
579                  * MSR_ARCH_PERFMON_FIXED_CTR0 ... CTR2:
580                  */
581                 hwc->counter_base =
582                         MSR_ARCH_PERFMON_FIXED_CTR0 - X86_PMC_IDX_FIXED;
583                 hwc->idx = idx;
584         } else {
585                 idx = hwc->idx;
586                 /* Try to get the previous generic counter again */
587                 if (test_and_set_bit(idx, cpuc->used_mask)) {
588 try_generic:
589                         idx = find_first_zero_bit(cpuc->used_mask,
590                                                   x86_pmu.num_counters);
591                         if (idx == x86_pmu.num_counters)
592                                 return -EAGAIN;
593
594                         set_bit(idx, cpuc->used_mask);
595                         hwc->idx = idx;
596                 }
597                 hwc->config_base  = x86_pmu.eventsel;
598                 hwc->counter_base = x86_pmu.perfctr;
599         }
600
601         perf_counters_lapic_init(hwc->nmi);
602
603         x86_pmu.disable(hwc, idx);
604
605         cpuc->counters[idx] = counter;
606         set_bit(idx, cpuc->active_mask);
607
608         x86_perf_counter_set_period(counter, hwc, idx);
609         x86_pmu.enable(hwc, idx);
610
611         return 0;
612 }
613
614 void perf_counter_print_debug(void)
615 {
616         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
617         struct cpu_hw_counters *cpuc;
618         unsigned long flags;
619         int cpu, idx;
620
621         if (!x86_pmu.num_counters)
622                 return;
623
624         local_irq_save(flags);
625
626         cpu = smp_processor_id();
627         cpuc = &per_cpu(cpu_hw_counters, cpu);
628
629         if (x86_pmu.version >= 2) {
630                 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
631                 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
632                 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
633                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
634
635                 pr_info("\n");
636                 pr_info("CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
637                 pr_info("CPU#%d: status:     %016llx\n", cpu, status);
638                 pr_info("CPU#%d: overflow:   %016llx\n", cpu, overflow);
639                 pr_info("CPU#%d: fixed:      %016llx\n", cpu, fixed);
640         }
641         pr_info("CPU#%d: used:       %016llx\n", cpu, *(u64 *)cpuc->used_mask);
642
643         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
644                 rdmsrl(x86_pmu.eventsel + idx, pmc_ctrl);
645                 rdmsrl(x86_pmu.perfctr  + idx, pmc_count);
646
647                 prev_left = per_cpu(prev_left[idx], cpu);
648
649                 pr_info("CPU#%d:   gen-PMC%d ctrl:  %016llx\n",
650                         cpu, idx, pmc_ctrl);
651                 pr_info("CPU#%d:   gen-PMC%d count: %016llx\n",
652                         cpu, idx, pmc_count);
653                 pr_info("CPU#%d:   gen-PMC%d left:  %016llx\n",
654                         cpu, idx, prev_left);
655         }
656         for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
657                 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
658
659                 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
660                         cpu, idx, pmc_count);
661         }
662         local_irq_restore(flags);
663 }
664
665 static void x86_pmu_disable(struct perf_counter *counter)
666 {
667         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
668         struct hw_perf_counter *hwc = &counter->hw;
669         int idx = hwc->idx;
670
671         /*
672          * Must be done before we disable, otherwise the nmi handler
673          * could reenable again:
674          */
675         clear_bit(idx, cpuc->active_mask);
676         x86_pmu.disable(hwc, idx);
677
678         /*
679          * Make sure the cleared pointer becomes visible before we
680          * (potentially) free the counter:
681          */
682         barrier();
683
684         /*
685          * Drain the remaining delta count out of a counter
686          * that we are disabling:
687          */
688         x86_perf_counter_update(counter, hwc, idx);
689         cpuc->counters[idx] = NULL;
690         clear_bit(idx, cpuc->used_mask);
691 }
692
693 /*
694  * Save and restart an expired counter. Called by NMI contexts,
695  * so it has to be careful about preempting normal counter ops:
696  */
697 static void intel_pmu_save_and_restart(struct perf_counter *counter)
698 {
699         struct hw_perf_counter *hwc = &counter->hw;
700         int idx = hwc->idx;
701
702         x86_perf_counter_update(counter, hwc, idx);
703         x86_perf_counter_set_period(counter, hwc, idx);
704
705         if (counter->state == PERF_COUNTER_STATE_ACTIVE)
706                 intel_pmu_enable_counter(hwc, idx);
707 }
708
709 /*
710  * Maximum interrupt frequency of 100KHz per CPU
711  */
712 #define PERFMON_MAX_INTERRUPTS (100000/HZ)
713
714 /*
715  * This handler is triggered by the local APIC, so the APIC IRQ handling
716  * rules apply:
717  */
718 static int intel_pmu_handle_irq(struct pt_regs *regs, int nmi)
719 {
720         int bit, cpu = smp_processor_id();
721         u64 ack, status;
722         struct cpu_hw_counters *cpuc = &per_cpu(cpu_hw_counters, cpu);
723
724         perf_disable();
725         status = intel_pmu_get_status();
726         if (!status) {
727                 perf_enable();
728                 return 0;
729         }
730
731 again:
732         inc_irq_stat(apic_perf_irqs);
733         ack = status;
734         for_each_bit(bit, (unsigned long *)&status, X86_PMC_IDX_MAX) {
735                 struct perf_counter *counter = cpuc->counters[bit];
736
737                 clear_bit(bit, (unsigned long *) &status);
738                 if (!test_bit(bit, cpuc->active_mask))
739                         continue;
740
741                 intel_pmu_save_and_restart(counter);
742                 if (perf_counter_overflow(counter, nmi, regs, 0))
743                         intel_pmu_disable_counter(&counter->hw, bit);
744         }
745
746         intel_pmu_ack_status(ack);
747
748         /*
749          * Repeat if there is more work to be done:
750          */
751         status = intel_pmu_get_status();
752         if (status)
753                 goto again;
754
755         if (++cpuc->interrupts != PERFMON_MAX_INTERRUPTS)
756                 perf_enable();
757
758         return 1;
759 }
760
761 static int amd_pmu_handle_irq(struct pt_regs *regs, int nmi)
762 {
763         int cpu = smp_processor_id();
764         struct cpu_hw_counters *cpuc = &per_cpu(cpu_hw_counters, cpu);
765         u64 val;
766         int handled = 0;
767         struct perf_counter *counter;
768         struct hw_perf_counter *hwc;
769         int idx, throttle = 0;
770
771         if (++cpuc->interrupts == PERFMON_MAX_INTERRUPTS) {
772                 throttle = 1;
773                 __perf_disable();
774                 cpuc->enabled = 0;
775                 barrier();
776         }
777
778         for (idx = 0; idx < x86_pmu.num_counters; idx++) {
779                 int disable = 0;
780
781                 if (!test_bit(idx, cpuc->active_mask))
782                         continue;
783
784                 counter = cpuc->counters[idx];
785                 hwc = &counter->hw;
786                 val = x86_perf_counter_update(counter, hwc, idx);
787                 if (val & (1ULL << (x86_pmu.counter_bits - 1)))
788                         goto next;
789
790                 /* counter overflow */
791                 x86_perf_counter_set_period(counter, hwc, idx);
792                 handled = 1;
793                 inc_irq_stat(apic_perf_irqs);
794                 disable = perf_counter_overflow(counter, nmi, regs, 0);
795
796 next:
797                 if (disable || throttle)
798                         amd_pmu_disable_counter(hwc, idx);
799         }
800
801         return handled;
802 }
803
804 void perf_counter_unthrottle(void)
805 {
806         struct cpu_hw_counters *cpuc;
807
808         if (!x86_pmu_initialized())
809                 return;
810
811         cpuc = &__get_cpu_var(cpu_hw_counters);
812         if (cpuc->interrupts >= PERFMON_MAX_INTERRUPTS) {
813                 /*
814                  * Clear them before re-enabling irqs/NMIs again:
815                  */
816                 cpuc->interrupts = 0;
817                 perf_enable();
818         } else {
819                 cpuc->interrupts = 0;
820         }
821 }
822
823 void smp_perf_counter_interrupt(struct pt_regs *regs)
824 {
825         irq_enter();
826         apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
827         ack_APIC_irq();
828         x86_pmu.handle_irq(regs, 0);
829         irq_exit();
830 }
831
832 void smp_perf_pending_interrupt(struct pt_regs *regs)
833 {
834         irq_enter();
835         ack_APIC_irq();
836         inc_irq_stat(apic_pending_irqs);
837         perf_counter_do_pending();
838         irq_exit();
839 }
840
841 void set_perf_counter_pending(void)
842 {
843         apic->send_IPI_self(LOCAL_PENDING_VECTOR);
844 }
845
846 void perf_counters_lapic_init(int nmi)
847 {
848         u32 apic_val;
849
850         if (!x86_pmu_initialized())
851                 return;
852
853         /*
854          * Enable the performance counter vector in the APIC LVT:
855          */
856         apic_val = apic_read(APIC_LVTERR);
857
858         apic_write(APIC_LVTERR, apic_val | APIC_LVT_MASKED);
859         if (nmi)
860                 apic_write(APIC_LVTPC, APIC_DM_NMI);
861         else
862                 apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
863         apic_write(APIC_LVTERR, apic_val);
864 }
865
866 static int __kprobes
867 perf_counter_nmi_handler(struct notifier_block *self,
868                          unsigned long cmd, void *__args)
869 {
870         struct die_args *args = __args;
871         struct pt_regs *regs;
872         int ret;
873
874         if (!atomic_read(&active_counters))
875                 return NOTIFY_DONE;
876
877         switch (cmd) {
878         case DIE_NMI:
879         case DIE_NMI_IPI:
880                 break;
881
882         default:
883                 return NOTIFY_DONE;
884         }
885
886         regs = args->regs;
887
888         apic_write(APIC_LVTPC, APIC_DM_NMI);
889         ret = x86_pmu.handle_irq(regs, 1);
890
891         return ret ? NOTIFY_STOP : NOTIFY_OK;
892 }
893
894 static __read_mostly struct notifier_block perf_counter_nmi_notifier = {
895         .notifier_call          = perf_counter_nmi_handler,
896         .next                   = NULL,
897         .priority               = 1
898 };
899
900 static struct x86_pmu intel_pmu = {
901         .name                   = "Intel",
902         .handle_irq             = intel_pmu_handle_irq,
903         .disable_all            = intel_pmu_disable_all,
904         .enable_all             = intel_pmu_enable_all,
905         .enable                 = intel_pmu_enable_counter,
906         .disable                = intel_pmu_disable_counter,
907         .eventsel               = MSR_ARCH_PERFMON_EVENTSEL0,
908         .perfctr                = MSR_ARCH_PERFMON_PERFCTR0,
909         .event_map              = intel_pmu_event_map,
910         .raw_event              = intel_pmu_raw_event,
911         .max_events             = ARRAY_SIZE(intel_perfmon_event_map),
912         /*
913          * Intel PMCs cannot be accessed sanely above 32 bit width,
914          * so we install an artificial 1<<31 period regardless of
915          * the generic counter period:
916          */
917         .max_period             = (1ULL << 31) - 1,
918 };
919
920 static struct x86_pmu amd_pmu = {
921         .name                   = "AMD",
922         .handle_irq             = amd_pmu_handle_irq,
923         .disable_all            = amd_pmu_disable_all,
924         .enable_all             = amd_pmu_enable_all,
925         .enable                 = amd_pmu_enable_counter,
926         .disable                = amd_pmu_disable_counter,
927         .eventsel               = MSR_K7_EVNTSEL0,
928         .perfctr                = MSR_K7_PERFCTR0,
929         .event_map              = amd_pmu_event_map,
930         .raw_event              = amd_pmu_raw_event,
931         .max_events             = ARRAY_SIZE(amd_perfmon_event_map),
932         .num_counters           = 4,
933         .counter_bits           = 48,
934         .counter_mask           = (1ULL << 48) - 1,
935         /* use highest bit to detect overflow */
936         .max_period             = (1ULL << 47) - 1,
937 };
938
939 static int intel_pmu_init(void)
940 {
941         union cpuid10_edx edx;
942         union cpuid10_eax eax;
943         unsigned int unused;
944         unsigned int ebx;
945         int version;
946
947         if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
948                 return -ENODEV;
949
950         /*
951          * Check whether the Architectural PerfMon supports
952          * Branch Misses Retired Event or not.
953          */
954         cpuid(10, &eax.full, &ebx, &unused, &edx.full);
955         if (eax.split.mask_length <= ARCH_PERFMON_BRANCH_MISSES_RETIRED)
956                 return -ENODEV;
957
958         version = eax.split.version_id;
959         if (version < 2)
960                 return -ENODEV;
961
962         x86_pmu = intel_pmu;
963         x86_pmu.version = version;
964         x86_pmu.num_counters = eax.split.num_counters;
965
966         /*
967          * Quirk: v2 perfmon does not report fixed-purpose counters, so
968          * assume at least 3 counters:
969          */
970         x86_pmu.num_counters_fixed = max((int)edx.split.num_counters_fixed, 3);
971
972         x86_pmu.counter_bits = eax.split.bit_width;
973         x86_pmu.counter_mask = (1ULL << eax.split.bit_width) - 1;
974
975         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, x86_pmu.intel_ctrl);
976
977         return 0;
978 }
979
980 static int amd_pmu_init(void)
981 {
982         x86_pmu = amd_pmu;
983         return 0;
984 }
985
986 void __init init_hw_perf_counters(void)
987 {
988         int err;
989
990         switch (boot_cpu_data.x86_vendor) {
991         case X86_VENDOR_INTEL:
992                 err = intel_pmu_init();
993                 break;
994         case X86_VENDOR_AMD:
995                 err = amd_pmu_init();
996                 break;
997         default:
998                 return;
999         }
1000         if (err != 0)
1001                 return;
1002
1003         pr_info("%s Performance Monitoring support detected.\n", x86_pmu.name);
1004         pr_info("... version:         %d\n", x86_pmu.version);
1005         pr_info("... bit width:       %d\n", x86_pmu.counter_bits);
1006
1007         pr_info("... num counters:    %d\n", x86_pmu.num_counters);
1008         if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1009                 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1010                 WARN(1, KERN_ERR "hw perf counters %d > max(%d), clipping!",
1011                      x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1012         }
1013         perf_counter_mask = (1 << x86_pmu.num_counters) - 1;
1014         perf_max_counters = x86_pmu.num_counters;
1015
1016         pr_info("... value mask:      %016Lx\n", x86_pmu.counter_mask);
1017         pr_info("... max period:      %016Lx\n", x86_pmu.max_period);
1018
1019         if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1020                 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1021                 WARN(1, KERN_ERR "hw perf counters fixed %d > max(%d), clipping!",
1022                      x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1023         }
1024         pr_info("... fixed counters:  %d\n", x86_pmu.num_counters_fixed);
1025
1026         perf_counter_mask |=
1027                 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1028
1029         pr_info("... counter mask:    %016Lx\n", perf_counter_mask);
1030
1031         perf_counters_lapic_init(0);
1032         register_die_notifier(&perf_counter_nmi_notifier);
1033 }
1034
1035 static inline void x86_pmu_read(struct perf_counter *counter)
1036 {
1037         x86_perf_counter_update(counter, &counter->hw, counter->hw.idx);
1038 }
1039
1040 static const struct pmu pmu = {
1041         .enable         = x86_pmu_enable,
1042         .disable        = x86_pmu_disable,
1043         .read           = x86_pmu_read,
1044 };
1045
1046 const struct pmu *hw_perf_counter_init(struct perf_counter *counter)
1047 {
1048         int err;
1049
1050         err = __hw_perf_counter_init(counter);
1051         if (err)
1052                 return ERR_PTR(err);
1053
1054         return &pmu;
1055 }
1056
1057 /*
1058  * callchain support
1059  */
1060
1061 static inline
1062 void callchain_store(struct perf_callchain_entry *entry, unsigned long ip)
1063 {
1064         if (entry->nr < MAX_STACK_DEPTH)
1065                 entry->ip[entry->nr++] = ip;
1066 }
1067
1068 static DEFINE_PER_CPU(struct perf_callchain_entry, irq_entry);
1069 static DEFINE_PER_CPU(struct perf_callchain_entry, nmi_entry);
1070
1071
1072 static void
1073 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1074 {
1075         /* Ignore warnings */
1076 }
1077
1078 static void backtrace_warning(void *data, char *msg)
1079 {
1080         /* Ignore warnings */
1081 }
1082
1083 static int backtrace_stack(void *data, char *name)
1084 {
1085         /* Don't bother with IRQ stacks for now */
1086         return -1;
1087 }
1088
1089 static void backtrace_address(void *data, unsigned long addr, int reliable)
1090 {
1091         struct perf_callchain_entry *entry = data;
1092
1093         if (reliable)
1094                 callchain_store(entry, addr);
1095 }
1096
1097 static const struct stacktrace_ops backtrace_ops = {
1098         .warning                = backtrace_warning,
1099         .warning_symbol         = backtrace_warning_symbol,
1100         .stack                  = backtrace_stack,
1101         .address                = backtrace_address,
1102 };
1103
1104 static void
1105 perf_callchain_kernel(struct pt_regs *regs, struct perf_callchain_entry *entry)
1106 {
1107         unsigned long bp;
1108         char *stack;
1109         int nr = entry->nr;
1110
1111         callchain_store(entry, instruction_pointer(regs));
1112
1113         stack = ((char *)regs + sizeof(struct pt_regs));
1114 #ifdef CONFIG_FRAME_POINTER
1115         bp = frame_pointer(regs);
1116 #else
1117         bp = 0;
1118 #endif
1119
1120         dump_trace(NULL, regs, (void *)stack, bp, &backtrace_ops, entry);
1121
1122         entry->kernel = entry->nr - nr;
1123 }
1124
1125
1126 struct stack_frame {
1127         const void __user       *next_fp;
1128         unsigned long           return_address;
1129 };
1130
1131 static int copy_stack_frame(const void __user *fp, struct stack_frame *frame)
1132 {
1133         int ret;
1134
1135         if (!access_ok(VERIFY_READ, fp, sizeof(*frame)))
1136                 return 0;
1137
1138         ret = 1;
1139         pagefault_disable();
1140         if (__copy_from_user_inatomic(frame, fp, sizeof(*frame)))
1141                 ret = 0;
1142         pagefault_enable();
1143
1144         return ret;
1145 }
1146
1147 static void
1148 perf_callchain_user(struct pt_regs *regs, struct perf_callchain_entry *entry)
1149 {
1150         struct stack_frame frame;
1151         const void __user *fp;
1152         int nr = entry->nr;
1153
1154         regs = (struct pt_regs *)current->thread.sp0 - 1;
1155         fp   = (void __user *)regs->bp;
1156
1157         callchain_store(entry, regs->ip);
1158
1159         while (entry->nr < MAX_STACK_DEPTH) {
1160                 frame.next_fp        = NULL;
1161                 frame.return_address = 0;
1162
1163                 if (!copy_stack_frame(fp, &frame))
1164                         break;
1165
1166                 if ((unsigned long)fp < user_stack_pointer(regs))
1167                         break;
1168
1169                 callchain_store(entry, frame.return_address);
1170                 fp = frame.next_fp;
1171         }
1172
1173         entry->user = entry->nr - nr;
1174 }
1175
1176 static void
1177 perf_do_callchain(struct pt_regs *regs, struct perf_callchain_entry *entry)
1178 {
1179         int is_user;
1180
1181         if (!regs)
1182                 return;
1183
1184         is_user = user_mode(regs);
1185
1186         if (!current || current->pid == 0)
1187                 return;
1188
1189         if (is_user && current->state != TASK_RUNNING)
1190                 return;
1191
1192         if (!is_user)
1193                 perf_callchain_kernel(regs, entry);
1194
1195         if (current->mm)
1196                 perf_callchain_user(regs, entry);
1197 }
1198
1199 struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
1200 {
1201         struct perf_callchain_entry *entry;
1202
1203         if (in_nmi())
1204                 entry = &__get_cpu_var(nmi_entry);
1205         else
1206                 entry = &__get_cpu_var(irq_entry);
1207
1208         entry->nr = 0;
1209         entry->hv = 0;
1210         entry->kernel = 0;
1211         entry->user = 0;
1212
1213         perf_do_callchain(regs, entry);
1214
1215         return entry;
1216 }