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>
35 #include <asm/timer.h>
37 #include "perf_event.h"
41 #define wrmsrl(msr, val) \
43 trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
44 (unsigned long)(val)); \
45 native_write_msr((msr), (u32)((u64)(val)), \
46 (u32)((u64)(val) >> 32)); \
50 struct x86_pmu x86_pmu __read_mostly;
52 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
56 u64 __read_mostly hw_cache_event_ids
57 [PERF_COUNT_HW_CACHE_MAX]
58 [PERF_COUNT_HW_CACHE_OP_MAX]
59 [PERF_COUNT_HW_CACHE_RESULT_MAX];
60 u64 __read_mostly hw_cache_extra_regs
61 [PERF_COUNT_HW_CACHE_MAX]
62 [PERF_COUNT_HW_CACHE_OP_MAX]
63 [PERF_COUNT_HW_CACHE_RESULT_MAX];
66 * Propagate event elapsed time into the generic event.
67 * Can only be executed on the CPU where the event is active.
68 * Returns the delta events processed.
70 u64 x86_perf_event_update(struct perf_event *event)
72 struct hw_perf_event *hwc = &event->hw;
73 int shift = 64 - x86_pmu.cntval_bits;
74 u64 prev_raw_count, new_raw_count;
78 if (idx == X86_PMC_IDX_FIXED_BTS)
82 * Careful: an NMI might modify the previous event value.
84 * Our tactic to handle this is to first atomically read and
85 * exchange a new raw count - then add that new-prev delta
86 * count to the generic event atomically:
89 prev_raw_count = local64_read(&hwc->prev_count);
90 rdmsrl(hwc->event_base, new_raw_count);
92 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
93 new_raw_count) != prev_raw_count)
97 * Now we have the new raw value and have updated the prev
98 * timestamp already. We can now calculate the elapsed delta
99 * (event-)time and add that to the generic event.
101 * Careful, not all hw sign-extends above the physical width
104 delta = (new_raw_count << shift) - (prev_raw_count << shift);
107 local64_add(delta, &event->count);
108 local64_sub(delta, &hwc->period_left);
110 return new_raw_count;
114 * Find and validate any extra registers to set up.
116 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
118 struct hw_perf_event_extra *reg;
119 struct extra_reg *er;
121 reg = &event->hw.extra_reg;
123 if (!x86_pmu.extra_regs)
126 for (er = x86_pmu.extra_regs; er->msr; er++) {
127 if (er->event != (config & er->config_mask))
129 if (event->attr.config1 & ~er->valid_mask)
133 reg->config = event->attr.config1;
140 static atomic_t active_events;
141 static DEFINE_MUTEX(pmc_reserve_mutex);
143 #ifdef CONFIG_X86_LOCAL_APIC
145 static bool reserve_pmc_hardware(void)
149 for (i = 0; i < x86_pmu.num_counters; i++) {
150 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
154 for (i = 0; i < x86_pmu.num_counters; i++) {
155 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
162 for (i--; i >= 0; i--)
163 release_evntsel_nmi(x86_pmu_config_addr(i));
165 i = x86_pmu.num_counters;
168 for (i--; i >= 0; i--)
169 release_perfctr_nmi(x86_pmu_event_addr(i));
174 static void release_pmc_hardware(void)
178 for (i = 0; i < x86_pmu.num_counters; i++) {
179 release_perfctr_nmi(x86_pmu_event_addr(i));
180 release_evntsel_nmi(x86_pmu_config_addr(i));
186 static bool reserve_pmc_hardware(void) { return true; }
187 static void release_pmc_hardware(void) {}
191 static bool check_hw_exists(void)
193 u64 val, val_new = 0;
197 * Check to see if the BIOS enabled any of the counters, if so
200 for (i = 0; i < x86_pmu.num_counters; i++) {
201 reg = x86_pmu_config_addr(i);
202 ret = rdmsrl_safe(reg, &val);
205 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
209 if (x86_pmu.num_counters_fixed) {
210 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
211 ret = rdmsrl_safe(reg, &val);
214 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
215 if (val & (0x03 << i*4))
221 * Now write a value and read it back to see if it matches,
222 * this is needed to detect certain hardware emulators (qemu/kvm)
223 * that don't trap on the MSR access and always return 0s.
226 ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
227 ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
228 if (ret || val != val_new)
235 * We still allow the PMU driver to operate:
237 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
238 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
243 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
248 static void hw_perf_event_destroy(struct perf_event *event)
250 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
251 release_pmc_hardware();
252 release_ds_buffers();
253 mutex_unlock(&pmc_reserve_mutex);
257 static inline int x86_pmu_initialized(void)
259 return x86_pmu.handle_irq != NULL;
263 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
265 struct perf_event_attr *attr = &event->attr;
266 unsigned int cache_type, cache_op, cache_result;
269 config = attr->config;
271 cache_type = (config >> 0) & 0xff;
272 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
275 cache_op = (config >> 8) & 0xff;
276 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
279 cache_result = (config >> 16) & 0xff;
280 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
283 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
292 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
293 return x86_pmu_extra_regs(val, event);
296 int x86_setup_perfctr(struct perf_event *event)
298 struct perf_event_attr *attr = &event->attr;
299 struct hw_perf_event *hwc = &event->hw;
302 if (!is_sampling_event(event)) {
303 hwc->sample_period = x86_pmu.max_period;
304 hwc->last_period = hwc->sample_period;
305 local64_set(&hwc->period_left, hwc->sample_period);
308 * If we have a PMU initialized but no APIC
309 * interrupts, we cannot sample hardware
310 * events (user-space has to fall back and
311 * sample via a hrtimer based software event):
317 if (attr->type == PERF_TYPE_RAW)
318 return x86_pmu_extra_regs(event->attr.config, event);
320 if (attr->type == PERF_TYPE_HW_CACHE)
321 return set_ext_hw_attr(hwc, event);
323 if (attr->config >= x86_pmu.max_events)
329 config = x86_pmu.event_map(attr->config);
340 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
341 !attr->freq && hwc->sample_period == 1) {
342 /* BTS is not supported by this architecture. */
343 if (!x86_pmu.bts_active)
346 /* BTS is currently only allowed for user-mode. */
347 if (!attr->exclude_kernel)
351 hwc->config |= config;
356 int x86_pmu_hw_config(struct perf_event *event)
358 if (event->attr.precise_ip) {
361 /* Support for constant skid */
362 if (x86_pmu.pebs_active) {
365 /* Support for IP fixup */
370 if (event->attr.precise_ip > precise)
376 * (keep 'enabled' bit clear for now)
378 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
381 * Count user and OS events unless requested not to
383 if (!event->attr.exclude_user)
384 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
385 if (!event->attr.exclude_kernel)
386 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
388 if (event->attr.type == PERF_TYPE_RAW)
389 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
391 return x86_setup_perfctr(event);
395 * Setup the hardware configuration for a given attr_type
397 static int __x86_pmu_event_init(struct perf_event *event)
401 if (!x86_pmu_initialized())
405 if (!atomic_inc_not_zero(&active_events)) {
406 mutex_lock(&pmc_reserve_mutex);
407 if (atomic_read(&active_events) == 0) {
408 if (!reserve_pmc_hardware())
411 reserve_ds_buffers();
414 atomic_inc(&active_events);
415 mutex_unlock(&pmc_reserve_mutex);
420 event->destroy = hw_perf_event_destroy;
423 event->hw.last_cpu = -1;
424 event->hw.last_tag = ~0ULL;
427 event->hw.extra_reg.idx = EXTRA_REG_NONE;
429 return x86_pmu.hw_config(event);
432 void x86_pmu_disable_all(void)
434 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
437 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
440 if (!test_bit(idx, cpuc->active_mask))
442 rdmsrl(x86_pmu_config_addr(idx), val);
443 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
445 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
446 wrmsrl(x86_pmu_config_addr(idx), val);
450 static void x86_pmu_disable(struct pmu *pmu)
452 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
454 if (!x86_pmu_initialized())
464 x86_pmu.disable_all();
467 void x86_pmu_enable_all(int added)
469 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
472 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
473 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
475 if (!test_bit(idx, cpuc->active_mask))
478 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
482 static struct pmu pmu;
484 static inline int is_x86_event(struct perf_event *event)
486 return event->pmu == &pmu;
490 * Event scheduler state:
492 * Assign events iterating over all events and counters, beginning
493 * with events with least weights first. Keep the current iterator
494 * state in struct sched_state.
498 int event; /* event index */
499 int counter; /* counter index */
500 int unassigned; /* number of events to be assigned left */
501 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
504 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
505 #define SCHED_STATES_MAX 2
510 struct event_constraint **constraints;
511 struct sched_state state;
513 struct sched_state saved[SCHED_STATES_MAX];
517 * Initialize interator that runs through all events and counters.
519 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **c,
520 int num, int wmin, int wmax)
524 memset(sched, 0, sizeof(*sched));
525 sched->max_events = num;
526 sched->max_weight = wmax;
527 sched->constraints = c;
529 for (idx = 0; idx < num; idx++) {
530 if (c[idx]->weight == wmin)
534 sched->state.event = idx; /* start with min weight */
535 sched->state.weight = wmin;
536 sched->state.unassigned = num;
539 static void perf_sched_save_state(struct perf_sched *sched)
541 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
544 sched->saved[sched->saved_states] = sched->state;
545 sched->saved_states++;
548 static bool perf_sched_restore_state(struct perf_sched *sched)
550 if (!sched->saved_states)
553 sched->saved_states--;
554 sched->state = sched->saved[sched->saved_states];
556 /* continue with next counter: */
557 clear_bit(sched->state.counter++, sched->state.used);
563 * Select a counter for the current event to schedule. Return true on
566 static bool __perf_sched_find_counter(struct perf_sched *sched)
568 struct event_constraint *c;
571 if (!sched->state.unassigned)
574 if (sched->state.event >= sched->max_events)
577 c = sched->constraints[sched->state.event];
579 /* Prefer fixed purpose counters */
580 if (x86_pmu.num_counters_fixed) {
581 idx = X86_PMC_IDX_FIXED;
582 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_MAX) {
583 if (!__test_and_set_bit(idx, sched->state.used))
587 /* Grab the first unused counter starting with idx */
588 idx = sched->state.counter;
589 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_FIXED) {
590 if (!__test_and_set_bit(idx, sched->state.used))
597 sched->state.counter = idx;
600 perf_sched_save_state(sched);
605 static bool perf_sched_find_counter(struct perf_sched *sched)
607 while (!__perf_sched_find_counter(sched)) {
608 if (!perf_sched_restore_state(sched))
616 * Go through all unassigned events and find the next one to schedule.
617 * Take events with the least weight first. Return true on success.
619 static bool perf_sched_next_event(struct perf_sched *sched)
621 struct event_constraint *c;
623 if (!sched->state.unassigned || !--sched->state.unassigned)
628 sched->state.event++;
629 if (sched->state.event >= sched->max_events) {
631 sched->state.event = 0;
632 sched->state.weight++;
633 if (sched->state.weight > sched->max_weight)
636 c = sched->constraints[sched->state.event];
637 } while (c->weight != sched->state.weight);
639 sched->state.counter = 0; /* start with first counter */
645 * Assign a counter for each event.
647 static int perf_assign_events(struct event_constraint **constraints, int n,
648 int wmin, int wmax, int *assign)
650 struct perf_sched sched;
652 perf_sched_init(&sched, constraints, n, wmin, wmax);
655 if (!perf_sched_find_counter(&sched))
658 assign[sched.state.event] = sched.state.counter;
659 } while (perf_sched_next_event(&sched));
661 return sched.state.unassigned;
664 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
666 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
667 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
668 int i, wmin, wmax, num = 0;
669 struct hw_perf_event *hwc;
671 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
673 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
674 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
676 wmin = min(wmin, c->weight);
677 wmax = max(wmax, c->weight);
681 * fastpath, try to reuse previous register
683 for (i = 0; i < n; i++) {
684 hwc = &cpuc->event_list[i]->hw;
691 /* constraint still honored */
692 if (!test_bit(hwc->idx, c->idxmsk))
695 /* not already used */
696 if (test_bit(hwc->idx, used_mask))
699 __set_bit(hwc->idx, used_mask);
701 assign[i] = hwc->idx;
706 num = perf_assign_events(constraints, n, wmin, wmax, assign);
709 * scheduling failed or is just a simulation,
710 * free resources if necessary
712 if (!assign || num) {
713 for (i = 0; i < n; i++) {
714 if (x86_pmu.put_event_constraints)
715 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
718 return num ? -EINVAL : 0;
722 * dogrp: true if must collect siblings events (group)
723 * returns total number of events and error code
725 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
727 struct perf_event *event;
730 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
732 /* current number of events already accepted */
735 if (is_x86_event(leader)) {
738 cpuc->event_list[n] = leader;
744 list_for_each_entry(event, &leader->sibling_list, group_entry) {
745 if (!is_x86_event(event) ||
746 event->state <= PERF_EVENT_STATE_OFF)
752 cpuc->event_list[n] = event;
758 static inline void x86_assign_hw_event(struct perf_event *event,
759 struct cpu_hw_events *cpuc, int i)
761 struct hw_perf_event *hwc = &event->hw;
763 hwc->idx = cpuc->assign[i];
764 hwc->last_cpu = smp_processor_id();
765 hwc->last_tag = ++cpuc->tags[i];
767 if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
768 hwc->config_base = 0;
770 } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
771 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
772 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
774 hwc->config_base = x86_pmu_config_addr(hwc->idx);
775 hwc->event_base = x86_pmu_event_addr(hwc->idx);
779 static inline int match_prev_assignment(struct hw_perf_event *hwc,
780 struct cpu_hw_events *cpuc,
783 return hwc->idx == cpuc->assign[i] &&
784 hwc->last_cpu == smp_processor_id() &&
785 hwc->last_tag == cpuc->tags[i];
788 static void x86_pmu_start(struct perf_event *event, int flags);
790 static void x86_pmu_enable(struct pmu *pmu)
792 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
793 struct perf_event *event;
794 struct hw_perf_event *hwc;
795 int i, added = cpuc->n_added;
797 if (!x86_pmu_initialized())
804 int n_running = cpuc->n_events - cpuc->n_added;
806 * apply assignment obtained either from
807 * hw_perf_group_sched_in() or x86_pmu_enable()
809 * step1: save events moving to new counters
810 * step2: reprogram moved events into new counters
812 for (i = 0; i < n_running; i++) {
813 event = cpuc->event_list[i];
817 * we can avoid reprogramming counter if:
818 * - assigned same counter as last time
819 * - running on same CPU as last time
820 * - no other event has used the counter since
822 if (hwc->idx == -1 ||
823 match_prev_assignment(hwc, cpuc, i))
827 * Ensure we don't accidentally enable a stopped
828 * counter simply because we rescheduled.
830 if (hwc->state & PERF_HES_STOPPED)
831 hwc->state |= PERF_HES_ARCH;
833 x86_pmu_stop(event, PERF_EF_UPDATE);
836 for (i = 0; i < cpuc->n_events; i++) {
837 event = cpuc->event_list[i];
840 if (!match_prev_assignment(hwc, cpuc, i))
841 x86_assign_hw_event(event, cpuc, i);
842 else if (i < n_running)
845 if (hwc->state & PERF_HES_ARCH)
848 x86_pmu_start(event, PERF_EF_RELOAD);
851 perf_events_lapic_init();
857 x86_pmu.enable_all(added);
860 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
863 * Set the next IRQ period, based on the hwc->period_left value.
864 * To be called with the event disabled in hw:
866 int x86_perf_event_set_period(struct perf_event *event)
868 struct hw_perf_event *hwc = &event->hw;
869 s64 left = local64_read(&hwc->period_left);
870 s64 period = hwc->sample_period;
871 int ret = 0, idx = hwc->idx;
873 if (idx == X86_PMC_IDX_FIXED_BTS)
877 * If we are way outside a reasonable range then just skip forward:
879 if (unlikely(left <= -period)) {
881 local64_set(&hwc->period_left, left);
882 hwc->last_period = period;
886 if (unlikely(left <= 0)) {
888 local64_set(&hwc->period_left, left);
889 hwc->last_period = period;
893 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
895 if (unlikely(left < 2))
898 if (left > x86_pmu.max_period)
899 left = x86_pmu.max_period;
901 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
904 * The hw event starts counting from this event offset,
905 * mark it to be able to extra future deltas:
907 local64_set(&hwc->prev_count, (u64)-left);
909 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
912 * Due to erratum on certan cpu we need
913 * a second write to be sure the register
914 * is updated properly
916 if (x86_pmu.perfctr_second_write) {
917 wrmsrl(hwc->event_base,
918 (u64)(-left) & x86_pmu.cntval_mask);
921 perf_event_update_userpage(event);
926 void x86_pmu_enable_event(struct perf_event *event)
928 if (__this_cpu_read(cpu_hw_events.enabled))
929 __x86_pmu_enable_event(&event->hw,
930 ARCH_PERFMON_EVENTSEL_ENABLE);
934 * Add a single event to the PMU.
936 * The event is added to the group of enabled events
937 * but only if it can be scehduled with existing events.
939 static int x86_pmu_add(struct perf_event *event, int flags)
941 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
942 struct hw_perf_event *hwc;
943 int assign[X86_PMC_IDX_MAX];
948 perf_pmu_disable(event->pmu);
950 ret = n = collect_events(cpuc, event, false);
954 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
955 if (!(flags & PERF_EF_START))
956 hwc->state |= PERF_HES_ARCH;
959 * If group events scheduling transaction was started,
960 * skip the schedulability test here, it will be performed
961 * at commit time (->commit_txn) as a whole
963 if (cpuc->group_flag & PERF_EVENT_TXN)
966 ret = x86_pmu.schedule_events(cpuc, n, assign);
970 * copy new assignment, now we know it is possible
971 * will be used by hw_perf_enable()
973 memcpy(cpuc->assign, assign, n*sizeof(int));
977 cpuc->n_added += n - n0;
978 cpuc->n_txn += n - n0;
982 perf_pmu_enable(event->pmu);
986 static void x86_pmu_start(struct perf_event *event, int flags)
988 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
989 int idx = event->hw.idx;
991 if (WARN_ON_ONCE(idx == -1))
994 if (flags & PERF_EF_RELOAD) {
995 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
996 x86_perf_event_set_period(event);
1001 cpuc->events[idx] = event;
1002 __set_bit(idx, cpuc->active_mask);
1003 __set_bit(idx, cpuc->running);
1004 x86_pmu.enable(event);
1005 perf_event_update_userpage(event);
1008 void perf_event_print_debug(void)
1010 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1012 struct cpu_hw_events *cpuc;
1013 unsigned long flags;
1016 if (!x86_pmu.num_counters)
1019 local_irq_save(flags);
1021 cpu = smp_processor_id();
1022 cpuc = &per_cpu(cpu_hw_events, cpu);
1024 if (x86_pmu.version >= 2) {
1025 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1026 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1027 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1028 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1029 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1032 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1033 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1034 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1035 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1036 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1038 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1040 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1041 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1042 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1044 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1046 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1047 cpu, idx, pmc_ctrl);
1048 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1049 cpu, idx, pmc_count);
1050 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1051 cpu, idx, prev_left);
1053 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1054 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1056 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1057 cpu, idx, pmc_count);
1059 local_irq_restore(flags);
1062 void x86_pmu_stop(struct perf_event *event, int flags)
1064 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1065 struct hw_perf_event *hwc = &event->hw;
1067 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1068 x86_pmu.disable(event);
1069 cpuc->events[hwc->idx] = NULL;
1070 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1071 hwc->state |= PERF_HES_STOPPED;
1074 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1076 * Drain the remaining delta count out of a event
1077 * that we are disabling:
1079 x86_perf_event_update(event);
1080 hwc->state |= PERF_HES_UPTODATE;
1084 static void x86_pmu_del(struct perf_event *event, int flags)
1086 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1090 * If we're called during a txn, we don't need to do anything.
1091 * The events never got scheduled and ->cancel_txn will truncate
1094 if (cpuc->group_flag & PERF_EVENT_TXN)
1097 x86_pmu_stop(event, PERF_EF_UPDATE);
1099 for (i = 0; i < cpuc->n_events; i++) {
1100 if (event == cpuc->event_list[i]) {
1102 if (x86_pmu.put_event_constraints)
1103 x86_pmu.put_event_constraints(cpuc, event);
1105 while (++i < cpuc->n_events)
1106 cpuc->event_list[i-1] = cpuc->event_list[i];
1112 perf_event_update_userpage(event);
1115 int x86_pmu_handle_irq(struct pt_regs *regs)
1117 struct perf_sample_data data;
1118 struct cpu_hw_events *cpuc;
1119 struct perf_event *event;
1120 int idx, handled = 0;
1123 perf_sample_data_init(&data, 0);
1125 cpuc = &__get_cpu_var(cpu_hw_events);
1128 * Some chipsets need to unmask the LVTPC in a particular spot
1129 * inside the nmi handler. As a result, the unmasking was pushed
1130 * into all the nmi handlers.
1132 * This generic handler doesn't seem to have any issues where the
1133 * unmasking occurs so it was left at the top.
1135 apic_write(APIC_LVTPC, APIC_DM_NMI);
1137 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1138 if (!test_bit(idx, cpuc->active_mask)) {
1140 * Though we deactivated the counter some cpus
1141 * might still deliver spurious interrupts still
1142 * in flight. Catch them:
1144 if (__test_and_clear_bit(idx, cpuc->running))
1149 event = cpuc->events[idx];
1151 val = x86_perf_event_update(event);
1152 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1159 data.period = event->hw.last_period;
1161 if (!x86_perf_event_set_period(event))
1164 if (perf_event_overflow(event, &data, regs))
1165 x86_pmu_stop(event, 0);
1169 inc_irq_stat(apic_perf_irqs);
1174 void perf_events_lapic_init(void)
1176 if (!x86_pmu.apic || !x86_pmu_initialized())
1180 * Always use NMI for PMU
1182 apic_write(APIC_LVTPC, APIC_DM_NMI);
1185 static int __kprobes
1186 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1188 if (!atomic_read(&active_events))
1191 return x86_pmu.handle_irq(regs);
1194 struct event_constraint emptyconstraint;
1195 struct event_constraint unconstrained;
1197 static int __cpuinit
1198 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1200 unsigned int cpu = (long)hcpu;
1201 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1202 int ret = NOTIFY_OK;
1204 switch (action & ~CPU_TASKS_FROZEN) {
1205 case CPU_UP_PREPARE:
1206 cpuc->kfree_on_online = NULL;
1207 if (x86_pmu.cpu_prepare)
1208 ret = x86_pmu.cpu_prepare(cpu);
1212 if (x86_pmu.attr_rdpmc)
1213 set_in_cr4(X86_CR4_PCE);
1214 if (x86_pmu.cpu_starting)
1215 x86_pmu.cpu_starting(cpu);
1219 kfree(cpuc->kfree_on_online);
1223 if (x86_pmu.cpu_dying)
1224 x86_pmu.cpu_dying(cpu);
1227 case CPU_UP_CANCELED:
1229 if (x86_pmu.cpu_dead)
1230 x86_pmu.cpu_dead(cpu);
1240 static void __init pmu_check_apic(void)
1246 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1247 pr_info("no hardware sampling interrupt available.\n");
1250 static int __init init_hw_perf_events(void)
1252 struct x86_pmu_quirk *quirk;
1253 struct event_constraint *c;
1256 pr_info("Performance Events: ");
1258 switch (boot_cpu_data.x86_vendor) {
1259 case X86_VENDOR_INTEL:
1260 err = intel_pmu_init();
1262 case X86_VENDOR_AMD:
1263 err = amd_pmu_init();
1269 pr_cont("no PMU driver, software events only.\n");
1275 /* sanity check that the hardware exists or is emulated */
1276 if (!check_hw_exists())
1279 pr_cont("%s PMU driver.\n", x86_pmu.name);
1281 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1284 if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1285 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1286 x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1287 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1289 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1291 if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1292 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1293 x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1294 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1297 x86_pmu.intel_ctrl |=
1298 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1300 perf_events_lapic_init();
1301 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1303 unconstrained = (struct event_constraint)
1304 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1305 0, x86_pmu.num_counters, 0);
1307 if (x86_pmu.event_constraints) {
1309 * event on fixed counter2 (REF_CYCLES) only works on this
1310 * counter, so do not extend mask to generic counters
1312 for_each_event_constraint(c, x86_pmu.event_constraints) {
1313 if (c->cmask != X86_RAW_EVENT_MASK
1314 || c->idxmsk64 == X86_PMC_MSK_FIXED_REF_CYCLES) {
1318 c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1319 c->weight += x86_pmu.num_counters;
1323 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1325 pr_info("... version: %d\n", x86_pmu.version);
1326 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1327 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1328 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1329 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1330 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1331 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1333 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1334 perf_cpu_notifier(x86_pmu_notifier);
1338 early_initcall(init_hw_perf_events);
1340 static inline void x86_pmu_read(struct perf_event *event)
1342 x86_perf_event_update(event);
1346 * Start group events scheduling transaction
1347 * Set the flag to make pmu::enable() not perform the
1348 * schedulability test, it will be performed at commit time
1350 static void x86_pmu_start_txn(struct pmu *pmu)
1352 perf_pmu_disable(pmu);
1353 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1354 __this_cpu_write(cpu_hw_events.n_txn, 0);
1358 * Stop group events scheduling transaction
1359 * Clear the flag and pmu::enable() will perform the
1360 * schedulability test.
1362 static void x86_pmu_cancel_txn(struct pmu *pmu)
1364 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1366 * Truncate the collected events.
1368 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1369 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1370 perf_pmu_enable(pmu);
1374 * Commit group events scheduling transaction
1375 * Perform the group schedulability test as a whole
1376 * Return 0 if success
1378 static int x86_pmu_commit_txn(struct pmu *pmu)
1380 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1381 int assign[X86_PMC_IDX_MAX];
1386 if (!x86_pmu_initialized())
1389 ret = x86_pmu.schedule_events(cpuc, n, assign);
1394 * copy new assignment, now we know it is possible
1395 * will be used by hw_perf_enable()
1397 memcpy(cpuc->assign, assign, n*sizeof(int));
1399 cpuc->group_flag &= ~PERF_EVENT_TXN;
1400 perf_pmu_enable(pmu);
1404 * a fake_cpuc is used to validate event groups. Due to
1405 * the extra reg logic, we need to also allocate a fake
1406 * per_core and per_cpu structure. Otherwise, group events
1407 * using extra reg may conflict without the kernel being
1408 * able to catch this when the last event gets added to
1411 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1413 kfree(cpuc->shared_regs);
1417 static struct cpu_hw_events *allocate_fake_cpuc(void)
1419 struct cpu_hw_events *cpuc;
1420 int cpu = raw_smp_processor_id();
1422 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1424 return ERR_PTR(-ENOMEM);
1426 /* only needed, if we have extra_regs */
1427 if (x86_pmu.extra_regs) {
1428 cpuc->shared_regs = allocate_shared_regs(cpu);
1429 if (!cpuc->shared_regs)
1434 free_fake_cpuc(cpuc);
1435 return ERR_PTR(-ENOMEM);
1439 * validate that we can schedule this event
1441 static int validate_event(struct perf_event *event)
1443 struct cpu_hw_events *fake_cpuc;
1444 struct event_constraint *c;
1447 fake_cpuc = allocate_fake_cpuc();
1448 if (IS_ERR(fake_cpuc))
1449 return PTR_ERR(fake_cpuc);
1451 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1453 if (!c || !c->weight)
1456 if (x86_pmu.put_event_constraints)
1457 x86_pmu.put_event_constraints(fake_cpuc, event);
1459 free_fake_cpuc(fake_cpuc);
1465 * validate a single event group
1467 * validation include:
1468 * - check events are compatible which each other
1469 * - events do not compete for the same counter
1470 * - number of events <= number of counters
1472 * validation ensures the group can be loaded onto the
1473 * PMU if it was the only group available.
1475 static int validate_group(struct perf_event *event)
1477 struct perf_event *leader = event->group_leader;
1478 struct cpu_hw_events *fake_cpuc;
1479 int ret = -EINVAL, n;
1481 fake_cpuc = allocate_fake_cpuc();
1482 if (IS_ERR(fake_cpuc))
1483 return PTR_ERR(fake_cpuc);
1485 * the event is not yet connected with its
1486 * siblings therefore we must first collect
1487 * existing siblings, then add the new event
1488 * before we can simulate the scheduling
1490 n = collect_events(fake_cpuc, leader, true);
1494 fake_cpuc->n_events = n;
1495 n = collect_events(fake_cpuc, event, false);
1499 fake_cpuc->n_events = n;
1501 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1504 free_fake_cpuc(fake_cpuc);
1508 static int x86_pmu_event_init(struct perf_event *event)
1513 switch (event->attr.type) {
1515 case PERF_TYPE_HARDWARE:
1516 case PERF_TYPE_HW_CACHE:
1523 err = __x86_pmu_event_init(event);
1526 * we temporarily connect event to its pmu
1527 * such that validate_group() can classify
1528 * it as an x86 event using is_x86_event()
1533 if (event->group_leader != event)
1534 err = validate_group(event);
1536 err = validate_event(event);
1542 event->destroy(event);
1548 static int x86_pmu_event_idx(struct perf_event *event)
1550 int idx = event->hw.idx;
1552 if (x86_pmu.num_counters_fixed && idx >= X86_PMC_IDX_FIXED) {
1553 idx -= X86_PMC_IDX_FIXED;
1560 static ssize_t get_attr_rdpmc(struct device *cdev,
1561 struct device_attribute *attr,
1564 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1567 static void change_rdpmc(void *info)
1569 bool enable = !!(unsigned long)info;
1572 set_in_cr4(X86_CR4_PCE);
1574 clear_in_cr4(X86_CR4_PCE);
1577 static ssize_t set_attr_rdpmc(struct device *cdev,
1578 struct device_attribute *attr,
1579 const char *buf, size_t count)
1581 unsigned long val = simple_strtoul(buf, NULL, 0);
1583 if (!!val != !!x86_pmu.attr_rdpmc) {
1584 x86_pmu.attr_rdpmc = !!val;
1585 smp_call_function(change_rdpmc, (void *)val, 1);
1591 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
1593 static struct attribute *x86_pmu_attrs[] = {
1594 &dev_attr_rdpmc.attr,
1598 static struct attribute_group x86_pmu_attr_group = {
1599 .attrs = x86_pmu_attrs,
1602 static const struct attribute_group *x86_pmu_attr_groups[] = {
1603 &x86_pmu_attr_group,
1607 static struct pmu pmu = {
1608 .pmu_enable = x86_pmu_enable,
1609 .pmu_disable = x86_pmu_disable,
1611 .attr_groups = x86_pmu_attr_groups,
1613 .event_init = x86_pmu_event_init,
1617 .start = x86_pmu_start,
1618 .stop = x86_pmu_stop,
1619 .read = x86_pmu_read,
1621 .start_txn = x86_pmu_start_txn,
1622 .cancel_txn = x86_pmu_cancel_txn,
1623 .commit_txn = x86_pmu_commit_txn,
1625 .event_idx = x86_pmu_event_idx,
1628 void perf_update_user_clock(struct perf_event_mmap_page *userpg, u64 now)
1630 if (!boot_cpu_has(X86_FEATURE_CONSTANT_TSC))
1633 if (!boot_cpu_has(X86_FEATURE_NONSTOP_TSC))
1636 userpg->time_mult = this_cpu_read(cyc2ns);
1637 userpg->time_shift = CYC2NS_SCALE_FACTOR;
1638 userpg->time_offset = this_cpu_read(cyc2ns_offset) - now;
1645 static int backtrace_stack(void *data, char *name)
1650 static void backtrace_address(void *data, unsigned long addr, int reliable)
1652 struct perf_callchain_entry *entry = data;
1654 perf_callchain_store(entry, addr);
1657 static const struct stacktrace_ops backtrace_ops = {
1658 .stack = backtrace_stack,
1659 .address = backtrace_address,
1660 .walk_stack = print_context_stack_bp,
1664 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1666 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1667 /* TODO: We don't support guest os callchain now */
1671 perf_callchain_store(entry, regs->ip);
1673 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1676 #ifdef CONFIG_COMPAT
1678 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1680 /* 32-bit process in 64-bit kernel. */
1681 struct stack_frame_ia32 frame;
1682 const void __user *fp;
1684 if (!test_thread_flag(TIF_IA32))
1687 fp = compat_ptr(regs->bp);
1688 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1689 unsigned long bytes;
1690 frame.next_frame = 0;
1691 frame.return_address = 0;
1693 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1694 if (bytes != sizeof(frame))
1697 if (fp < compat_ptr(regs->sp))
1700 perf_callchain_store(entry, frame.return_address);
1701 fp = compat_ptr(frame.next_frame);
1707 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1714 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1716 struct stack_frame frame;
1717 const void __user *fp;
1719 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1720 /* TODO: We don't support guest os callchain now */
1724 fp = (void __user *)regs->bp;
1726 perf_callchain_store(entry, regs->ip);
1731 if (perf_callchain_user32(regs, entry))
1734 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1735 unsigned long bytes;
1736 frame.next_frame = NULL;
1737 frame.return_address = 0;
1739 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1740 if (bytes != sizeof(frame))
1743 if ((unsigned long)fp < regs->sp)
1746 perf_callchain_store(entry, frame.return_address);
1747 fp = frame.next_frame;
1751 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1755 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1756 ip = perf_guest_cbs->get_guest_ip();
1758 ip = instruction_pointer(regs);
1763 unsigned long perf_misc_flags(struct pt_regs *regs)
1767 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1768 if (perf_guest_cbs->is_user_mode())
1769 misc |= PERF_RECORD_MISC_GUEST_USER;
1771 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1773 if (user_mode(regs))
1774 misc |= PERF_RECORD_MISC_USER;
1776 misc |= PERF_RECORD_MISC_KERNEL;
1779 if (regs->flags & PERF_EFLAGS_EXACT)
1780 misc |= PERF_RECORD_MISC_EXACT_IP;
1785 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
1787 cap->version = x86_pmu.version;
1788 cap->num_counters_gp = x86_pmu.num_counters;
1789 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
1790 cap->bit_width_gp = x86_pmu.cntval_bits;
1791 cap->bit_width_fixed = x86_pmu.cntval_bits;
1792 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
1793 cap->events_mask_len = x86_pmu.events_mask_len;
1795 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);