perfcounters: add fixed-mode PMC enumeration
[pandora-kernel.git] / arch / x86 / kernel / cpu / perf_counter.c
1 /*
2  * Performance counter x86 architecture code
3  *
4  *  Copyright(C) 2008 Thomas Gleixner <tglx@linutronix.de>
5  *  Copyright(C) 2008 Red Hat, Inc., Ingo Molnar
6  *
7  *  For licencing details see kernel-base/COPYING
8  */
9
10 #include <linux/perf_counter.h>
11 #include <linux/capability.h>
12 #include <linux/notifier.h>
13 #include <linux/hardirq.h>
14 #include <linux/kprobes.h>
15 #include <linux/module.h>
16 #include <linux/kdebug.h>
17 #include <linux/sched.h>
18
19 #include <asm/perf_counter.h>
20 #include <asm/apic.h>
21
22 static bool perf_counters_initialized __read_mostly;
23
24 /*
25  * Number of (generic) HW counters:
26  */
27 static int nr_hw_counters __read_mostly;
28 static u32 perf_counter_mask __read_mostly;
29
30 static int nr_hw_counters_fixed __read_mostly;
31
32 struct cpu_hw_counters {
33         struct perf_counter     *generic[X86_PMC_MAX_GENERIC];
34         unsigned long           used[BITS_TO_LONGS(X86_PMC_MAX_GENERIC)];
35
36         struct perf_counter     *fixed[X86_PMC_MAX_FIXED];
37         unsigned long           used_fixed[BITS_TO_LONGS(X86_PMC_MAX_FIXED)];
38 };
39
40 /*
41  * Intel PerfMon v3. Used on Core2 and later.
42  */
43 static DEFINE_PER_CPU(struct cpu_hw_counters, cpu_hw_counters);
44
45 static const int intel_perfmon_event_map[] =
46 {
47   [PERF_COUNT_CYCLES]                   = 0x003c,
48   [PERF_COUNT_INSTRUCTIONS]             = 0x00c0,
49   [PERF_COUNT_CACHE_REFERENCES]         = 0x4f2e,
50   [PERF_COUNT_CACHE_MISSES]             = 0x412e,
51   [PERF_COUNT_BRANCH_INSTRUCTIONS]      = 0x00c4,
52   [PERF_COUNT_BRANCH_MISSES]            = 0x00c5,
53 };
54
55 static const int max_intel_perfmon_events = ARRAY_SIZE(intel_perfmon_event_map);
56
57 /*
58  * Propagate counter elapsed time into the generic counter.
59  * Can only be executed on the CPU where the counter is active.
60  * Returns the delta events processed.
61  */
62 static void
63 x86_perf_counter_update(struct perf_counter *counter,
64                         struct hw_perf_counter *hwc, int idx)
65 {
66         u64 prev_raw_count, new_raw_count, delta;
67
68         /*
69          * Careful: an NMI might modify the previous counter value.
70          *
71          * Our tactic to handle this is to first atomically read and
72          * exchange a new raw count - then add that new-prev delta
73          * count to the generic counter atomically:
74          */
75 again:
76         prev_raw_count = atomic64_read(&hwc->prev_count);
77         rdmsrl(hwc->counter_base + idx, new_raw_count);
78
79         if (atomic64_cmpxchg(&hwc->prev_count, prev_raw_count,
80                                         new_raw_count) != prev_raw_count)
81                 goto again;
82
83         /*
84          * Now we have the new raw value and have updated the prev
85          * timestamp already. We can now calculate the elapsed delta
86          * (counter-)time and add that to the generic counter.
87          *
88          * Careful, not all hw sign-extends above the physical width
89          * of the count, so we do that by clipping the delta to 32 bits:
90          */
91         delta = (u64)(u32)((s32)new_raw_count - (s32)prev_raw_count);
92
93         atomic64_add(delta, &counter->count);
94         atomic64_sub(delta, &hwc->period_left);
95 }
96
97 /*
98  * Setup the hardware configuration for a given hw_event_type
99  */
100 static int __hw_perf_counter_init(struct perf_counter *counter)
101 {
102         struct perf_counter_hw_event *hw_event = &counter->hw_event;
103         struct hw_perf_counter *hwc = &counter->hw;
104
105         if (unlikely(!perf_counters_initialized))
106                 return -EINVAL;
107
108         /*
109          * Count user events, and generate PMC IRQs:
110          * (keep 'enabled' bit clear for now)
111          */
112         hwc->config = ARCH_PERFMON_EVENTSEL_USR | ARCH_PERFMON_EVENTSEL_INT;
113
114         /*
115          * If privileged enough, count OS events too, and allow
116          * NMI events as well:
117          */
118         hwc->nmi = 0;
119         if (capable(CAP_SYS_ADMIN)) {
120                 hwc->config |= ARCH_PERFMON_EVENTSEL_OS;
121                 if (hw_event->nmi)
122                         hwc->nmi = 1;
123         }
124
125         hwc->config_base        = MSR_ARCH_PERFMON_EVENTSEL0;
126         hwc->counter_base       = MSR_ARCH_PERFMON_PERFCTR0;
127
128         hwc->irq_period         = hw_event->irq_period;
129         /*
130          * Intel PMCs cannot be accessed sanely above 32 bit width,
131          * so we install an artificial 1<<31 period regardless of
132          * the generic counter period:
133          */
134         if ((s64)hwc->irq_period <= 0 || hwc->irq_period > 0x7FFFFFFF)
135                 hwc->irq_period = 0x7FFFFFFF;
136
137         atomic64_set(&hwc->period_left, hwc->irq_period);
138
139         /*
140          * Raw event type provide the config in the event structure
141          */
142         if (hw_event->raw) {
143                 hwc->config |= hw_event->type;
144         } else {
145                 if (hw_event->type >= max_intel_perfmon_events)
146                         return -EINVAL;
147                 /*
148                  * The generic map:
149                  */
150                 hwc->config |= intel_perfmon_event_map[hw_event->type];
151         }
152         counter->wakeup_pending = 0;
153
154         return 0;
155 }
156
157 void hw_perf_enable_all(void)
158 {
159         if (unlikely(!perf_counters_initialized))
160                 return;
161
162         wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, perf_counter_mask, 0);
163 }
164
165 u64 hw_perf_save_disable(void)
166 {
167         u64 ctrl;
168
169         if (unlikely(!perf_counters_initialized))
170                 return 0;
171
172         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
173         wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, 0, 0);
174
175         return ctrl;
176 }
177 EXPORT_SYMBOL_GPL(hw_perf_save_disable);
178
179 void hw_perf_restore(u64 ctrl)
180 {
181         if (unlikely(!perf_counters_initialized))
182                 return;
183
184         wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, ctrl, 0);
185 }
186 EXPORT_SYMBOL_GPL(hw_perf_restore);
187
188 static inline void
189 __pmc_generic_disable(struct perf_counter *counter,
190                            struct hw_perf_counter *hwc, unsigned int idx)
191 {
192         int err;
193
194         err = wrmsr_safe(hwc->config_base + idx, hwc->config, 0);
195 }
196
197 static DEFINE_PER_CPU(u64, prev_left[X86_PMC_MAX_GENERIC]);
198
199 /*
200  * Set the next IRQ period, based on the hwc->period_left value.
201  * To be called with the counter disabled in hw:
202  */
203 static void
204 __hw_perf_counter_set_period(struct perf_counter *counter,
205                              struct hw_perf_counter *hwc, int idx)
206 {
207         s32 left = atomic64_read(&hwc->period_left);
208         s32 period = hwc->irq_period;
209
210         /*
211          * If we are way outside a reasoable range then just skip forward:
212          */
213         if (unlikely(left <= -period)) {
214                 left = period;
215                 atomic64_set(&hwc->period_left, left);
216         }
217
218         if (unlikely(left <= 0)) {
219                 left += period;
220                 atomic64_set(&hwc->period_left, left);
221         }
222
223         per_cpu(prev_left[idx], smp_processor_id()) = left;
224
225         /*
226          * The hw counter starts counting from this counter offset,
227          * mark it to be able to extra future deltas:
228          */
229         atomic64_set(&hwc->prev_count, (u64)(s64)-left);
230
231         wrmsr(hwc->counter_base + idx, -left, 0);
232 }
233
234 static void
235 __pmc_generic_enable(struct perf_counter *counter,
236                           struct hw_perf_counter *hwc, int idx)
237 {
238         wrmsr(hwc->config_base + idx,
239               hwc->config | ARCH_PERFMON_EVENTSEL0_ENABLE, 0);
240 }
241
242 /*
243  * Find a PMC slot for the freshly enabled / scheduled in counter:
244  */
245 static void pmc_generic_enable(struct perf_counter *counter)
246 {
247         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
248         struct hw_perf_counter *hwc = &counter->hw;
249         int idx = hwc->idx;
250
251         /* Try to get the previous counter again */
252         if (test_and_set_bit(idx, cpuc->used)) {
253                 idx = find_first_zero_bit(cpuc->used, nr_hw_counters);
254                 set_bit(idx, cpuc->used);
255                 hwc->idx = idx;
256         }
257
258         perf_counters_lapic_init(hwc->nmi);
259
260         __pmc_generic_disable(counter, hwc, idx);
261
262         cpuc->generic[idx] = counter;
263
264         __hw_perf_counter_set_period(counter, hwc, idx);
265         __pmc_generic_enable(counter, hwc, idx);
266 }
267
268 void perf_counter_print_debug(void)
269 {
270         u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left;
271         int cpu, idx;
272
273         if (!nr_hw_counters)
274                 return;
275
276         local_irq_disable();
277
278         cpu = smp_processor_id();
279
280         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
281         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
282         rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
283
284         printk(KERN_INFO "\n");
285         printk(KERN_INFO "CPU#%d: ctrl:       %016llx\n", cpu, ctrl);
286         printk(KERN_INFO "CPU#%d: status:     %016llx\n", cpu, status);
287         printk(KERN_INFO "CPU#%d: overflow:   %016llx\n", cpu, overflow);
288
289         for (idx = 0; idx < nr_hw_counters; idx++) {
290                 rdmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + idx, pmc_ctrl);
291                 rdmsrl(MSR_ARCH_PERFMON_PERFCTR0  + idx, pmc_count);
292
293                 prev_left = per_cpu(prev_left[idx], cpu);
294
295                 printk(KERN_INFO "CPU#%d: PMC%d ctrl:  %016llx\n",
296                         cpu, idx, pmc_ctrl);
297                 printk(KERN_INFO "CPU#%d: PMC%d count: %016llx\n",
298                         cpu, idx, pmc_count);
299                 printk(KERN_INFO "CPU#%d: PMC%d left:  %016llx\n",
300                         cpu, idx, prev_left);
301         }
302         local_irq_enable();
303 }
304
305 static void pmc_generic_disable(struct perf_counter *counter)
306 {
307         struct cpu_hw_counters *cpuc = &__get_cpu_var(cpu_hw_counters);
308         struct hw_perf_counter *hwc = &counter->hw;
309         unsigned int idx = hwc->idx;
310
311         __pmc_generic_disable(counter, hwc, idx);
312
313         clear_bit(idx, cpuc->used);
314         cpuc->generic[idx] = NULL;
315
316         /*
317          * Drain the remaining delta count out of a counter
318          * that we are disabling:
319          */
320         x86_perf_counter_update(counter, hwc, idx);
321 }
322
323 static void perf_store_irq_data(struct perf_counter *counter, u64 data)
324 {
325         struct perf_data *irqdata = counter->irqdata;
326
327         if (irqdata->len > PERF_DATA_BUFLEN - sizeof(u64)) {
328                 irqdata->overrun++;
329         } else {
330                 u64 *p = (u64 *) &irqdata->data[irqdata->len];
331
332                 *p = data;
333                 irqdata->len += sizeof(u64);
334         }
335 }
336
337 /*
338  * Save and restart an expired counter. Called by NMI contexts,
339  * so it has to be careful about preempting normal counter ops:
340  */
341 static void perf_save_and_restart(struct perf_counter *counter)
342 {
343         struct hw_perf_counter *hwc = &counter->hw;
344         int idx = hwc->idx;
345         u64 pmc_ctrl;
346
347         rdmsrl(MSR_ARCH_PERFMON_EVENTSEL0 + idx, pmc_ctrl);
348
349         x86_perf_counter_update(counter, hwc, idx);
350         __hw_perf_counter_set_period(counter, hwc, idx);
351
352         if (pmc_ctrl & ARCH_PERFMON_EVENTSEL0_ENABLE)
353                 __pmc_generic_enable(counter, hwc, idx);
354 }
355
356 static void
357 perf_handle_group(struct perf_counter *sibling, u64 *status, u64 *overflown)
358 {
359         struct perf_counter *counter, *group_leader = sibling->group_leader;
360
361         /*
362          * Store sibling timestamps (if any):
363          */
364         list_for_each_entry(counter, &group_leader->sibling_list, list_entry) {
365                 x86_perf_counter_update(counter, &counter->hw, counter->hw.idx);
366                 perf_store_irq_data(sibling, counter->hw_event.type);
367                 perf_store_irq_data(sibling, atomic64_read(&counter->count));
368         }
369 }
370
371 /*
372  * This handler is triggered by the local APIC, so the APIC IRQ handling
373  * rules apply:
374  */
375 static void __smp_perf_counter_interrupt(struct pt_regs *regs, int nmi)
376 {
377         int bit, cpu = smp_processor_id();
378         u64 ack, status, saved_global;
379         struct cpu_hw_counters *cpuc;
380
381         rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, saved_global);
382
383         /* Disable counters globally */
384         wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, 0, 0);
385         ack_APIC_irq();
386
387         cpuc = &per_cpu(cpu_hw_counters, cpu);
388
389         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
390         if (!status)
391                 goto out;
392
393 again:
394         ack = status;
395         for_each_bit(bit, (unsigned long *) &status, nr_hw_counters) {
396                 struct perf_counter *counter = cpuc->generic[bit];
397
398                 clear_bit(bit, (unsigned long *) &status);
399                 if (!counter)
400                         continue;
401
402                 perf_save_and_restart(counter);
403
404                 switch (counter->hw_event.record_type) {
405                 case PERF_RECORD_SIMPLE:
406                         continue;
407                 case PERF_RECORD_IRQ:
408                         perf_store_irq_data(counter, instruction_pointer(regs));
409                         break;
410                 case PERF_RECORD_GROUP:
411                         perf_handle_group(counter, &status, &ack);
412                         break;
413                 }
414                 /*
415                  * From NMI context we cannot call into the scheduler to
416                  * do a task wakeup - but we mark these generic as
417                  * wakeup_pending and initate a wakeup callback:
418                  */
419                 if (nmi) {
420                         counter->wakeup_pending = 1;
421                         set_tsk_thread_flag(current, TIF_PERF_COUNTERS);
422                 } else {
423                         wake_up(&counter->waitq);
424                 }
425         }
426
427         wrmsr(MSR_CORE_PERF_GLOBAL_OVF_CTRL, ack, 0);
428
429         /*
430          * Repeat if there is more work to be done:
431          */
432         rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
433         if (status)
434                 goto again;
435 out:
436         /*
437          * Restore - do not reenable when global enable is off:
438          */
439         wrmsr(MSR_CORE_PERF_GLOBAL_CTRL, saved_global, 0);
440 }
441
442 void smp_perf_counter_interrupt(struct pt_regs *regs)
443 {
444         irq_enter();
445         inc_irq_stat(apic_perf_irqs);
446         apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
447         __smp_perf_counter_interrupt(regs, 0);
448
449         irq_exit();
450 }
451
452 /*
453  * This handler is triggered by NMI contexts:
454  */
455 void perf_counter_notify(struct pt_regs *regs)
456 {
457         struct cpu_hw_counters *cpuc;
458         unsigned long flags;
459         int bit, cpu;
460
461         local_irq_save(flags);
462         cpu = smp_processor_id();
463         cpuc = &per_cpu(cpu_hw_counters, cpu);
464
465         for_each_bit(bit, cpuc->used, nr_hw_counters) {
466                 struct perf_counter *counter = cpuc->generic[bit];
467
468                 if (!counter)
469                         continue;
470
471                 if (counter->wakeup_pending) {
472                         counter->wakeup_pending = 0;
473                         wake_up(&counter->waitq);
474                 }
475         }
476
477         local_irq_restore(flags);
478 }
479
480 void __cpuinit perf_counters_lapic_init(int nmi)
481 {
482         u32 apic_val;
483
484         if (!perf_counters_initialized)
485                 return;
486         /*
487          * Enable the performance counter vector in the APIC LVT:
488          */
489         apic_val = apic_read(APIC_LVTERR);
490
491         apic_write(APIC_LVTERR, apic_val | APIC_LVT_MASKED);
492         if (nmi)
493                 apic_write(APIC_LVTPC, APIC_DM_NMI);
494         else
495                 apic_write(APIC_LVTPC, LOCAL_PERF_VECTOR);
496         apic_write(APIC_LVTERR, apic_val);
497 }
498
499 static int __kprobes
500 perf_counter_nmi_handler(struct notifier_block *self,
501                          unsigned long cmd, void *__args)
502 {
503         struct die_args *args = __args;
504         struct pt_regs *regs;
505
506         if (likely(cmd != DIE_NMI_IPI))
507                 return NOTIFY_DONE;
508
509         regs = args->regs;
510
511         apic_write(APIC_LVTPC, APIC_DM_NMI);
512         __smp_perf_counter_interrupt(regs, 1);
513
514         return NOTIFY_STOP;
515 }
516
517 static __read_mostly struct notifier_block perf_counter_nmi_notifier = {
518         .notifier_call          = perf_counter_nmi_handler
519 };
520
521 void __init init_hw_perf_counters(void)
522 {
523         union cpuid10_eax eax;
524         unsigned int ebx;
525         unsigned int unused;
526         union cpuid10_edx edx;
527
528         if (!cpu_has(&boot_cpu_data, X86_FEATURE_ARCH_PERFMON))
529                 return;
530
531         /*
532          * Check whether the Architectural PerfMon supports
533          * Branch Misses Retired Event or not.
534          */
535         cpuid(10, &eax.full, &ebx, &unused, &edx.full);
536         if (eax.split.mask_length <= ARCH_PERFMON_BRANCH_MISSES_RETIRED)
537                 return;
538
539         printk(KERN_INFO "Intel Performance Monitoring support detected.\n");
540
541         printk(KERN_INFO "... version:         %d\n", eax.split.version_id);
542         printk(KERN_INFO "... num counters:    %d\n", eax.split.num_counters);
543         nr_hw_counters = eax.split.num_counters;
544         if (nr_hw_counters > X86_PMC_MAX_GENERIC) {
545                 nr_hw_counters = X86_PMC_MAX_GENERIC;
546                 WARN(1, KERN_ERR "hw perf counters %d > max(%d), clipping!",
547                         nr_hw_counters, X86_PMC_MAX_GENERIC);
548         }
549         perf_counter_mask = (1 << nr_hw_counters) - 1;
550         perf_max_counters = nr_hw_counters;
551
552         printk(KERN_INFO "... bit width:       %d\n", eax.split.bit_width);
553         printk(KERN_INFO "... mask length:     %d\n", eax.split.mask_length);
554
555         nr_hw_counters_fixed = edx.split.num_counters_fixed;
556         if (nr_hw_counters_fixed > X86_PMC_MAX_FIXED) {
557                 nr_hw_counters_fixed = X86_PMC_MAX_FIXED;
558                 WARN(1, KERN_ERR "hw perf counters fixed %d > max(%d), clipping!",
559                         nr_hw_counters_fixed, X86_PMC_MAX_FIXED);
560         }
561         printk(KERN_INFO "... fixed counters:  %d\n", nr_hw_counters_fixed);
562
563         perf_counters_initialized = true;
564
565         perf_counters_lapic_init(0);
566         register_die_notifier(&perf_counter_nmi_notifier);
567 }
568
569 static void pmc_generic_read(struct perf_counter *counter)
570 {
571         x86_perf_counter_update(counter, &counter->hw, counter->hw.idx);
572 }
573
574 static const struct hw_perf_counter_ops x86_perf_counter_ops = {
575         .hw_perf_counter_enable         = pmc_generic_enable,
576         .hw_perf_counter_disable        = pmc_generic_disable,
577         .hw_perf_counter_read           = pmc_generic_read,
578 };
579
580 const struct hw_perf_counter_ops *
581 hw_perf_counter_init(struct perf_counter *counter)
582 {
583         int err;
584
585         err = __hw_perf_counter_init(counter);
586         if (err)
587                 return NULL;
588
589         return &x86_perf_counter_ops;
590 }