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/highmem.h>
26 #include <linux/cpu.h>
27 #include <linux/bitops.h>
30 #include <asm/stacktrace.h>
32 #include <asm/compat.h>
36 #define wrmsrl(msr, val) \
38 trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
39 (unsigned long)(val)); \
40 native_write_msr((msr), (u32)((u64)(val)), \
41 (u32)((u64)(val) >> 32)); \
46 * best effort, GUP based copy_from_user() that assumes IRQ or NMI context
49 copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
51 unsigned long offset, addr = (unsigned long)from;
52 unsigned long size, len = 0;
58 ret = __get_user_pages_fast(addr, 1, 0, &page);
62 offset = addr & (PAGE_SIZE - 1);
63 size = min(PAGE_SIZE - offset, n - len);
65 map = kmap_atomic(page);
66 memcpy(to, map+offset, size);
79 struct event_constraint {
81 unsigned long idxmsk[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
90 int nb_id; /* NorthBridge id */
91 int refcnt; /* reference count */
92 struct perf_event *owners[X86_PMC_IDX_MAX];
93 struct event_constraint event_constraints[X86_PMC_IDX_MAX];
98 #define MAX_LBR_ENTRIES 16
100 struct cpu_hw_events {
102 * Generic x86 PMC bits
104 struct perf_event *events[X86_PMC_IDX_MAX]; /* in counter order */
105 unsigned long active_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
106 unsigned long running[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
112 int assign[X86_PMC_IDX_MAX]; /* event to counter assignment */
113 u64 tags[X86_PMC_IDX_MAX];
114 struct perf_event *event_list[X86_PMC_IDX_MAX]; /* in enabled order */
116 unsigned int group_flag;
119 * Intel DebugStore bits
121 struct debug_store *ds;
129 struct perf_branch_stack lbr_stack;
130 struct perf_branch_entry lbr_entries[MAX_LBR_ENTRIES];
133 * Intel percore register state.
134 * Coordinate shared resources between HT threads.
136 int percore_used; /* Used by this CPU? */
137 struct intel_percore *per_core;
142 struct amd_nb *amd_nb;
145 #define __EVENT_CONSTRAINT(c, n, m, w) {\
146 { .idxmsk64 = (n) }, \
152 #define EVENT_CONSTRAINT(c, n, m) \
153 __EVENT_CONSTRAINT(c, n, m, HWEIGHT(n))
156 * Constraint on the Event code.
158 #define INTEL_EVENT_CONSTRAINT(c, n) \
159 EVENT_CONSTRAINT(c, n, ARCH_PERFMON_EVENTSEL_EVENT)
162 * Constraint on the Event code + UMask + fixed-mask
164 * filter mask to validate fixed counter events.
165 * the following filters disqualify for fixed counters:
169 * The other filters are supported by fixed counters.
170 * The any-thread option is supported starting with v3.
172 #define FIXED_EVENT_CONSTRAINT(c, n) \
173 EVENT_CONSTRAINT(c, (1ULL << (32+n)), X86_RAW_EVENT_MASK)
176 * Constraint on the Event code + UMask
178 #define INTEL_UEVENT_CONSTRAINT(c, n) \
179 EVENT_CONSTRAINT(c, n, INTEL_ARCH_EVENT_MASK)
180 #define PEBS_EVENT_CONSTRAINT(c, n) \
181 INTEL_UEVENT_CONSTRAINT(c, n)
183 #define EVENT_CONSTRAINT_END \
184 EVENT_CONSTRAINT(0, 0, 0)
186 #define for_each_event_constraint(e, c) \
187 for ((e) = (c); (e)->weight; (e)++)
190 * Extra registers for specific events.
191 * Some events need large masks and require external MSRs.
192 * Define a mapping to these extra registers.
201 #define EVENT_EXTRA_REG(e, ms, m, vm) { \
204 .config_mask = (m), \
205 .valid_mask = (vm), \
207 #define INTEL_EVENT_EXTRA_REG(event, msr, vm) \
208 EVENT_EXTRA_REG(event, msr, ARCH_PERFMON_EVENTSEL_EVENT, vm)
209 #define EVENT_EXTRA_END EVENT_EXTRA_REG(0, 0, 0, 0)
211 union perf_capabilities {
215 u64 pebs_arch_reg : 1;
223 * struct x86_pmu - generic x86 pmu
227 * Generic x86 PMC bits
231 int (*handle_irq)(struct pt_regs *);
232 void (*disable_all)(void);
233 void (*enable_all)(int added);
234 void (*enable)(struct perf_event *);
235 void (*disable)(struct perf_event *);
236 int (*hw_config)(struct perf_event *event);
237 int (*schedule_events)(struct cpu_hw_events *cpuc, int n, int *assign);
240 u64 (*event_map)(int);
243 int num_counters_fixed;
248 struct event_constraint *
249 (*get_event_constraints)(struct cpu_hw_events *cpuc,
250 struct perf_event *event);
252 void (*put_event_constraints)(struct cpu_hw_events *cpuc,
253 struct perf_event *event);
254 struct event_constraint *event_constraints;
255 struct event_constraint *percore_constraints;
256 void (*quirks)(void);
257 int perfctr_second_write;
259 int (*cpu_prepare)(int cpu);
260 void (*cpu_starting)(int cpu);
261 void (*cpu_dying)(int cpu);
262 void (*cpu_dead)(int cpu);
265 * Intel Arch Perfmon v2+
268 union perf_capabilities intel_cap;
271 * Intel DebugStore bits
274 int bts_active, pebs_active;
275 int pebs_record_size;
276 void (*drain_pebs)(struct pt_regs *regs);
277 struct event_constraint *pebs_constraints;
282 unsigned long lbr_tos, lbr_from, lbr_to; /* MSR base regs */
283 int lbr_nr; /* hardware stack size */
286 * Extra registers for events
288 struct extra_reg *extra_regs;
291 static struct x86_pmu x86_pmu __read_mostly;
293 static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
297 static int x86_perf_event_set_period(struct perf_event *event);
300 * Generalized hw caching related hw_event table, filled
301 * in on a per model basis. A value of 0 means
302 * 'not supported', -1 means 'hw_event makes no sense on
303 * this CPU', any other value means the raw hw_event
307 #define C(x) PERF_COUNT_HW_CACHE_##x
309 static u64 __read_mostly hw_cache_event_ids
310 [PERF_COUNT_HW_CACHE_MAX]
311 [PERF_COUNT_HW_CACHE_OP_MAX]
312 [PERF_COUNT_HW_CACHE_RESULT_MAX];
313 static u64 __read_mostly hw_cache_extra_regs
314 [PERF_COUNT_HW_CACHE_MAX]
315 [PERF_COUNT_HW_CACHE_OP_MAX]
316 [PERF_COUNT_HW_CACHE_RESULT_MAX];
319 * Propagate event elapsed time into the generic event.
320 * Can only be executed on the CPU where the event is active.
321 * Returns the delta events processed.
324 x86_perf_event_update(struct perf_event *event)
326 struct hw_perf_event *hwc = &event->hw;
327 int shift = 64 - x86_pmu.cntval_bits;
328 u64 prev_raw_count, new_raw_count;
332 if (idx == X86_PMC_IDX_FIXED_BTS)
336 * Careful: an NMI might modify the previous event value.
338 * Our tactic to handle this is to first atomically read and
339 * exchange a new raw count - then add that new-prev delta
340 * count to the generic event atomically:
343 prev_raw_count = local64_read(&hwc->prev_count);
344 rdmsrl(hwc->event_base, new_raw_count);
346 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
347 new_raw_count) != prev_raw_count)
351 * Now we have the new raw value and have updated the prev
352 * timestamp already. We can now calculate the elapsed delta
353 * (event-)time and add that to the generic event.
355 * Careful, not all hw sign-extends above the physical width
358 delta = (new_raw_count << shift) - (prev_raw_count << shift);
361 local64_add(delta, &event->count);
362 local64_sub(delta, &hwc->period_left);
364 return new_raw_count;
367 /* using X86_FEATURE_PERFCTR_CORE to later implement ALTERNATIVE() here */
368 static inline int x86_pmu_addr_offset(int index)
370 if (boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
375 static inline unsigned int x86_pmu_config_addr(int index)
377 return x86_pmu.eventsel + x86_pmu_addr_offset(index);
380 static inline unsigned int x86_pmu_event_addr(int index)
382 return x86_pmu.perfctr + x86_pmu_addr_offset(index);
386 * Find and validate any extra registers to set up.
388 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
390 struct extra_reg *er;
392 event->hw.extra_reg = 0;
393 event->hw.extra_config = 0;
395 if (!x86_pmu.extra_regs)
398 for (er = x86_pmu.extra_regs; er->msr; er++) {
399 if (er->event != (config & er->config_mask))
401 if (event->attr.config1 & ~er->valid_mask)
403 event->hw.extra_reg = er->msr;
404 event->hw.extra_config = event->attr.config1;
410 static atomic_t active_events;
411 static DEFINE_MUTEX(pmc_reserve_mutex);
413 #ifdef CONFIG_X86_LOCAL_APIC
415 static bool reserve_pmc_hardware(void)
419 for (i = 0; i < x86_pmu.num_counters; i++) {
420 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
424 for (i = 0; i < x86_pmu.num_counters; i++) {
425 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
432 for (i--; i >= 0; i--)
433 release_evntsel_nmi(x86_pmu_config_addr(i));
435 i = x86_pmu.num_counters;
438 for (i--; i >= 0; i--)
439 release_perfctr_nmi(x86_pmu_event_addr(i));
444 static void release_pmc_hardware(void)
448 for (i = 0; i < x86_pmu.num_counters; i++) {
449 release_perfctr_nmi(x86_pmu_event_addr(i));
450 release_evntsel_nmi(x86_pmu_config_addr(i));
456 static bool reserve_pmc_hardware(void) { return true; }
457 static void release_pmc_hardware(void) {}
461 static bool check_hw_exists(void)
463 u64 val, val_new = 0;
467 * Check to see if the BIOS enabled any of the counters, if so
470 for (i = 0; i < x86_pmu.num_counters; i++) {
471 reg = x86_pmu_config_addr(i);
472 ret = rdmsrl_safe(reg, &val);
475 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
479 if (x86_pmu.num_counters_fixed) {
480 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
481 ret = rdmsrl_safe(reg, &val);
484 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
485 if (val & (0x03 << i*4))
491 * Now write a value and read it back to see if it matches,
492 * this is needed to detect certain hardware emulators (qemu/kvm)
493 * that don't trap on the MSR access and always return 0s.
496 ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
497 ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
498 if (ret || val != val_new)
504 printk(KERN_CONT "Broken BIOS detected, using software events only.\n");
505 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
509 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
513 static void reserve_ds_buffers(void);
514 static void release_ds_buffers(void);
516 static void hw_perf_event_destroy(struct perf_event *event)
518 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
519 release_pmc_hardware();
520 release_ds_buffers();
521 mutex_unlock(&pmc_reserve_mutex);
525 static inline int x86_pmu_initialized(void)
527 return x86_pmu.handle_irq != NULL;
531 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
533 struct perf_event_attr *attr = &event->attr;
534 unsigned int cache_type, cache_op, cache_result;
537 config = attr->config;
539 cache_type = (config >> 0) & 0xff;
540 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
543 cache_op = (config >> 8) & 0xff;
544 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
547 cache_result = (config >> 16) & 0xff;
548 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
551 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
560 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
561 return x86_pmu_extra_regs(val, event);
564 static int x86_setup_perfctr(struct perf_event *event)
566 struct perf_event_attr *attr = &event->attr;
567 struct hw_perf_event *hwc = &event->hw;
570 if (!is_sampling_event(event)) {
571 hwc->sample_period = x86_pmu.max_period;
572 hwc->last_period = hwc->sample_period;
573 local64_set(&hwc->period_left, hwc->sample_period);
576 * If we have a PMU initialized but no APIC
577 * interrupts, we cannot sample hardware
578 * events (user-space has to fall back and
579 * sample via a hrtimer based software event):
585 if (attr->type == PERF_TYPE_RAW)
586 return x86_pmu_extra_regs(event->attr.config, event);
588 if (attr->type == PERF_TYPE_HW_CACHE)
589 return set_ext_hw_attr(hwc, event);
591 if (attr->config >= x86_pmu.max_events)
597 config = x86_pmu.event_map(attr->config);
608 if ((attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS) &&
609 (hwc->sample_period == 1)) {
610 /* BTS is not supported by this architecture. */
611 if (!x86_pmu.bts_active)
614 /* BTS is currently only allowed for user-mode. */
615 if (!attr->exclude_kernel)
619 hwc->config |= config;
624 static int x86_pmu_hw_config(struct perf_event *event)
626 if (event->attr.precise_ip) {
629 /* Support for constant skid */
630 if (x86_pmu.pebs_active) {
633 /* Support for IP fixup */
638 if (event->attr.precise_ip > precise)
644 * (keep 'enabled' bit clear for now)
646 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
649 * Count user and OS events unless requested not to
651 if (!event->attr.exclude_user)
652 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
653 if (!event->attr.exclude_kernel)
654 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
656 if (event->attr.type == PERF_TYPE_RAW)
657 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
659 return x86_setup_perfctr(event);
663 * Setup the hardware configuration for a given attr_type
665 static int __x86_pmu_event_init(struct perf_event *event)
669 if (!x86_pmu_initialized())
673 if (!atomic_inc_not_zero(&active_events)) {
674 mutex_lock(&pmc_reserve_mutex);
675 if (atomic_read(&active_events) == 0) {
676 if (!reserve_pmc_hardware())
679 reserve_ds_buffers();
682 atomic_inc(&active_events);
683 mutex_unlock(&pmc_reserve_mutex);
688 event->destroy = hw_perf_event_destroy;
691 event->hw.last_cpu = -1;
692 event->hw.last_tag = ~0ULL;
694 return x86_pmu.hw_config(event);
697 static void x86_pmu_disable_all(void)
699 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
702 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
705 if (!test_bit(idx, cpuc->active_mask))
707 rdmsrl(x86_pmu_config_addr(idx), val);
708 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
710 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
711 wrmsrl(x86_pmu_config_addr(idx), val);
715 static void x86_pmu_disable(struct pmu *pmu)
717 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
719 if (!x86_pmu_initialized())
729 x86_pmu.disable_all();
732 static inline void __x86_pmu_enable_event(struct hw_perf_event *hwc,
736 wrmsrl(hwc->extra_reg, hwc->extra_config);
737 wrmsrl(hwc->config_base, hwc->config | enable_mask);
740 static void x86_pmu_enable_all(int added)
742 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
745 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
746 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
748 if (!test_bit(idx, cpuc->active_mask))
751 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
755 static struct pmu pmu;
757 static inline int is_x86_event(struct perf_event *event)
759 return event->pmu == &pmu;
762 static int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
764 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
765 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
766 int i, j, w, wmax, num = 0;
767 struct hw_perf_event *hwc;
769 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
771 for (i = 0; i < n; i++) {
772 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
777 * fastpath, try to reuse previous register
779 for (i = 0; i < n; i++) {
780 hwc = &cpuc->event_list[i]->hw;
787 /* constraint still honored */
788 if (!test_bit(hwc->idx, c->idxmsk))
791 /* not already used */
792 if (test_bit(hwc->idx, used_mask))
795 __set_bit(hwc->idx, used_mask);
797 assign[i] = hwc->idx;
806 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
809 * weight = number of possible counters
811 * 1 = most constrained, only works on one counter
812 * wmax = least constrained, works on any counter
814 * assign events to counters starting with most
815 * constrained events.
817 wmax = x86_pmu.num_counters;
820 * when fixed event counters are present,
821 * wmax is incremented by 1 to account
822 * for one more choice
824 if (x86_pmu.num_counters_fixed)
827 for (w = 1, num = n; num && w <= wmax; w++) {
829 for (i = 0; num && i < n; i++) {
831 hwc = &cpuc->event_list[i]->hw;
836 for_each_set_bit(j, c->idxmsk, X86_PMC_IDX_MAX) {
837 if (!test_bit(j, used_mask))
841 if (j == X86_PMC_IDX_MAX)
844 __set_bit(j, used_mask);
853 * scheduling failed or is just a simulation,
854 * free resources if necessary
856 if (!assign || num) {
857 for (i = 0; i < n; i++) {
858 if (x86_pmu.put_event_constraints)
859 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
862 return num ? -ENOSPC : 0;
866 * dogrp: true if must collect siblings events (group)
867 * returns total number of events and error code
869 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
871 struct perf_event *event;
874 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
876 /* current number of events already accepted */
879 if (is_x86_event(leader)) {
882 cpuc->event_list[n] = leader;
888 list_for_each_entry(event, &leader->sibling_list, group_entry) {
889 if (!is_x86_event(event) ||
890 event->state <= PERF_EVENT_STATE_OFF)
896 cpuc->event_list[n] = event;
902 static inline void x86_assign_hw_event(struct perf_event *event,
903 struct cpu_hw_events *cpuc, int i)
905 struct hw_perf_event *hwc = &event->hw;
907 hwc->idx = cpuc->assign[i];
908 hwc->last_cpu = smp_processor_id();
909 hwc->last_tag = ++cpuc->tags[i];
911 if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
912 hwc->config_base = 0;
914 } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
915 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
916 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0;
918 hwc->config_base = x86_pmu_config_addr(hwc->idx);
919 hwc->event_base = x86_pmu_event_addr(hwc->idx);
923 static inline int match_prev_assignment(struct hw_perf_event *hwc,
924 struct cpu_hw_events *cpuc,
927 return hwc->idx == cpuc->assign[i] &&
928 hwc->last_cpu == smp_processor_id() &&
929 hwc->last_tag == cpuc->tags[i];
932 static void x86_pmu_start(struct perf_event *event, int flags);
933 static void x86_pmu_stop(struct perf_event *event, int flags);
935 static void x86_pmu_enable(struct pmu *pmu)
937 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
938 struct perf_event *event;
939 struct hw_perf_event *hwc;
940 int i, added = cpuc->n_added;
942 if (!x86_pmu_initialized())
949 int n_running = cpuc->n_events - cpuc->n_added;
951 * apply assignment obtained either from
952 * hw_perf_group_sched_in() or x86_pmu_enable()
954 * step1: save events moving to new counters
955 * step2: reprogram moved events into new counters
957 for (i = 0; i < n_running; i++) {
958 event = cpuc->event_list[i];
962 * we can avoid reprogramming counter if:
963 * - assigned same counter as last time
964 * - running on same CPU as last time
965 * - no other event has used the counter since
967 if (hwc->idx == -1 ||
968 match_prev_assignment(hwc, cpuc, i))
972 * Ensure we don't accidentally enable a stopped
973 * counter simply because we rescheduled.
975 if (hwc->state & PERF_HES_STOPPED)
976 hwc->state |= PERF_HES_ARCH;
978 x86_pmu_stop(event, PERF_EF_UPDATE);
981 for (i = 0; i < cpuc->n_events; i++) {
982 event = cpuc->event_list[i];
985 if (!match_prev_assignment(hwc, cpuc, i))
986 x86_assign_hw_event(event, cpuc, i);
987 else if (i < n_running)
990 if (hwc->state & PERF_HES_ARCH)
993 x86_pmu_start(event, PERF_EF_RELOAD);
996 perf_events_lapic_init();
1002 x86_pmu.enable_all(added);
1005 static inline void x86_pmu_disable_event(struct perf_event *event)
1007 struct hw_perf_event *hwc = &event->hw;
1009 wrmsrl(hwc->config_base, hwc->config);
1012 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1015 * Set the next IRQ period, based on the hwc->period_left value.
1016 * To be called with the event disabled in hw:
1019 x86_perf_event_set_period(struct perf_event *event)
1021 struct hw_perf_event *hwc = &event->hw;
1022 s64 left = local64_read(&hwc->period_left);
1023 s64 period = hwc->sample_period;
1024 int ret = 0, idx = hwc->idx;
1026 if (idx == X86_PMC_IDX_FIXED_BTS)
1030 * If we are way outside a reasonable range then just skip forward:
1032 if (unlikely(left <= -period)) {
1034 local64_set(&hwc->period_left, left);
1035 hwc->last_period = period;
1039 if (unlikely(left <= 0)) {
1041 local64_set(&hwc->period_left, left);
1042 hwc->last_period = period;
1046 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1048 if (unlikely(left < 2))
1051 if (left > x86_pmu.max_period)
1052 left = x86_pmu.max_period;
1054 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1057 * The hw event starts counting from this event offset,
1058 * mark it to be able to extra future deltas:
1060 local64_set(&hwc->prev_count, (u64)-left);
1062 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1065 * Due to erratum on certan cpu we need
1066 * a second write to be sure the register
1067 * is updated properly
1069 if (x86_pmu.perfctr_second_write) {
1070 wrmsrl(hwc->event_base,
1071 (u64)(-left) & x86_pmu.cntval_mask);
1074 perf_event_update_userpage(event);
1079 static void x86_pmu_enable_event(struct perf_event *event)
1081 if (__this_cpu_read(cpu_hw_events.enabled))
1082 __x86_pmu_enable_event(&event->hw,
1083 ARCH_PERFMON_EVENTSEL_ENABLE);
1087 * Add a single event to the PMU.
1089 * The event is added to the group of enabled events
1090 * but only if it can be scehduled with existing events.
1092 static int x86_pmu_add(struct perf_event *event, int flags)
1094 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1095 struct hw_perf_event *hwc;
1096 int assign[X86_PMC_IDX_MAX];
1101 perf_pmu_disable(event->pmu);
1102 n0 = cpuc->n_events;
1103 ret = n = collect_events(cpuc, event, false);
1107 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1108 if (!(flags & PERF_EF_START))
1109 hwc->state |= PERF_HES_ARCH;
1112 * If group events scheduling transaction was started,
1113 * skip the schedulability test here, it will be peformed
1114 * at commit time (->commit_txn) as a whole
1116 if (cpuc->group_flag & PERF_EVENT_TXN)
1119 ret = x86_pmu.schedule_events(cpuc, n, assign);
1123 * copy new assignment, now we know it is possible
1124 * will be used by hw_perf_enable()
1126 memcpy(cpuc->assign, assign, n*sizeof(int));
1130 cpuc->n_added += n - n0;
1131 cpuc->n_txn += n - n0;
1135 perf_pmu_enable(event->pmu);
1139 static void x86_pmu_start(struct perf_event *event, int flags)
1141 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1142 int idx = event->hw.idx;
1144 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1147 if (WARN_ON_ONCE(idx == -1))
1150 if (flags & PERF_EF_RELOAD) {
1151 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1152 x86_perf_event_set_period(event);
1155 event->hw.state = 0;
1157 cpuc->events[idx] = event;
1158 __set_bit(idx, cpuc->active_mask);
1159 __set_bit(idx, cpuc->running);
1160 x86_pmu.enable(event);
1161 perf_event_update_userpage(event);
1164 void perf_event_print_debug(void)
1166 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1168 struct cpu_hw_events *cpuc;
1169 unsigned long flags;
1172 if (!x86_pmu.num_counters)
1175 local_irq_save(flags);
1177 cpu = smp_processor_id();
1178 cpuc = &per_cpu(cpu_hw_events, cpu);
1180 if (x86_pmu.version >= 2) {
1181 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1182 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1183 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1184 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1185 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1188 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1189 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1190 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1191 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1192 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1194 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1196 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1197 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1198 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1200 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1202 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1203 cpu, idx, pmc_ctrl);
1204 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1205 cpu, idx, pmc_count);
1206 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1207 cpu, idx, prev_left);
1209 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1210 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1212 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1213 cpu, idx, pmc_count);
1215 local_irq_restore(flags);
1218 static void x86_pmu_stop(struct perf_event *event, int flags)
1220 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1221 struct hw_perf_event *hwc = &event->hw;
1223 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1224 x86_pmu.disable(event);
1225 cpuc->events[hwc->idx] = NULL;
1226 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1227 hwc->state |= PERF_HES_STOPPED;
1230 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1232 * Drain the remaining delta count out of a event
1233 * that we are disabling:
1235 x86_perf_event_update(event);
1236 hwc->state |= PERF_HES_UPTODATE;
1240 static void x86_pmu_del(struct perf_event *event, int flags)
1242 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1246 * If we're called during a txn, we don't need to do anything.
1247 * The events never got scheduled and ->cancel_txn will truncate
1250 if (cpuc->group_flag & PERF_EVENT_TXN)
1253 x86_pmu_stop(event, PERF_EF_UPDATE);
1255 for (i = 0; i < cpuc->n_events; i++) {
1256 if (event == cpuc->event_list[i]) {
1258 if (x86_pmu.put_event_constraints)
1259 x86_pmu.put_event_constraints(cpuc, event);
1261 while (++i < cpuc->n_events)
1262 cpuc->event_list[i-1] = cpuc->event_list[i];
1268 perf_event_update_userpage(event);
1271 static int x86_pmu_handle_irq(struct pt_regs *regs)
1273 struct perf_sample_data data;
1274 struct cpu_hw_events *cpuc;
1275 struct perf_event *event;
1276 int idx, handled = 0;
1279 perf_sample_data_init(&data, 0);
1281 cpuc = &__get_cpu_var(cpu_hw_events);
1283 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1284 if (!test_bit(idx, cpuc->active_mask)) {
1286 * Though we deactivated the counter some cpus
1287 * might still deliver spurious interrupts still
1288 * in flight. Catch them:
1290 if (__test_and_clear_bit(idx, cpuc->running))
1295 event = cpuc->events[idx];
1297 val = x86_perf_event_update(event);
1298 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1305 data.period = event->hw.last_period;
1307 if (!x86_perf_event_set_period(event))
1310 if (perf_event_overflow(event, 1, &data, regs))
1311 x86_pmu_stop(event, 0);
1315 inc_irq_stat(apic_perf_irqs);
1320 void perf_events_lapic_init(void)
1322 if (!x86_pmu.apic || !x86_pmu_initialized())
1326 * Always use NMI for PMU
1328 apic_write(APIC_LVTPC, APIC_DM_NMI);
1331 struct pmu_nmi_state {
1332 unsigned int marked;
1336 static DEFINE_PER_CPU(struct pmu_nmi_state, pmu_nmi);
1338 static int __kprobes
1339 perf_event_nmi_handler(struct notifier_block *self,
1340 unsigned long cmd, void *__args)
1342 struct die_args *args = __args;
1343 unsigned int this_nmi;
1346 if (!atomic_read(&active_events))
1352 case DIE_NMIUNKNOWN:
1353 this_nmi = percpu_read(irq_stat.__nmi_count);
1354 if (this_nmi != __this_cpu_read(pmu_nmi.marked))
1355 /* let the kernel handle the unknown nmi */
1358 * This one is a PMU back-to-back nmi. Two events
1359 * trigger 'simultaneously' raising two back-to-back
1360 * NMIs. If the first NMI handles both, the latter
1361 * will be empty and daze the CPU. So, we drop it to
1362 * avoid false-positive 'unknown nmi' messages.
1369 apic_write(APIC_LVTPC, APIC_DM_NMI);
1371 handled = x86_pmu.handle_irq(args->regs);
1375 this_nmi = percpu_read(irq_stat.__nmi_count);
1376 if ((handled > 1) ||
1377 /* the next nmi could be a back-to-back nmi */
1378 ((__this_cpu_read(pmu_nmi.marked) == this_nmi) &&
1379 (__this_cpu_read(pmu_nmi.handled) > 1))) {
1381 * We could have two subsequent back-to-back nmis: The
1382 * first handles more than one counter, the 2nd
1383 * handles only one counter and the 3rd handles no
1386 * This is the 2nd nmi because the previous was
1387 * handling more than one counter. We will mark the
1388 * next (3rd) and then drop it if unhandled.
1390 __this_cpu_write(pmu_nmi.marked, this_nmi + 1);
1391 __this_cpu_write(pmu_nmi.handled, handled);
1397 static __read_mostly struct notifier_block perf_event_nmi_notifier = {
1398 .notifier_call = perf_event_nmi_handler,
1400 .priority = NMI_LOCAL_LOW_PRIOR,
1403 static struct event_constraint unconstrained;
1404 static struct event_constraint emptyconstraint;
1406 static struct event_constraint *
1407 x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
1409 struct event_constraint *c;
1411 if (x86_pmu.event_constraints) {
1412 for_each_event_constraint(c, x86_pmu.event_constraints) {
1413 if ((event->hw.config & c->cmask) == c->code)
1418 return &unconstrained;
1421 #include "perf_event_amd.c"
1422 #include "perf_event_p6.c"
1423 #include "perf_event_p4.c"
1424 #include "perf_event_intel_lbr.c"
1425 #include "perf_event_intel_ds.c"
1426 #include "perf_event_intel.c"
1428 static int __cpuinit
1429 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1431 unsigned int cpu = (long)hcpu;
1432 int ret = NOTIFY_OK;
1434 switch (action & ~CPU_TASKS_FROZEN) {
1435 case CPU_UP_PREPARE:
1436 if (x86_pmu.cpu_prepare)
1437 ret = x86_pmu.cpu_prepare(cpu);
1441 if (x86_pmu.cpu_starting)
1442 x86_pmu.cpu_starting(cpu);
1446 if (x86_pmu.cpu_dying)
1447 x86_pmu.cpu_dying(cpu);
1450 case CPU_UP_CANCELED:
1452 if (x86_pmu.cpu_dead)
1453 x86_pmu.cpu_dead(cpu);
1463 static void __init pmu_check_apic(void)
1469 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1470 pr_info("no hardware sampling interrupt available.\n");
1473 static int __init init_hw_perf_events(void)
1475 struct event_constraint *c;
1478 pr_info("Performance Events: ");
1480 switch (boot_cpu_data.x86_vendor) {
1481 case X86_VENDOR_INTEL:
1482 err = intel_pmu_init();
1484 case X86_VENDOR_AMD:
1485 err = amd_pmu_init();
1491 pr_cont("no PMU driver, software events only.\n");
1497 /* sanity check that the hardware exists or is emulated */
1498 if (!check_hw_exists())
1501 pr_cont("%s PMU driver.\n", x86_pmu.name);
1506 if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1507 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1508 x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1509 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1511 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1513 if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1514 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1515 x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1516 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1519 x86_pmu.intel_ctrl |=
1520 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1522 perf_events_lapic_init();
1523 register_die_notifier(&perf_event_nmi_notifier);
1525 unconstrained = (struct event_constraint)
1526 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1527 0, x86_pmu.num_counters);
1529 if (x86_pmu.event_constraints) {
1530 for_each_event_constraint(c, x86_pmu.event_constraints) {
1531 if (c->cmask != X86_RAW_EVENT_MASK)
1534 c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1535 c->weight += x86_pmu.num_counters;
1539 pr_info("... version: %d\n", x86_pmu.version);
1540 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1541 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1542 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1543 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1544 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1545 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1547 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1548 perf_cpu_notifier(x86_pmu_notifier);
1552 early_initcall(init_hw_perf_events);
1554 static inline void x86_pmu_read(struct perf_event *event)
1556 x86_perf_event_update(event);
1560 * Start group events scheduling transaction
1561 * Set the flag to make pmu::enable() not perform the
1562 * schedulability test, it will be performed at commit time
1564 static void x86_pmu_start_txn(struct pmu *pmu)
1566 perf_pmu_disable(pmu);
1567 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1568 __this_cpu_write(cpu_hw_events.n_txn, 0);
1572 * Stop group events scheduling transaction
1573 * Clear the flag and pmu::enable() will perform the
1574 * schedulability test.
1576 static void x86_pmu_cancel_txn(struct pmu *pmu)
1578 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1580 * Truncate the collected events.
1582 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1583 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1584 perf_pmu_enable(pmu);
1588 * Commit group events scheduling transaction
1589 * Perform the group schedulability test as a whole
1590 * Return 0 if success
1592 static int x86_pmu_commit_txn(struct pmu *pmu)
1594 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1595 int assign[X86_PMC_IDX_MAX];
1600 if (!x86_pmu_initialized())
1603 ret = x86_pmu.schedule_events(cpuc, n, assign);
1608 * copy new assignment, now we know it is possible
1609 * will be used by hw_perf_enable()
1611 memcpy(cpuc->assign, assign, n*sizeof(int));
1613 cpuc->group_flag &= ~PERF_EVENT_TXN;
1614 perf_pmu_enable(pmu);
1619 * validate that we can schedule this event
1621 static int validate_event(struct perf_event *event)
1623 struct cpu_hw_events *fake_cpuc;
1624 struct event_constraint *c;
1627 fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1631 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1633 if (!c || !c->weight)
1636 if (x86_pmu.put_event_constraints)
1637 x86_pmu.put_event_constraints(fake_cpuc, event);
1645 * validate a single event group
1647 * validation include:
1648 * - check events are compatible which each other
1649 * - events do not compete for the same counter
1650 * - number of events <= number of counters
1652 * validation ensures the group can be loaded onto the
1653 * PMU if it was the only group available.
1655 static int validate_group(struct perf_event *event)
1657 struct perf_event *leader = event->group_leader;
1658 struct cpu_hw_events *fake_cpuc;
1662 fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1667 * the event is not yet connected with its
1668 * siblings therefore we must first collect
1669 * existing siblings, then add the new event
1670 * before we can simulate the scheduling
1673 n = collect_events(fake_cpuc, leader, true);
1677 fake_cpuc->n_events = n;
1678 n = collect_events(fake_cpuc, event, false);
1682 fake_cpuc->n_events = n;
1684 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1692 static int x86_pmu_event_init(struct perf_event *event)
1697 switch (event->attr.type) {
1699 case PERF_TYPE_HARDWARE:
1700 case PERF_TYPE_HW_CACHE:
1707 err = __x86_pmu_event_init(event);
1710 * we temporarily connect event to its pmu
1711 * such that validate_group() can classify
1712 * it as an x86 event using is_x86_event()
1717 if (event->group_leader != event)
1718 err = validate_group(event);
1720 err = validate_event(event);
1726 event->destroy(event);
1732 static struct pmu pmu = {
1733 .pmu_enable = x86_pmu_enable,
1734 .pmu_disable = x86_pmu_disable,
1736 .event_init = x86_pmu_event_init,
1740 .start = x86_pmu_start,
1741 .stop = x86_pmu_stop,
1742 .read = x86_pmu_read,
1744 .start_txn = x86_pmu_start_txn,
1745 .cancel_txn = x86_pmu_cancel_txn,
1746 .commit_txn = x86_pmu_commit_txn,
1754 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1756 /* Ignore warnings */
1759 static void backtrace_warning(void *data, char *msg)
1761 /* Ignore warnings */
1764 static int backtrace_stack(void *data, char *name)
1769 static void backtrace_address(void *data, unsigned long addr, int reliable)
1771 struct perf_callchain_entry *entry = data;
1773 perf_callchain_store(entry, addr);
1776 static const struct stacktrace_ops backtrace_ops = {
1777 .warning = backtrace_warning,
1778 .warning_symbol = backtrace_warning_symbol,
1779 .stack = backtrace_stack,
1780 .address = backtrace_address,
1781 .walk_stack = print_context_stack_bp,
1785 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1787 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1788 /* TODO: We don't support guest os callchain now */
1792 perf_callchain_store(entry, regs->ip);
1794 dump_trace(NULL, regs, NULL, &backtrace_ops, entry);
1797 #ifdef CONFIG_COMPAT
1799 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1801 /* 32-bit process in 64-bit kernel. */
1802 struct stack_frame_ia32 frame;
1803 const void __user *fp;
1805 if (!test_thread_flag(TIF_IA32))
1808 fp = compat_ptr(regs->bp);
1809 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1810 unsigned long bytes;
1811 frame.next_frame = 0;
1812 frame.return_address = 0;
1814 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1815 if (bytes != sizeof(frame))
1818 if (fp < compat_ptr(regs->sp))
1821 perf_callchain_store(entry, frame.return_address);
1822 fp = compat_ptr(frame.next_frame);
1828 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1835 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1837 struct stack_frame frame;
1838 const void __user *fp;
1840 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1841 /* TODO: We don't support guest os callchain now */
1845 fp = (void __user *)regs->bp;
1847 perf_callchain_store(entry, regs->ip);
1849 if (perf_callchain_user32(regs, entry))
1852 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1853 unsigned long bytes;
1854 frame.next_frame = NULL;
1855 frame.return_address = 0;
1857 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1858 if (bytes != sizeof(frame))
1861 if ((unsigned long)fp < regs->sp)
1864 perf_callchain_store(entry, frame.return_address);
1865 fp = frame.next_frame;
1869 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1873 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1874 ip = perf_guest_cbs->get_guest_ip();
1876 ip = instruction_pointer(regs);
1881 unsigned long perf_misc_flags(struct pt_regs *regs)
1885 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1886 if (perf_guest_cbs->is_user_mode())
1887 misc |= PERF_RECORD_MISC_GUEST_USER;
1889 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1891 if (user_mode(regs))
1892 misc |= PERF_RECORD_MISC_USER;
1894 misc |= PERF_RECORD_MISC_KERNEL;
1897 if (regs->flags & PERF_EFLAGS_EXACT)
1898 misc |= PERF_RECORD_MISC_EXACT_IP;