2 * Performance events x86 architecture code
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 * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
10 * Copyright (C) 2009 Google, Inc., Stephane Eranian
12 * For licencing details see kernel-base/COPYING
15 #include <linux/perf_event.h>
16 #include <linux/capability.h>
17 #include <linux/notifier.h>
18 #include <linux/hardirq.h>
19 #include <linux/kprobes.h>
20 #include <linux/module.h>
21 #include <linux/kdebug.h>
22 #include <linux/sched.h>
23 #include <linux/uaccess.h>
24 #include <linux/slab.h>
25 #include <linux/cpu.h>
26 #include <linux/bitops.h>
27 #include <linux/device.h>
30 #include <asm/stacktrace.h>
32 #include <asm/compat.h>
34 #include <asm/alternative.h>
36 #include "perf_event.h"
40 #define wrmsrl(msr, val) \
42 trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
43 (unsigned long)(val)); \
44 native_write_msr((msr), (u32)((u64)(val)), \
45 (u32)((u64)(val) >> 32)); \
49 struct x86_pmu x86_pmu __read_mostly;
51 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
55 u64 __read_mostly hw_cache_event_ids
56 [PERF_COUNT_HW_CACHE_MAX]
57 [PERF_COUNT_HW_CACHE_OP_MAX]
58 [PERF_COUNT_HW_CACHE_RESULT_MAX];
59 u64 __read_mostly hw_cache_extra_regs
60 [PERF_COUNT_HW_CACHE_MAX]
61 [PERF_COUNT_HW_CACHE_OP_MAX]
62 [PERF_COUNT_HW_CACHE_RESULT_MAX];
65 * Propagate event elapsed time into the generic event.
66 * Can only be executed on the CPU where the event is active.
67 * Returns the delta events processed.
69 u64 x86_perf_event_update(struct perf_event *event)
71 struct hw_perf_event *hwc = &event->hw;
72 int shift = 64 - x86_pmu.cntval_bits;
73 u64 prev_raw_count, new_raw_count;
77 if (idx == X86_PMC_IDX_FIXED_BTS)
81 * Careful: an NMI might modify the previous event value.
83 * Our tactic to handle this is to first atomically read and
84 * exchange a new raw count - then add that new-prev delta
85 * count to the generic event atomically:
88 prev_raw_count = local64_read(&hwc->prev_count);
89 rdmsrl(hwc->event_base, new_raw_count);
91 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
92 new_raw_count) != prev_raw_count)
96 * Now we have the new raw value and have updated the prev
97 * timestamp already. We can now calculate the elapsed delta
98 * (event-)time and add that to the generic event.
100 * Careful, not all hw sign-extends above the physical width
103 delta = (new_raw_count << shift) - (prev_raw_count << shift);
106 local64_add(delta, &event->count);
107 local64_sub(delta, &hwc->period_left);
109 return new_raw_count;
113 * Find and validate any extra registers to set up.
115 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
117 struct hw_perf_event_extra *reg;
118 struct extra_reg *er;
120 reg = &event->hw.extra_reg;
122 if (!x86_pmu.extra_regs)
125 for (er = x86_pmu.extra_regs; er->msr; er++) {
126 if (er->event != (config & er->config_mask))
128 if (event->attr.config1 & ~er->valid_mask)
132 reg->config = event->attr.config1;
139 static atomic_t active_events;
140 static DEFINE_MUTEX(pmc_reserve_mutex);
142 #ifdef CONFIG_X86_LOCAL_APIC
144 static bool reserve_pmc_hardware(void)
148 for (i = 0; i < x86_pmu.num_counters; i++) {
149 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
153 for (i = 0; i < x86_pmu.num_counters; i++) {
154 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
161 for (i--; i >= 0; i--)
162 release_evntsel_nmi(x86_pmu_config_addr(i));
164 i = x86_pmu.num_counters;
167 for (i--; i >= 0; i--)
168 release_perfctr_nmi(x86_pmu_event_addr(i));
173 static void release_pmc_hardware(void)
177 for (i = 0; i < x86_pmu.num_counters; i++) {
178 release_perfctr_nmi(x86_pmu_event_addr(i));
179 release_evntsel_nmi(x86_pmu_config_addr(i));
185 static bool reserve_pmc_hardware(void) { return true; }
186 static void release_pmc_hardware(void) {}
190 static bool check_hw_exists(void)
192 u64 val, val_new = 0;
196 * Check to see if the BIOS enabled any of the counters, if so
199 for (i = 0; i < x86_pmu.num_counters; i++) {
200 reg = x86_pmu_config_addr(i);
201 ret = rdmsrl_safe(reg, &val);
204 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
208 if (x86_pmu.num_counters_fixed) {
209 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
210 ret = rdmsrl_safe(reg, &val);
213 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
214 if (val & (0x03 << i*4))
220 * Now write a value and read it back to see if it matches,
221 * this is needed to detect certain hardware emulators (qemu/kvm)
222 * that don't trap on the MSR access and always return 0s.
225 ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
226 ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
227 if (ret || val != val_new)
234 * We still allow the PMU driver to operate:
236 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
237 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
242 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
247 static void hw_perf_event_destroy(struct perf_event *event)
249 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
250 release_pmc_hardware();
251 release_ds_buffers();
252 mutex_unlock(&pmc_reserve_mutex);
256 static inline int x86_pmu_initialized(void)
258 return x86_pmu.handle_irq != NULL;
262 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
264 struct perf_event_attr *attr = &event->attr;
265 unsigned int cache_type, cache_op, cache_result;
268 config = attr->config;
270 cache_type = (config >> 0) & 0xff;
271 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
274 cache_op = (config >> 8) & 0xff;
275 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
278 cache_result = (config >> 16) & 0xff;
279 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
282 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
291 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
292 return x86_pmu_extra_regs(val, event);
295 int x86_setup_perfctr(struct perf_event *event)
297 struct perf_event_attr *attr = &event->attr;
298 struct hw_perf_event *hwc = &event->hw;
301 if (!is_sampling_event(event)) {
302 hwc->sample_period = x86_pmu.max_period;
303 hwc->last_period = hwc->sample_period;
304 local64_set(&hwc->period_left, hwc->sample_period);
307 * If we have a PMU initialized but no APIC
308 * interrupts, we cannot sample hardware
309 * events (user-space has to fall back and
310 * sample via a hrtimer based software event):
316 if (attr->type == PERF_TYPE_RAW)
317 return x86_pmu_extra_regs(event->attr.config, event);
319 if (attr->type == PERF_TYPE_HW_CACHE)
320 return set_ext_hw_attr(hwc, event);
322 if (attr->config >= x86_pmu.max_events)
328 config = x86_pmu.event_map(attr->config);
339 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
340 !attr->freq && hwc->sample_period == 1) {
341 /* BTS is not supported by this architecture. */
342 if (!x86_pmu.bts_active)
345 /* BTS is currently only allowed for user-mode. */
346 if (!attr->exclude_kernel)
350 hwc->config |= config;
355 int x86_pmu_hw_config(struct perf_event *event)
357 if (event->attr.precise_ip) {
360 /* Support for constant skid */
361 if (x86_pmu.pebs_active) {
364 /* Support for IP fixup */
369 if (event->attr.precise_ip > precise)
375 * (keep 'enabled' bit clear for now)
377 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
380 * Count user and OS events unless requested not to
382 if (!event->attr.exclude_user)
383 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
384 if (!event->attr.exclude_kernel)
385 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
387 if (event->attr.type == PERF_TYPE_RAW)
388 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
390 return x86_setup_perfctr(event);
394 * Setup the hardware configuration for a given attr_type
396 static int __x86_pmu_event_init(struct perf_event *event)
400 if (!x86_pmu_initialized())
404 if (!atomic_inc_not_zero(&active_events)) {
405 mutex_lock(&pmc_reserve_mutex);
406 if (atomic_read(&active_events) == 0) {
407 if (!reserve_pmc_hardware())
410 reserve_ds_buffers();
413 atomic_inc(&active_events);
414 mutex_unlock(&pmc_reserve_mutex);
419 event->destroy = hw_perf_event_destroy;
422 event->hw.last_cpu = -1;
423 event->hw.last_tag = ~0ULL;
426 event->hw.extra_reg.idx = EXTRA_REG_NONE;
428 return x86_pmu.hw_config(event);
431 void x86_pmu_disable_all(void)
433 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
436 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
439 if (!test_bit(idx, cpuc->active_mask))
441 rdmsrl(x86_pmu_config_addr(idx), val);
442 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
444 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
445 wrmsrl(x86_pmu_config_addr(idx), val);
449 static void x86_pmu_disable(struct pmu *pmu)
451 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
453 if (!x86_pmu_initialized())
463 x86_pmu.disable_all();
466 void x86_pmu_enable_all(int added)
468 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
471 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
472 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
474 if (!test_bit(idx, cpuc->active_mask))
477 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
481 static struct pmu pmu;
483 static inline int is_x86_event(struct perf_event *event)
485 return event->pmu == &pmu;
489 * Event scheduler state:
491 * Assign events iterating over all events and counters, beginning
492 * with events with least weights first. Keep the current iterator
493 * state in struct sched_state.
497 int event; /* event index */
498 int counter; /* counter index */
499 int unassigned; /* number of events to be assigned left */
500 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
503 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
504 #define SCHED_STATES_MAX 2
509 struct event_constraint **constraints;
510 struct sched_state state;
512 struct sched_state saved[SCHED_STATES_MAX];
516 * Initialize interator that runs through all events and counters.
518 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **c,
519 int num, int wmin, int wmax)
523 memset(sched, 0, sizeof(*sched));
524 sched->max_events = num;
525 sched->max_weight = wmax;
526 sched->constraints = c;
528 for (idx = 0; idx < num; idx++) {
529 if (c[idx]->weight == wmin)
533 sched->state.event = idx; /* start with min weight */
534 sched->state.weight = wmin;
535 sched->state.unassigned = num;
538 static void perf_sched_save_state(struct perf_sched *sched)
540 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
543 sched->saved[sched->saved_states] = sched->state;
544 sched->saved_states++;
547 static bool perf_sched_restore_state(struct perf_sched *sched)
549 if (!sched->saved_states)
552 sched->saved_states--;
553 sched->state = sched->saved[sched->saved_states];
555 /* continue with next counter: */
556 clear_bit(sched->state.counter++, sched->state.used);
562 * Select a counter for the current event to schedule. Return true on
565 static bool __perf_sched_find_counter(struct perf_sched *sched)
567 struct event_constraint *c;
570 if (!sched->state.unassigned)
573 if (sched->state.event >= sched->max_events)
576 c = sched->constraints[sched->state.event];
578 /* Prefer fixed purpose counters */
579 if (x86_pmu.num_counters_fixed) {
580 idx = X86_PMC_IDX_FIXED;
581 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_MAX) {
582 if (!__test_and_set_bit(idx, sched->state.used))
586 /* Grab the first unused counter starting with idx */
587 idx = sched->state.counter;
588 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_FIXED) {
589 if (!__test_and_set_bit(idx, sched->state.used))
596 sched->state.counter = idx;
599 perf_sched_save_state(sched);
604 static bool perf_sched_find_counter(struct perf_sched *sched)
606 while (!__perf_sched_find_counter(sched)) {
607 if (!perf_sched_restore_state(sched))
615 * Go through all unassigned events and find the next one to schedule.
616 * Take events with the least weight first. Return true on success.
618 static bool perf_sched_next_event(struct perf_sched *sched)
620 struct event_constraint *c;
622 if (!sched->state.unassigned || !--sched->state.unassigned)
627 sched->state.event++;
628 if (sched->state.event >= sched->max_events) {
630 sched->state.event = 0;
631 sched->state.weight++;
632 if (sched->state.weight > sched->max_weight)
635 c = sched->constraints[sched->state.event];
636 } while (c->weight != sched->state.weight);
638 sched->state.counter = 0; /* start with first counter */
644 * Assign a counter for each event.
646 static int perf_assign_events(struct event_constraint **constraints, int n,
647 int wmin, int wmax, int *assign)
649 struct perf_sched sched;
651 perf_sched_init(&sched, constraints, n, wmin, wmax);
654 if (!perf_sched_find_counter(&sched))
657 assign[sched.state.event] = sched.state.counter;
658 } while (perf_sched_next_event(&sched));
660 return sched.state.unassigned;
663 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
665 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
666 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
667 int i, wmin, wmax, num = 0;
668 struct hw_perf_event *hwc;
670 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
672 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
673 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
675 wmin = min(wmin, c->weight);
676 wmax = max(wmax, c->weight);
680 * fastpath, try to reuse previous register
682 for (i = 0; i < n; i++) {
683 hwc = &cpuc->event_list[i]->hw;
690 /* constraint still honored */
691 if (!test_bit(hwc->idx, c->idxmsk))
694 /* not already used */
695 if (test_bit(hwc->idx, used_mask))
698 __set_bit(hwc->idx, used_mask);
700 assign[i] = hwc->idx;
705 num = perf_assign_events(constraints, n, wmin, wmax, assign);
708 * scheduling failed or is just a simulation,
709 * free resources if necessary
711 if (!assign || num) {
712 for (i = 0; i < n; i++) {
713 if (x86_pmu.put_event_constraints)
714 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
717 return num ? -EINVAL : 0;
721 * dogrp: true if must collect siblings events (group)
722 * returns total number of events and error code
724 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
726 struct perf_event *event;
729 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
731 /* current number of events already accepted */
734 if (is_x86_event(leader)) {
737 cpuc->event_list[n] = leader;
743 list_for_each_entry(event, &leader->sibling_list, group_entry) {
744 if (!is_x86_event(event) ||
745 event->state <= PERF_EVENT_STATE_OFF)
751 cpuc->event_list[n] = event;
757 static inline void x86_assign_hw_event(struct perf_event *event,
758 struct cpu_hw_events *cpuc, int i)
760 struct hw_perf_event *hwc = &event->hw;
762 hwc->idx = cpuc->assign[i];
763 hwc->last_cpu = smp_processor_id();
764 hwc->last_tag = ++cpuc->tags[i];
766 if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
767 hwc->config_base = 0;
769 } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
770 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
771 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
773 hwc->config_base = x86_pmu_config_addr(hwc->idx);
774 hwc->event_base = x86_pmu_event_addr(hwc->idx);
778 static inline int match_prev_assignment(struct hw_perf_event *hwc,
779 struct cpu_hw_events *cpuc,
782 return hwc->idx == cpuc->assign[i] &&
783 hwc->last_cpu == smp_processor_id() &&
784 hwc->last_tag == cpuc->tags[i];
787 static void x86_pmu_start(struct perf_event *event, int flags);
789 static void x86_pmu_enable(struct pmu *pmu)
791 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
792 struct perf_event *event;
793 struct hw_perf_event *hwc;
794 int i, added = cpuc->n_added;
796 if (!x86_pmu_initialized())
803 int n_running = cpuc->n_events - cpuc->n_added;
805 * apply assignment obtained either from
806 * hw_perf_group_sched_in() or x86_pmu_enable()
808 * step1: save events moving to new counters
809 * step2: reprogram moved events into new counters
811 for (i = 0; i < n_running; i++) {
812 event = cpuc->event_list[i];
816 * we can avoid reprogramming counter if:
817 * - assigned same counter as last time
818 * - running on same CPU as last time
819 * - no other event has used the counter since
821 if (hwc->idx == -1 ||
822 match_prev_assignment(hwc, cpuc, i))
826 * Ensure we don't accidentally enable a stopped
827 * counter simply because we rescheduled.
829 if (hwc->state & PERF_HES_STOPPED)
830 hwc->state |= PERF_HES_ARCH;
832 x86_pmu_stop(event, PERF_EF_UPDATE);
835 for (i = 0; i < cpuc->n_events; i++) {
836 event = cpuc->event_list[i];
839 if (!match_prev_assignment(hwc, cpuc, i))
840 x86_assign_hw_event(event, cpuc, i);
841 else if (i < n_running)
844 if (hwc->state & PERF_HES_ARCH)
847 x86_pmu_start(event, PERF_EF_RELOAD);
850 perf_events_lapic_init();
856 x86_pmu.enable_all(added);
859 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
862 * Set the next IRQ period, based on the hwc->period_left value.
863 * To be called with the event disabled in hw:
865 int x86_perf_event_set_period(struct perf_event *event)
867 struct hw_perf_event *hwc = &event->hw;
868 s64 left = local64_read(&hwc->period_left);
869 s64 period = hwc->sample_period;
870 int ret = 0, idx = hwc->idx;
872 if (idx == X86_PMC_IDX_FIXED_BTS)
876 * If we are way outside a reasonable range then just skip forward:
878 if (unlikely(left <= -period)) {
880 local64_set(&hwc->period_left, left);
881 hwc->last_period = period;
885 if (unlikely(left <= 0)) {
887 local64_set(&hwc->period_left, left);
888 hwc->last_period = period;
892 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
894 if (unlikely(left < 2))
897 if (left > x86_pmu.max_period)
898 left = x86_pmu.max_period;
900 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
903 * The hw event starts counting from this event offset,
904 * mark it to be able to extra future deltas:
906 local64_set(&hwc->prev_count, (u64)-left);
908 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
911 * Due to erratum on certan cpu we need
912 * a second write to be sure the register
913 * is updated properly
915 if (x86_pmu.perfctr_second_write) {
916 wrmsrl(hwc->event_base,
917 (u64)(-left) & x86_pmu.cntval_mask);
920 perf_event_update_userpage(event);
925 void x86_pmu_enable_event(struct perf_event *event)
927 if (__this_cpu_read(cpu_hw_events.enabled))
928 __x86_pmu_enable_event(&event->hw,
929 ARCH_PERFMON_EVENTSEL_ENABLE);
933 * Add a single event to the PMU.
935 * The event is added to the group of enabled events
936 * but only if it can be scehduled with existing events.
938 static int x86_pmu_add(struct perf_event *event, int flags)
940 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
941 struct hw_perf_event *hwc;
942 int assign[X86_PMC_IDX_MAX];
947 perf_pmu_disable(event->pmu);
949 ret = n = collect_events(cpuc, event, false);
953 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
954 if (!(flags & PERF_EF_START))
955 hwc->state |= PERF_HES_ARCH;
958 * If group events scheduling transaction was started,
959 * skip the schedulability test here, it will be performed
960 * at commit time (->commit_txn) as a whole
962 if (cpuc->group_flag & PERF_EVENT_TXN)
965 ret = x86_pmu.schedule_events(cpuc, n, assign);
969 * copy new assignment, now we know it is possible
970 * will be used by hw_perf_enable()
972 memcpy(cpuc->assign, assign, n*sizeof(int));
976 cpuc->n_added += n - n0;
977 cpuc->n_txn += n - n0;
981 perf_pmu_enable(event->pmu);
985 static void x86_pmu_start(struct perf_event *event, int flags)
987 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
988 int idx = event->hw.idx;
990 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
993 if (WARN_ON_ONCE(idx == -1))
996 if (flags & PERF_EF_RELOAD) {
997 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
998 x86_perf_event_set_period(event);
1001 event->hw.state = 0;
1003 cpuc->events[idx] = event;
1004 __set_bit(idx, cpuc->active_mask);
1005 __set_bit(idx, cpuc->running);
1006 x86_pmu.enable(event);
1007 perf_event_update_userpage(event);
1010 void perf_event_print_debug(void)
1012 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1014 struct cpu_hw_events *cpuc;
1015 unsigned long flags;
1018 if (!x86_pmu.num_counters)
1021 local_irq_save(flags);
1023 cpu = smp_processor_id();
1024 cpuc = &per_cpu(cpu_hw_events, cpu);
1026 if (x86_pmu.version >= 2) {
1027 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1028 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1029 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1030 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1031 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1034 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1035 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1036 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1037 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1038 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1040 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1042 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1043 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1044 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1046 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1048 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1049 cpu, idx, pmc_ctrl);
1050 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1051 cpu, idx, pmc_count);
1052 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1053 cpu, idx, prev_left);
1055 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1056 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1058 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1059 cpu, idx, pmc_count);
1061 local_irq_restore(flags);
1064 void x86_pmu_stop(struct perf_event *event, int flags)
1066 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1067 struct hw_perf_event *hwc = &event->hw;
1069 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1070 x86_pmu.disable(event);
1071 cpuc->events[hwc->idx] = NULL;
1072 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1073 hwc->state |= PERF_HES_STOPPED;
1076 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1078 * Drain the remaining delta count out of a event
1079 * that we are disabling:
1081 x86_perf_event_update(event);
1082 hwc->state |= PERF_HES_UPTODATE;
1086 static void x86_pmu_del(struct perf_event *event, int flags)
1088 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1092 * If we're called during a txn, we don't need to do anything.
1093 * The events never got scheduled and ->cancel_txn will truncate
1096 if (cpuc->group_flag & PERF_EVENT_TXN)
1099 x86_pmu_stop(event, PERF_EF_UPDATE);
1101 for (i = 0; i < cpuc->n_events; i++) {
1102 if (event == cpuc->event_list[i]) {
1104 if (x86_pmu.put_event_constraints)
1105 x86_pmu.put_event_constraints(cpuc, event);
1107 while (++i < cpuc->n_events)
1108 cpuc->event_list[i-1] = cpuc->event_list[i];
1114 perf_event_update_userpage(event);
1117 int x86_pmu_handle_irq(struct pt_regs *regs)
1119 struct perf_sample_data data;
1120 struct cpu_hw_events *cpuc;
1121 struct perf_event *event;
1122 int idx, handled = 0;
1125 perf_sample_data_init(&data, 0);
1127 cpuc = &__get_cpu_var(cpu_hw_events);
1130 * Some chipsets need to unmask the LVTPC in a particular spot
1131 * inside the nmi handler. As a result, the unmasking was pushed
1132 * into all the nmi handlers.
1134 * This generic handler doesn't seem to have any issues where the
1135 * unmasking occurs so it was left at the top.
1137 apic_write(APIC_LVTPC, APIC_DM_NMI);
1139 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1140 if (!test_bit(idx, cpuc->active_mask)) {
1142 * Though we deactivated the counter some cpus
1143 * might still deliver spurious interrupts still
1144 * in flight. Catch them:
1146 if (__test_and_clear_bit(idx, cpuc->running))
1151 event = cpuc->events[idx];
1153 val = x86_perf_event_update(event);
1154 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1161 data.period = event->hw.last_period;
1163 if (!x86_perf_event_set_period(event))
1166 if (perf_event_overflow(event, &data, regs))
1167 x86_pmu_stop(event, 0);
1171 inc_irq_stat(apic_perf_irqs);
1176 void perf_events_lapic_init(void)
1178 if (!x86_pmu.apic || !x86_pmu_initialized())
1182 * Always use NMI for PMU
1184 apic_write(APIC_LVTPC, APIC_DM_NMI);
1187 static int __kprobes
1188 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1190 if (!atomic_read(&active_events))
1193 return x86_pmu.handle_irq(regs);
1196 struct event_constraint emptyconstraint;
1197 struct event_constraint unconstrained;
1199 static int __cpuinit
1200 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1202 unsigned int cpu = (long)hcpu;
1203 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1204 int ret = NOTIFY_OK;
1206 switch (action & ~CPU_TASKS_FROZEN) {
1207 case CPU_UP_PREPARE:
1208 cpuc->kfree_on_online = NULL;
1209 if (x86_pmu.cpu_prepare)
1210 ret = x86_pmu.cpu_prepare(cpu);
1214 if (x86_pmu.attr_rdpmc)
1215 set_in_cr4(X86_CR4_PCE);
1216 if (x86_pmu.cpu_starting)
1217 x86_pmu.cpu_starting(cpu);
1221 kfree(cpuc->kfree_on_online);
1225 if (x86_pmu.cpu_dying)
1226 x86_pmu.cpu_dying(cpu);
1229 case CPU_UP_CANCELED:
1231 if (x86_pmu.cpu_dead)
1232 x86_pmu.cpu_dead(cpu);
1242 static void __init pmu_check_apic(void)
1248 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1249 pr_info("no hardware sampling interrupt available.\n");
1252 static int __init init_hw_perf_events(void)
1254 struct x86_pmu_quirk *quirk;
1255 struct event_constraint *c;
1258 pr_info("Performance Events: ");
1260 switch (boot_cpu_data.x86_vendor) {
1261 case X86_VENDOR_INTEL:
1262 err = intel_pmu_init();
1264 case X86_VENDOR_AMD:
1265 err = amd_pmu_init();
1271 pr_cont("no PMU driver, software events only.\n");
1277 /* sanity check that the hardware exists or is emulated */
1278 if (!check_hw_exists())
1281 pr_cont("%s PMU driver.\n", x86_pmu.name);
1283 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1286 if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1287 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1288 x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1289 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1291 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1293 if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1294 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1295 x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1296 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1299 x86_pmu.intel_ctrl |=
1300 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1302 perf_events_lapic_init();
1303 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1305 unconstrained = (struct event_constraint)
1306 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1307 0, x86_pmu.num_counters, 0);
1309 if (x86_pmu.event_constraints) {
1311 * event on fixed counter2 (REF_CYCLES) only works on this
1312 * counter, so do not extend mask to generic counters
1314 for_each_event_constraint(c, x86_pmu.event_constraints) {
1315 if (c->cmask != X86_RAW_EVENT_MASK
1316 || c->idxmsk64 == X86_PMC_MSK_FIXED_REF_CYCLES) {
1320 c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1321 c->weight += x86_pmu.num_counters;
1325 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1327 pr_info("... version: %d\n", x86_pmu.version);
1328 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1329 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1330 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1331 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1332 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1333 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1335 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1336 perf_cpu_notifier(x86_pmu_notifier);
1340 early_initcall(init_hw_perf_events);
1342 static inline void x86_pmu_read(struct perf_event *event)
1344 x86_perf_event_update(event);
1348 * Start group events scheduling transaction
1349 * Set the flag to make pmu::enable() not perform the
1350 * schedulability test, it will be performed at commit time
1352 static void x86_pmu_start_txn(struct pmu *pmu)
1354 perf_pmu_disable(pmu);
1355 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1356 __this_cpu_write(cpu_hw_events.n_txn, 0);
1360 * Stop group events scheduling transaction
1361 * Clear the flag and pmu::enable() will perform the
1362 * schedulability test.
1364 static void x86_pmu_cancel_txn(struct pmu *pmu)
1366 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1368 * Truncate the collected events.
1370 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1371 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1372 perf_pmu_enable(pmu);
1376 * Commit group events scheduling transaction
1377 * Perform the group schedulability test as a whole
1378 * Return 0 if success
1380 static int x86_pmu_commit_txn(struct pmu *pmu)
1382 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1383 int assign[X86_PMC_IDX_MAX];
1388 if (!x86_pmu_initialized())
1391 ret = x86_pmu.schedule_events(cpuc, n, assign);
1396 * copy new assignment, now we know it is possible
1397 * will be used by hw_perf_enable()
1399 memcpy(cpuc->assign, assign, n*sizeof(int));
1401 cpuc->group_flag &= ~PERF_EVENT_TXN;
1402 perf_pmu_enable(pmu);
1406 * a fake_cpuc is used to validate event groups. Due to
1407 * the extra reg logic, we need to also allocate a fake
1408 * per_core and per_cpu structure. Otherwise, group events
1409 * using extra reg may conflict without the kernel being
1410 * able to catch this when the last event gets added to
1413 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1415 kfree(cpuc->shared_regs);
1419 static struct cpu_hw_events *allocate_fake_cpuc(void)
1421 struct cpu_hw_events *cpuc;
1422 int cpu = raw_smp_processor_id();
1424 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1426 return ERR_PTR(-ENOMEM);
1428 /* only needed, if we have extra_regs */
1429 if (x86_pmu.extra_regs) {
1430 cpuc->shared_regs = allocate_shared_regs(cpu);
1431 if (!cpuc->shared_regs)
1436 free_fake_cpuc(cpuc);
1437 return ERR_PTR(-ENOMEM);
1441 * validate that we can schedule this event
1443 static int validate_event(struct perf_event *event)
1445 struct cpu_hw_events *fake_cpuc;
1446 struct event_constraint *c;
1449 fake_cpuc = allocate_fake_cpuc();
1450 if (IS_ERR(fake_cpuc))
1451 return PTR_ERR(fake_cpuc);
1453 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1455 if (!c || !c->weight)
1458 if (x86_pmu.put_event_constraints)
1459 x86_pmu.put_event_constraints(fake_cpuc, event);
1461 free_fake_cpuc(fake_cpuc);
1467 * validate a single event group
1469 * validation include:
1470 * - check events are compatible which each other
1471 * - events do not compete for the same counter
1472 * - number of events <= number of counters
1474 * validation ensures the group can be loaded onto the
1475 * PMU if it was the only group available.
1477 static int validate_group(struct perf_event *event)
1479 struct perf_event *leader = event->group_leader;
1480 struct cpu_hw_events *fake_cpuc;
1481 int ret = -EINVAL, n;
1483 fake_cpuc = allocate_fake_cpuc();
1484 if (IS_ERR(fake_cpuc))
1485 return PTR_ERR(fake_cpuc);
1487 * the event is not yet connected with its
1488 * siblings therefore we must first collect
1489 * existing siblings, then add the new event
1490 * before we can simulate the scheduling
1492 n = collect_events(fake_cpuc, leader, true);
1496 fake_cpuc->n_events = n;
1497 n = collect_events(fake_cpuc, event, false);
1501 fake_cpuc->n_events = n;
1503 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1506 free_fake_cpuc(fake_cpuc);
1510 static int x86_pmu_event_init(struct perf_event *event)
1515 switch (event->attr.type) {
1517 case PERF_TYPE_HARDWARE:
1518 case PERF_TYPE_HW_CACHE:
1525 err = __x86_pmu_event_init(event);
1528 * we temporarily connect event to its pmu
1529 * such that validate_group() can classify
1530 * it as an x86 event using is_x86_event()
1535 if (event->group_leader != event)
1536 err = validate_group(event);
1538 err = validate_event(event);
1544 event->destroy(event);
1550 static int x86_pmu_event_idx(struct perf_event *event)
1552 int idx = event->hw.idx;
1554 if (x86_pmu.num_counters_fixed && idx >= X86_PMC_IDX_FIXED) {
1555 idx -= X86_PMC_IDX_FIXED;
1562 static ssize_t get_attr_rdpmc(struct device *cdev,
1563 struct device_attribute *attr,
1566 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1569 static void change_rdpmc(void *info)
1571 bool enable = !!(unsigned long)info;
1574 set_in_cr4(X86_CR4_PCE);
1576 clear_in_cr4(X86_CR4_PCE);
1579 static ssize_t set_attr_rdpmc(struct device *cdev,
1580 struct device_attribute *attr,
1581 const char *buf, size_t count)
1583 unsigned long val = simple_strtoul(buf, NULL, 0);
1585 if (!!val != !!x86_pmu.attr_rdpmc) {
1586 x86_pmu.attr_rdpmc = !!val;
1587 smp_call_function(change_rdpmc, (void *)val, 1);
1593 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
1595 static struct attribute *x86_pmu_attrs[] = {
1596 &dev_attr_rdpmc.attr,
1600 static struct attribute_group x86_pmu_attr_group = {
1601 .attrs = x86_pmu_attrs,
1604 static const struct attribute_group *x86_pmu_attr_groups[] = {
1605 &x86_pmu_attr_group,
1609 static struct pmu pmu = {
1610 .pmu_enable = x86_pmu_enable,
1611 .pmu_disable = x86_pmu_disable,
1613 .attr_groups = x86_pmu_attr_groups,
1615 .event_init = x86_pmu_event_init,
1619 .start = x86_pmu_start,
1620 .stop = x86_pmu_stop,
1621 .read = x86_pmu_read,
1623 .start_txn = x86_pmu_start_txn,
1624 .cancel_txn = x86_pmu_cancel_txn,
1625 .commit_txn = x86_pmu_commit_txn,
1627 .event_idx = x86_pmu_event_idx,
1634 static int backtrace_stack(void *data, char *name)
1639 static void backtrace_address(void *data, unsigned long addr, int reliable)
1641 struct perf_callchain_entry *entry = data;
1643 perf_callchain_store(entry, addr);
1646 static const struct stacktrace_ops backtrace_ops = {
1647 .stack = backtrace_stack,
1648 .address = backtrace_address,
1649 .walk_stack = print_context_stack_bp,
1653 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1655 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1656 /* TODO: We don't support guest os callchain now */
1660 perf_callchain_store(entry, regs->ip);
1662 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1665 #ifdef CONFIG_COMPAT
1667 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1669 /* 32-bit process in 64-bit kernel. */
1670 struct stack_frame_ia32 frame;
1671 const void __user *fp;
1673 if (!test_thread_flag(TIF_IA32))
1676 fp = compat_ptr(regs->bp);
1677 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1678 unsigned long bytes;
1679 frame.next_frame = 0;
1680 frame.return_address = 0;
1682 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1683 if (bytes != sizeof(frame))
1686 if (fp < compat_ptr(regs->sp))
1689 perf_callchain_store(entry, frame.return_address);
1690 fp = compat_ptr(frame.next_frame);
1696 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1703 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1705 struct stack_frame frame;
1706 const void __user *fp;
1708 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1709 /* TODO: We don't support guest os callchain now */
1713 fp = (void __user *)regs->bp;
1715 perf_callchain_store(entry, regs->ip);
1720 if (perf_callchain_user32(regs, entry))
1723 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1724 unsigned long bytes;
1725 frame.next_frame = NULL;
1726 frame.return_address = 0;
1728 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1729 if (bytes != sizeof(frame))
1732 if ((unsigned long)fp < regs->sp)
1735 perf_callchain_store(entry, frame.return_address);
1736 fp = frame.next_frame;
1740 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1744 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1745 ip = perf_guest_cbs->get_guest_ip();
1747 ip = instruction_pointer(regs);
1752 unsigned long perf_misc_flags(struct pt_regs *regs)
1756 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1757 if (perf_guest_cbs->is_user_mode())
1758 misc |= PERF_RECORD_MISC_GUEST_USER;
1760 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1762 if (user_mode(regs))
1763 misc |= PERF_RECORD_MISC_USER;
1765 misc |= PERF_RECORD_MISC_KERNEL;
1768 if (regs->flags & PERF_EFLAGS_EXACT)
1769 misc |= PERF_RECORD_MISC_EXACT_IP;
1774 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
1776 cap->version = x86_pmu.version;
1777 cap->num_counters_gp = x86_pmu.num_counters;
1778 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
1779 cap->bit_width_gp = x86_pmu.cntval_bits;
1780 cap->bit_width_fixed = x86_pmu.cntval_bits;
1781 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
1782 cap->events_mask_len = x86_pmu.events_mask_len;
1784 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);