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>
29 #include <asm/stacktrace.h>
32 #include <asm/alternative.h>
34 #include "perf_event.h"
38 #define wrmsrl(msr, val) \
40 trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
41 (unsigned long)(val)); \
42 native_write_msr((msr), (u32)((u64)(val)), \
43 (u32)((u64)(val) >> 32)); \
47 struct x86_pmu x86_pmu __read_mostly;
49 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
53 u64 __read_mostly hw_cache_event_ids
54 [PERF_COUNT_HW_CACHE_MAX]
55 [PERF_COUNT_HW_CACHE_OP_MAX]
56 [PERF_COUNT_HW_CACHE_RESULT_MAX];
57 u64 __read_mostly hw_cache_extra_regs
58 [PERF_COUNT_HW_CACHE_MAX]
59 [PERF_COUNT_HW_CACHE_OP_MAX]
60 [PERF_COUNT_HW_CACHE_RESULT_MAX];
63 * Propagate event elapsed time into the generic event.
64 * Can only be executed on the CPU where the event is active.
65 * Returns the delta events processed.
67 u64 x86_perf_event_update(struct perf_event *event)
69 struct hw_perf_event *hwc = &event->hw;
70 int shift = 64 - x86_pmu.cntval_bits;
71 u64 prev_raw_count, new_raw_count;
75 if (idx == X86_PMC_IDX_FIXED_BTS)
79 * Careful: an NMI might modify the previous event value.
81 * Our tactic to handle this is to first atomically read and
82 * exchange a new raw count - then add that new-prev delta
83 * count to the generic event atomically:
86 prev_raw_count = local64_read(&hwc->prev_count);
87 rdmsrl(hwc->event_base, new_raw_count);
89 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
90 new_raw_count) != prev_raw_count)
94 * Now we have the new raw value and have updated the prev
95 * timestamp already. We can now calculate the elapsed delta
96 * (event-)time and add that to the generic event.
98 * Careful, not all hw sign-extends above the physical width
101 delta = (new_raw_count << shift) - (prev_raw_count << shift);
104 local64_add(delta, &event->count);
105 local64_sub(delta, &hwc->period_left);
107 return new_raw_count;
111 * Find and validate any extra registers to set up.
113 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
115 struct hw_perf_event_extra *reg;
116 struct extra_reg *er;
118 reg = &event->hw.extra_reg;
120 if (!x86_pmu.extra_regs)
123 for (er = x86_pmu.extra_regs; er->msr; er++) {
124 if (er->event != (config & er->config_mask))
126 if (event->attr.config1 & ~er->valid_mask)
130 reg->config = event->attr.config1;
137 static atomic_t active_events;
138 static DEFINE_MUTEX(pmc_reserve_mutex);
140 #ifdef CONFIG_X86_LOCAL_APIC
142 static bool reserve_pmc_hardware(void)
146 for (i = 0; i < x86_pmu.num_counters; i++) {
147 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
151 for (i = 0; i < x86_pmu.num_counters; i++) {
152 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
159 for (i--; i >= 0; i--)
160 release_evntsel_nmi(x86_pmu_config_addr(i));
162 i = x86_pmu.num_counters;
165 for (i--; i >= 0; i--)
166 release_perfctr_nmi(x86_pmu_event_addr(i));
171 static void release_pmc_hardware(void)
175 for (i = 0; i < x86_pmu.num_counters; i++) {
176 release_perfctr_nmi(x86_pmu_event_addr(i));
177 release_evntsel_nmi(x86_pmu_config_addr(i));
183 static bool reserve_pmc_hardware(void) { return true; }
184 static void release_pmc_hardware(void) {}
188 static bool check_hw_exists(void)
190 u64 val, val_new = 0;
194 * Check to see if the BIOS enabled any of the counters, if so
197 for (i = 0; i < x86_pmu.num_counters; i++) {
198 reg = x86_pmu_config_addr(i);
199 ret = rdmsrl_safe(reg, &val);
202 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
206 if (x86_pmu.num_counters_fixed) {
207 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
208 ret = rdmsrl_safe(reg, &val);
211 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
212 if (val & (0x03 << i*4))
218 * Now write a value and read it back to see if it matches,
219 * this is needed to detect certain hardware emulators (qemu/kvm)
220 * that don't trap on the MSR access and always return 0s.
223 ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
224 ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
225 if (ret || val != val_new)
232 * We still allow the PMU driver to operate:
234 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
235 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
240 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
245 static void hw_perf_event_destroy(struct perf_event *event)
247 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
248 release_pmc_hardware();
249 release_ds_buffers();
250 mutex_unlock(&pmc_reserve_mutex);
254 static inline int x86_pmu_initialized(void)
256 return x86_pmu.handle_irq != NULL;
260 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
262 struct perf_event_attr *attr = &event->attr;
263 unsigned int cache_type, cache_op, cache_result;
266 config = attr->config;
268 cache_type = (config >> 0) & 0xff;
269 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
272 cache_op = (config >> 8) & 0xff;
273 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
276 cache_result = (config >> 16) & 0xff;
277 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
280 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
289 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
290 return x86_pmu_extra_regs(val, event);
293 int x86_setup_perfctr(struct perf_event *event)
295 struct perf_event_attr *attr = &event->attr;
296 struct hw_perf_event *hwc = &event->hw;
299 if (!is_sampling_event(event)) {
300 hwc->sample_period = x86_pmu.max_period;
301 hwc->last_period = hwc->sample_period;
302 local64_set(&hwc->period_left, hwc->sample_period);
305 * If we have a PMU initialized but no APIC
306 * interrupts, we cannot sample hardware
307 * events (user-space has to fall back and
308 * sample via a hrtimer based software event):
314 if (attr->type == PERF_TYPE_RAW)
315 return x86_pmu_extra_regs(event->attr.config, event);
317 if (attr->type == PERF_TYPE_HW_CACHE)
318 return set_ext_hw_attr(hwc, event);
320 if (attr->config >= x86_pmu.max_events)
326 config = x86_pmu.event_map(attr->config);
337 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
338 !attr->freq && hwc->sample_period == 1) {
339 /* BTS is not supported by this architecture. */
340 if (!x86_pmu.bts_active)
343 /* BTS is currently only allowed for user-mode. */
344 if (!attr->exclude_kernel)
348 hwc->config |= config;
353 int x86_pmu_hw_config(struct perf_event *event)
355 if (event->attr.precise_ip) {
358 /* Support for constant skid */
359 if (x86_pmu.pebs_active) {
362 /* Support for IP fixup */
367 if (event->attr.precise_ip > precise)
373 * (keep 'enabled' bit clear for now)
375 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
378 * Count user and OS events unless requested not to
380 if (!event->attr.exclude_user)
381 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
382 if (!event->attr.exclude_kernel)
383 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
385 if (event->attr.type == PERF_TYPE_RAW)
386 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
388 return x86_setup_perfctr(event);
392 * Setup the hardware configuration for a given attr_type
394 static int __x86_pmu_event_init(struct perf_event *event)
398 if (!x86_pmu_initialized())
402 if (!atomic_inc_not_zero(&active_events)) {
403 mutex_lock(&pmc_reserve_mutex);
404 if (atomic_read(&active_events) == 0) {
405 if (!reserve_pmc_hardware())
408 reserve_ds_buffers();
411 atomic_inc(&active_events);
412 mutex_unlock(&pmc_reserve_mutex);
417 event->destroy = hw_perf_event_destroy;
420 event->hw.last_cpu = -1;
421 event->hw.last_tag = ~0ULL;
424 event->hw.extra_reg.idx = EXTRA_REG_NONE;
426 return x86_pmu.hw_config(event);
429 void x86_pmu_disable_all(void)
431 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
434 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
437 if (!test_bit(idx, cpuc->active_mask))
439 rdmsrl(x86_pmu_config_addr(idx), val);
440 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
442 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
443 wrmsrl(x86_pmu_config_addr(idx), val);
447 static void x86_pmu_disable(struct pmu *pmu)
449 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
451 if (!x86_pmu_initialized())
461 x86_pmu.disable_all();
464 void x86_pmu_enable_all(int added)
466 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
469 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
470 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
472 if (!test_bit(idx, cpuc->active_mask))
475 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
479 static struct pmu pmu;
481 static inline int is_x86_event(struct perf_event *event)
483 return event->pmu == &pmu;
487 * Event scheduler state:
489 * Assign events iterating over all events and counters, beginning
490 * with events with least weights first. Keep the current iterator
491 * state in struct sched_state.
495 int event; /* event index */
496 int counter; /* counter index */
497 int unassigned; /* number of events to be assigned left */
498 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
501 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
502 #define SCHED_STATES_MAX 2
507 struct event_constraint **constraints;
508 struct sched_state state;
510 struct sched_state saved[SCHED_STATES_MAX];
514 * Initialize interator that runs through all events and counters.
516 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **c,
517 int num, int wmin, int wmax)
521 memset(sched, 0, sizeof(*sched));
522 sched->max_events = num;
523 sched->max_weight = wmax;
524 sched->constraints = c;
526 for (idx = 0; idx < num; idx++) {
527 if (c[idx]->weight == wmin)
531 sched->state.event = idx; /* start with min weight */
532 sched->state.weight = wmin;
533 sched->state.unassigned = num;
536 static void perf_sched_save_state(struct perf_sched *sched)
538 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
541 sched->saved[sched->saved_states] = sched->state;
542 sched->saved_states++;
545 static bool perf_sched_restore_state(struct perf_sched *sched)
547 if (!sched->saved_states)
550 sched->saved_states--;
551 sched->state = sched->saved[sched->saved_states];
553 /* continue with next counter: */
554 clear_bit(sched->state.counter++, sched->state.used);
560 * Select a counter for the current event to schedule. Return true on
563 static bool __perf_sched_find_counter(struct perf_sched *sched)
565 struct event_constraint *c;
568 if (!sched->state.unassigned)
571 if (sched->state.event >= sched->max_events)
574 c = sched->constraints[sched->state.event];
576 /* Prefer fixed purpose counters */
577 if (x86_pmu.num_counters_fixed) {
578 idx = X86_PMC_IDX_FIXED;
579 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_MAX) {
580 if (!__test_and_set_bit(idx, sched->state.used))
584 /* Grab the first unused counter starting with idx */
585 idx = sched->state.counter;
586 for_each_set_bit_cont(idx, c->idxmsk, X86_PMC_IDX_FIXED) {
587 if (!__test_and_set_bit(idx, sched->state.used))
594 sched->state.counter = idx;
597 perf_sched_save_state(sched);
602 static bool perf_sched_find_counter(struct perf_sched *sched)
604 while (!__perf_sched_find_counter(sched)) {
605 if (!perf_sched_restore_state(sched))
613 * Go through all unassigned events and find the next one to schedule.
614 * Take events with the least weight first. Return true on success.
616 static bool perf_sched_next_event(struct perf_sched *sched)
618 struct event_constraint *c;
620 if (!sched->state.unassigned || !--sched->state.unassigned)
625 sched->state.event++;
626 if (sched->state.event >= sched->max_events) {
628 sched->state.event = 0;
629 sched->state.weight++;
630 if (sched->state.weight > sched->max_weight)
633 c = sched->constraints[sched->state.event];
634 } while (c->weight != sched->state.weight);
636 sched->state.counter = 0; /* start with first counter */
642 * Assign a counter for each event.
644 static int perf_assign_events(struct event_constraint **constraints, int n,
645 int wmin, int wmax, int *assign)
647 struct perf_sched sched;
649 perf_sched_init(&sched, constraints, n, wmin, wmax);
652 if (!perf_sched_find_counter(&sched))
655 assign[sched.state.event] = sched.state.counter;
656 } while (perf_sched_next_event(&sched));
658 return sched.state.unassigned;
661 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
663 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
664 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
665 int i, wmin, wmax, num = 0;
666 struct hw_perf_event *hwc;
668 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
670 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
671 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
673 wmin = min(wmin, c->weight);
674 wmax = max(wmax, c->weight);
678 * fastpath, try to reuse previous register
680 for (i = 0; i < n; i++) {
681 hwc = &cpuc->event_list[i]->hw;
688 /* constraint still honored */
689 if (!test_bit(hwc->idx, c->idxmsk))
692 /* not already used */
693 if (test_bit(hwc->idx, used_mask))
696 __set_bit(hwc->idx, used_mask);
698 assign[i] = hwc->idx;
703 num = perf_assign_events(constraints, n, wmin, wmax, assign);
706 * scheduling failed or is just a simulation,
707 * free resources if necessary
709 if (!assign || num) {
710 for (i = 0; i < n; i++) {
711 if (x86_pmu.put_event_constraints)
712 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
715 return num ? -EINVAL : 0;
719 * dogrp: true if must collect siblings events (group)
720 * returns total number of events and error code
722 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
724 struct perf_event *event;
727 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
729 /* current number of events already accepted */
732 if (is_x86_event(leader)) {
735 cpuc->event_list[n] = leader;
741 list_for_each_entry(event, &leader->sibling_list, group_entry) {
742 if (!is_x86_event(event) ||
743 event->state <= PERF_EVENT_STATE_OFF)
749 cpuc->event_list[n] = event;
755 static inline void x86_assign_hw_event(struct perf_event *event,
756 struct cpu_hw_events *cpuc, int i)
758 struct hw_perf_event *hwc = &event->hw;
760 hwc->idx = cpuc->assign[i];
761 hwc->last_cpu = smp_processor_id();
762 hwc->last_tag = ++cpuc->tags[i];
764 if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
765 hwc->config_base = 0;
767 } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
768 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
769 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
771 hwc->config_base = x86_pmu_config_addr(hwc->idx);
772 hwc->event_base = x86_pmu_event_addr(hwc->idx);
776 static inline int match_prev_assignment(struct hw_perf_event *hwc,
777 struct cpu_hw_events *cpuc,
780 return hwc->idx == cpuc->assign[i] &&
781 hwc->last_cpu == smp_processor_id() &&
782 hwc->last_tag == cpuc->tags[i];
785 static void x86_pmu_start(struct perf_event *event, int flags);
787 static void x86_pmu_enable(struct pmu *pmu)
789 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
790 struct perf_event *event;
791 struct hw_perf_event *hwc;
792 int i, added = cpuc->n_added;
794 if (!x86_pmu_initialized())
801 int n_running = cpuc->n_events - cpuc->n_added;
803 * apply assignment obtained either from
804 * hw_perf_group_sched_in() or x86_pmu_enable()
806 * step1: save events moving to new counters
807 * step2: reprogram moved events into new counters
809 for (i = 0; i < n_running; i++) {
810 event = cpuc->event_list[i];
814 * we can avoid reprogramming counter if:
815 * - assigned same counter as last time
816 * - running on same CPU as last time
817 * - no other event has used the counter since
819 if (hwc->idx == -1 ||
820 match_prev_assignment(hwc, cpuc, i))
824 * Ensure we don't accidentally enable a stopped
825 * counter simply because we rescheduled.
827 if (hwc->state & PERF_HES_STOPPED)
828 hwc->state |= PERF_HES_ARCH;
830 x86_pmu_stop(event, PERF_EF_UPDATE);
833 for (i = 0; i < cpuc->n_events; i++) {
834 event = cpuc->event_list[i];
837 if (!match_prev_assignment(hwc, cpuc, i))
838 x86_assign_hw_event(event, cpuc, i);
839 else if (i < n_running)
842 if (hwc->state & PERF_HES_ARCH)
845 x86_pmu_start(event, PERF_EF_RELOAD);
848 perf_events_lapic_init();
854 x86_pmu.enable_all(added);
857 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
860 * Set the next IRQ period, based on the hwc->period_left value.
861 * To be called with the event disabled in hw:
863 int x86_perf_event_set_period(struct perf_event *event)
865 struct hw_perf_event *hwc = &event->hw;
866 s64 left = local64_read(&hwc->period_left);
867 s64 period = hwc->sample_period;
868 int ret = 0, idx = hwc->idx;
870 if (idx == X86_PMC_IDX_FIXED_BTS)
874 * If we are way outside a reasonable range then just skip forward:
876 if (unlikely(left <= -period)) {
878 local64_set(&hwc->period_left, left);
879 hwc->last_period = period;
883 if (unlikely(left <= 0)) {
885 local64_set(&hwc->period_left, left);
886 hwc->last_period = period;
890 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
892 if (unlikely(left < 2))
895 if (left > x86_pmu.max_period)
896 left = x86_pmu.max_period;
898 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
901 * The hw event starts counting from this event offset,
902 * mark it to be able to extra future deltas:
904 local64_set(&hwc->prev_count, (u64)-left);
906 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
909 * Due to erratum on certan cpu we need
910 * a second write to be sure the register
911 * is updated properly
913 if (x86_pmu.perfctr_second_write) {
914 wrmsrl(hwc->event_base,
915 (u64)(-left) & x86_pmu.cntval_mask);
918 perf_event_update_userpage(event);
923 void x86_pmu_enable_event(struct perf_event *event)
925 if (__this_cpu_read(cpu_hw_events.enabled))
926 __x86_pmu_enable_event(&event->hw,
927 ARCH_PERFMON_EVENTSEL_ENABLE);
931 * Add a single event to the PMU.
933 * The event is added to the group of enabled events
934 * but only if it can be scehduled with existing events.
936 static int x86_pmu_add(struct perf_event *event, int flags)
938 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
939 struct hw_perf_event *hwc;
940 int assign[X86_PMC_IDX_MAX];
945 perf_pmu_disable(event->pmu);
947 ret = n = collect_events(cpuc, event, false);
951 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
952 if (!(flags & PERF_EF_START))
953 hwc->state |= PERF_HES_ARCH;
956 * If group events scheduling transaction was started,
957 * skip the schedulability test here, it will be performed
958 * at commit time (->commit_txn) as a whole
960 if (cpuc->group_flag & PERF_EVENT_TXN)
963 ret = x86_pmu.schedule_events(cpuc, n, assign);
967 * copy new assignment, now we know it is possible
968 * will be used by hw_perf_enable()
970 memcpy(cpuc->assign, assign, n*sizeof(int));
974 cpuc->n_added += n - n0;
975 cpuc->n_txn += n - n0;
979 perf_pmu_enable(event->pmu);
983 static void x86_pmu_start(struct perf_event *event, int flags)
985 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
986 int idx = event->hw.idx;
988 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
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.cpu_starting)
1213 x86_pmu.cpu_starting(cpu);
1217 kfree(cpuc->kfree_on_online);
1221 if (x86_pmu.cpu_dying)
1222 x86_pmu.cpu_dying(cpu);
1225 case CPU_UP_CANCELED:
1227 if (x86_pmu.cpu_dead)
1228 x86_pmu.cpu_dead(cpu);
1238 static void __init pmu_check_apic(void)
1244 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1245 pr_info("no hardware sampling interrupt available.\n");
1248 static int __init init_hw_perf_events(void)
1250 struct x86_pmu_quirk *quirk;
1251 struct event_constraint *c;
1254 pr_info("Performance Events: ");
1256 switch (boot_cpu_data.x86_vendor) {
1257 case X86_VENDOR_INTEL:
1258 err = intel_pmu_init();
1260 case X86_VENDOR_AMD:
1261 err = amd_pmu_init();
1267 pr_cont("no PMU driver, software events only.\n");
1273 /* sanity check that the hardware exists or is emulated */
1274 if (!check_hw_exists())
1277 pr_cont("%s PMU driver.\n", x86_pmu.name);
1279 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1282 if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1283 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1284 x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1285 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1287 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1289 if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1290 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1291 x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1292 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1295 x86_pmu.intel_ctrl |=
1296 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1298 perf_events_lapic_init();
1299 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1301 unconstrained = (struct event_constraint)
1302 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1303 0, x86_pmu.num_counters, 0);
1305 if (x86_pmu.event_constraints) {
1307 * event on fixed counter2 (REF_CYCLES) only works on this
1308 * counter, so do not extend mask to generic counters
1310 for_each_event_constraint(c, x86_pmu.event_constraints) {
1311 if (c->cmask != X86_RAW_EVENT_MASK
1312 || c->idxmsk64 == X86_PMC_MSK_FIXED_REF_CYCLES) {
1316 c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1317 c->weight += x86_pmu.num_counters;
1321 pr_info("... version: %d\n", x86_pmu.version);
1322 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1323 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1324 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1325 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1326 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1327 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1329 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1330 perf_cpu_notifier(x86_pmu_notifier);
1334 early_initcall(init_hw_perf_events);
1336 static inline void x86_pmu_read(struct perf_event *event)
1338 x86_perf_event_update(event);
1342 * Start group events scheduling transaction
1343 * Set the flag to make pmu::enable() not perform the
1344 * schedulability test, it will be performed at commit time
1346 static void x86_pmu_start_txn(struct pmu *pmu)
1348 perf_pmu_disable(pmu);
1349 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1350 __this_cpu_write(cpu_hw_events.n_txn, 0);
1354 * Stop group events scheduling transaction
1355 * Clear the flag and pmu::enable() will perform the
1356 * schedulability test.
1358 static void x86_pmu_cancel_txn(struct pmu *pmu)
1360 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1362 * Truncate the collected events.
1364 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1365 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1366 perf_pmu_enable(pmu);
1370 * Commit group events scheduling transaction
1371 * Perform the group schedulability test as a whole
1372 * Return 0 if success
1374 static int x86_pmu_commit_txn(struct pmu *pmu)
1376 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1377 int assign[X86_PMC_IDX_MAX];
1382 if (!x86_pmu_initialized())
1385 ret = x86_pmu.schedule_events(cpuc, n, assign);
1390 * copy new assignment, now we know it is possible
1391 * will be used by hw_perf_enable()
1393 memcpy(cpuc->assign, assign, n*sizeof(int));
1395 cpuc->group_flag &= ~PERF_EVENT_TXN;
1396 perf_pmu_enable(pmu);
1400 * a fake_cpuc is used to validate event groups. Due to
1401 * the extra reg logic, we need to also allocate a fake
1402 * per_core and per_cpu structure. Otherwise, group events
1403 * using extra reg may conflict without the kernel being
1404 * able to catch this when the last event gets added to
1407 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1409 kfree(cpuc->shared_regs);
1413 static struct cpu_hw_events *allocate_fake_cpuc(void)
1415 struct cpu_hw_events *cpuc;
1416 int cpu = raw_smp_processor_id();
1418 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1420 return ERR_PTR(-ENOMEM);
1422 /* only needed, if we have extra_regs */
1423 if (x86_pmu.extra_regs) {
1424 cpuc->shared_regs = allocate_shared_regs(cpu);
1425 if (!cpuc->shared_regs)
1430 free_fake_cpuc(cpuc);
1431 return ERR_PTR(-ENOMEM);
1435 * validate that we can schedule this event
1437 static int validate_event(struct perf_event *event)
1439 struct cpu_hw_events *fake_cpuc;
1440 struct event_constraint *c;
1443 fake_cpuc = allocate_fake_cpuc();
1444 if (IS_ERR(fake_cpuc))
1445 return PTR_ERR(fake_cpuc);
1447 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1449 if (!c || !c->weight)
1452 if (x86_pmu.put_event_constraints)
1453 x86_pmu.put_event_constraints(fake_cpuc, event);
1455 free_fake_cpuc(fake_cpuc);
1461 * validate a single event group
1463 * validation include:
1464 * - check events are compatible which each other
1465 * - events do not compete for the same counter
1466 * - number of events <= number of counters
1468 * validation ensures the group can be loaded onto the
1469 * PMU if it was the only group available.
1471 static int validate_group(struct perf_event *event)
1473 struct perf_event *leader = event->group_leader;
1474 struct cpu_hw_events *fake_cpuc;
1475 int ret = -EINVAL, n;
1477 fake_cpuc = allocate_fake_cpuc();
1478 if (IS_ERR(fake_cpuc))
1479 return PTR_ERR(fake_cpuc);
1481 * the event is not yet connected with its
1482 * siblings therefore we must first collect
1483 * existing siblings, then add the new event
1484 * before we can simulate the scheduling
1486 n = collect_events(fake_cpuc, leader, true);
1490 fake_cpuc->n_events = n;
1491 n = collect_events(fake_cpuc, event, false);
1495 fake_cpuc->n_events = n;
1497 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1500 free_fake_cpuc(fake_cpuc);
1504 static int x86_pmu_event_init(struct perf_event *event)
1509 switch (event->attr.type) {
1511 case PERF_TYPE_HARDWARE:
1512 case PERF_TYPE_HW_CACHE:
1519 err = __x86_pmu_event_init(event);
1522 * we temporarily connect event to its pmu
1523 * such that validate_group() can classify
1524 * it as an x86 event using is_x86_event()
1529 if (event->group_leader != event)
1530 err = validate_group(event);
1532 err = validate_event(event);
1538 event->destroy(event);
1544 static struct pmu pmu = {
1545 .pmu_enable = x86_pmu_enable,
1546 .pmu_disable = x86_pmu_disable,
1548 .event_init = x86_pmu_event_init,
1552 .start = x86_pmu_start,
1553 .stop = x86_pmu_stop,
1554 .read = x86_pmu_read,
1556 .start_txn = x86_pmu_start_txn,
1557 .cancel_txn = x86_pmu_cancel_txn,
1558 .commit_txn = x86_pmu_commit_txn,
1565 static int backtrace_stack(void *data, char *name)
1570 static void backtrace_address(void *data, unsigned long addr, int reliable)
1572 struct perf_callchain_entry *entry = data;
1574 perf_callchain_store(entry, addr);
1577 static const struct stacktrace_ops backtrace_ops = {
1578 .stack = backtrace_stack,
1579 .address = backtrace_address,
1580 .walk_stack = print_context_stack_bp,
1584 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1586 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1587 /* TODO: We don't support guest os callchain now */
1591 perf_callchain_store(entry, regs->ip);
1593 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1596 #ifdef CONFIG_COMPAT
1598 #include <asm/compat.h>
1601 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1603 /* 32-bit process in 64-bit kernel. */
1604 struct stack_frame_ia32 frame;
1605 const void __user *fp;
1607 if (!test_thread_flag(TIF_IA32))
1610 fp = compat_ptr(regs->bp);
1611 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1612 unsigned long bytes;
1613 frame.next_frame = 0;
1614 frame.return_address = 0;
1616 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1617 if (bytes != sizeof(frame))
1620 if (fp < compat_ptr(regs->sp))
1623 perf_callchain_store(entry, frame.return_address);
1624 fp = compat_ptr(frame.next_frame);
1630 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1637 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1639 struct stack_frame frame;
1640 const void __user *fp;
1642 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1643 /* TODO: We don't support guest os callchain now */
1647 fp = (void __user *)regs->bp;
1649 perf_callchain_store(entry, regs->ip);
1654 if (perf_callchain_user32(regs, entry))
1657 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1658 unsigned long bytes;
1659 frame.next_frame = NULL;
1660 frame.return_address = 0;
1662 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1663 if (bytes != sizeof(frame))
1666 if ((unsigned long)fp < regs->sp)
1669 perf_callchain_store(entry, frame.return_address);
1670 fp = frame.next_frame;
1674 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1678 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1679 ip = perf_guest_cbs->get_guest_ip();
1681 ip = instruction_pointer(regs);
1686 unsigned long perf_misc_flags(struct pt_regs *regs)
1690 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1691 if (perf_guest_cbs->is_user_mode())
1692 misc |= PERF_RECORD_MISC_GUEST_USER;
1694 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1696 if (user_mode(regs))
1697 misc |= PERF_RECORD_MISC_USER;
1699 misc |= PERF_RECORD_MISC_KERNEL;
1702 if (regs->flags & PERF_EFLAGS_EXACT)
1703 misc |= PERF_RECORD_MISC_EXACT_IP;
1708 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
1710 cap->version = x86_pmu.version;
1711 cap->num_counters_gp = x86_pmu.num_counters;
1712 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
1713 cap->bit_width_gp = x86_pmu.cntval_bits;
1714 cap->bit_width_fixed = x86_pmu.cntval_bits;
1715 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
1716 cap->events_mask_len = x86_pmu.events_mask_len;
1718 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);