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