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>
37 #define wrmsrl(msr, val) \
39 trace_printk("wrmsrl(%lx, %lx)\n", (unsigned long)(msr),\
40 (unsigned long)(val)); \
41 native_write_msr((msr), (u32)((u64)(val)), \
42 (u32)((u64)(val) >> 32)); \
47 * best effort, GUP based copy_from_user() that assumes IRQ or NMI context
50 copy_from_user_nmi(void *to, const void __user *from, unsigned long n)
52 unsigned long offset, addr = (unsigned long)from;
53 unsigned long size, len = 0;
59 ret = __get_user_pages_fast(addr, 1, 0, &page);
63 offset = addr & (PAGE_SIZE - 1);
64 size = min(PAGE_SIZE - offset, n - len);
66 map = kmap_atomic(page);
67 memcpy(to, map+offset, size);
80 struct event_constraint {
82 unsigned long idxmsk[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
91 int nb_id; /* NorthBridge id */
92 int refcnt; /* reference count */
93 struct perf_event *owners[X86_PMC_IDX_MAX];
94 struct event_constraint event_constraints[X86_PMC_IDX_MAX];
99 #define MAX_LBR_ENTRIES 16
101 struct cpu_hw_events {
103 * Generic x86 PMC bits
105 struct perf_event *events[X86_PMC_IDX_MAX]; /* in counter order */
106 unsigned long active_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
107 unsigned long running[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
113 int assign[X86_PMC_IDX_MAX]; /* event to counter assignment */
114 u64 tags[X86_PMC_IDX_MAX];
115 struct perf_event *event_list[X86_PMC_IDX_MAX]; /* in enabled order */
117 unsigned int group_flag;
120 * Intel DebugStore bits
122 struct debug_store *ds;
130 struct perf_branch_stack lbr_stack;
131 struct perf_branch_entry lbr_entries[MAX_LBR_ENTRIES];
134 * Intel percore register state.
135 * Coordinate shared resources between HT threads.
137 int percore_used; /* Used by this CPU? */
138 struct intel_percore *per_core;
143 struct amd_nb *amd_nb;
146 #define __EVENT_CONSTRAINT(c, n, m, w) {\
147 { .idxmsk64 = (n) }, \
153 #define EVENT_CONSTRAINT(c, n, m) \
154 __EVENT_CONSTRAINT(c, n, m, HWEIGHT(n))
157 * Constraint on the Event code.
159 #define INTEL_EVENT_CONSTRAINT(c, n) \
160 EVENT_CONSTRAINT(c, n, ARCH_PERFMON_EVENTSEL_EVENT)
163 * Constraint on the Event code + UMask + fixed-mask
165 * filter mask to validate fixed counter events.
166 * the following filters disqualify for fixed counters:
170 * The other filters are supported by fixed counters.
171 * The any-thread option is supported starting with v3.
173 #define FIXED_EVENT_CONSTRAINT(c, n) \
174 EVENT_CONSTRAINT(c, (1ULL << (32+n)), X86_RAW_EVENT_MASK)
177 * Constraint on the Event code + UMask
179 #define INTEL_UEVENT_CONSTRAINT(c, n) \
180 EVENT_CONSTRAINT(c, n, INTEL_ARCH_EVENT_MASK)
182 #define EVENT_CONSTRAINT_END \
183 EVENT_CONSTRAINT(0, 0, 0)
185 #define for_each_event_constraint(e, c) \
186 for ((e) = (c); (e)->weight; (e)++)
189 * Extra registers for specific events.
190 * Some events need large masks and require external MSRs.
191 * Define a mapping to these extra registers.
200 #define EVENT_EXTRA_REG(e, ms, m, vm) { \
203 .config_mask = (m), \
204 .valid_mask = (vm), \
206 #define INTEL_EVENT_EXTRA_REG(event, msr, vm) \
207 EVENT_EXTRA_REG(event, msr, ARCH_PERFMON_EVENTSEL_EVENT, vm)
208 #define EVENT_EXTRA_END EVENT_EXTRA_REG(0, 0, 0, 0)
210 union perf_capabilities {
214 u64 pebs_arch_reg : 1;
222 * struct x86_pmu - generic x86 pmu
226 * Generic x86 PMC bits
230 int (*handle_irq)(struct pt_regs *);
231 void (*disable_all)(void);
232 void (*enable_all)(int added);
233 void (*enable)(struct perf_event *);
234 void (*disable)(struct perf_event *);
235 int (*hw_config)(struct perf_event *event);
236 int (*schedule_events)(struct cpu_hw_events *cpuc, int n, int *assign);
239 u64 (*event_map)(int);
242 int num_counters_fixed;
247 struct event_constraint *
248 (*get_event_constraints)(struct cpu_hw_events *cpuc,
249 struct perf_event *event);
251 void (*put_event_constraints)(struct cpu_hw_events *cpuc,
252 struct perf_event *event);
253 struct event_constraint *event_constraints;
254 struct event_constraint *percore_constraints;
255 void (*quirks)(void);
256 int perfctr_second_write;
258 int (*cpu_prepare)(int cpu);
259 void (*cpu_starting)(int cpu);
260 void (*cpu_dying)(int cpu);
261 void (*cpu_dead)(int cpu);
264 * Intel Arch Perfmon v2+
267 union perf_capabilities intel_cap;
270 * Intel DebugStore bits
273 int bts_active, pebs_active;
274 int pebs_record_size;
275 void (*drain_pebs)(struct pt_regs *regs);
276 struct event_constraint *pebs_constraints;
281 unsigned long lbr_tos, lbr_from, lbr_to; /* MSR base regs */
282 int lbr_nr; /* hardware stack size */
285 * Extra registers for events
287 struct extra_reg *extra_regs;
290 static struct x86_pmu x86_pmu __read_mostly;
292 static DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
296 static int x86_perf_event_set_period(struct perf_event *event);
299 * Generalized hw caching related hw_event table, filled
300 * in on a per model basis. A value of 0 means
301 * 'not supported', -1 means 'hw_event makes no sense on
302 * this CPU', any other value means the raw hw_event
306 #define C(x) PERF_COUNT_HW_CACHE_##x
308 static u64 __read_mostly hw_cache_event_ids
309 [PERF_COUNT_HW_CACHE_MAX]
310 [PERF_COUNT_HW_CACHE_OP_MAX]
311 [PERF_COUNT_HW_CACHE_RESULT_MAX];
312 static u64 __read_mostly hw_cache_extra_regs
313 [PERF_COUNT_HW_CACHE_MAX]
314 [PERF_COUNT_HW_CACHE_OP_MAX]
315 [PERF_COUNT_HW_CACHE_RESULT_MAX];
318 * Propagate event elapsed time into the generic event.
319 * Can only be executed on the CPU where the event is active.
320 * Returns the delta events processed.
323 x86_perf_event_update(struct perf_event *event)
325 struct hw_perf_event *hwc = &event->hw;
326 int shift = 64 - x86_pmu.cntval_bits;
327 u64 prev_raw_count, new_raw_count;
331 if (idx == X86_PMC_IDX_FIXED_BTS)
335 * Careful: an NMI might modify the previous event value.
337 * Our tactic to handle this is to first atomically read and
338 * exchange a new raw count - then add that new-prev delta
339 * count to the generic event atomically:
342 prev_raw_count = local64_read(&hwc->prev_count);
343 rdmsrl(hwc->event_base, new_raw_count);
345 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
346 new_raw_count) != prev_raw_count)
350 * Now we have the new raw value and have updated the prev
351 * timestamp already. We can now calculate the elapsed delta
352 * (event-)time and add that to the generic event.
354 * Careful, not all hw sign-extends above the physical width
357 delta = (new_raw_count << shift) - (prev_raw_count << shift);
360 local64_add(delta, &event->count);
361 local64_sub(delta, &hwc->period_left);
363 return new_raw_count;
366 /* using X86_FEATURE_PERFCTR_CORE to later implement ALTERNATIVE() here */
367 static inline int x86_pmu_addr_offset(int index)
369 if (boot_cpu_has(X86_FEATURE_PERFCTR_CORE))
374 static inline unsigned int x86_pmu_config_addr(int index)
376 return x86_pmu.eventsel + x86_pmu_addr_offset(index);
379 static inline unsigned int x86_pmu_event_addr(int index)
381 return x86_pmu.perfctr + x86_pmu_addr_offset(index);
385 * Find and validate any extra registers to set up.
387 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
389 struct extra_reg *er;
391 event->hw.extra_reg = 0;
392 event->hw.extra_config = 0;
394 if (!x86_pmu.extra_regs)
397 for (er = x86_pmu.extra_regs; er->msr; er++) {
398 if (er->event != (config & er->config_mask))
400 if (event->attr.config1 & ~er->valid_mask)
402 event->hw.extra_reg = er->msr;
403 event->hw.extra_config = event->attr.config1;
409 static atomic_t active_events;
410 static DEFINE_MUTEX(pmc_reserve_mutex);
412 #ifdef CONFIG_X86_LOCAL_APIC
414 static bool reserve_pmc_hardware(void)
418 for (i = 0; i < x86_pmu.num_counters; i++) {
419 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
423 for (i = 0; i < x86_pmu.num_counters; i++) {
424 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
431 for (i--; i >= 0; i--)
432 release_evntsel_nmi(x86_pmu_config_addr(i));
434 i = x86_pmu.num_counters;
437 for (i--; i >= 0; i--)
438 release_perfctr_nmi(x86_pmu_event_addr(i));
443 static void release_pmc_hardware(void)
447 for (i = 0; i < x86_pmu.num_counters; i++) {
448 release_perfctr_nmi(x86_pmu_event_addr(i));
449 release_evntsel_nmi(x86_pmu_config_addr(i));
455 static bool reserve_pmc_hardware(void) { return true; }
456 static void release_pmc_hardware(void) {}
460 static bool check_hw_exists(void)
462 u64 val, val_new = 0;
466 * Check to see if the BIOS enabled any of the counters, if so
469 for (i = 0; i < x86_pmu.num_counters; i++) {
470 reg = x86_pmu_config_addr(i);
471 ret = rdmsrl_safe(reg, &val);
474 if (val & ARCH_PERFMON_EVENTSEL_ENABLE)
478 if (x86_pmu.num_counters_fixed) {
479 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
480 ret = rdmsrl_safe(reg, &val);
483 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
484 if (val & (0x03 << i*4))
490 * Now write a value and read it back to see if it matches,
491 * this is needed to detect certain hardware emulators (qemu/kvm)
492 * that don't trap on the MSR access and always return 0s.
495 ret = checking_wrmsrl(x86_pmu_event_addr(0), val);
496 ret |= rdmsrl_safe(x86_pmu_event_addr(0), &val_new);
497 if (ret || val != val_new)
504 * We still allow the PMU driver to operate:
506 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
507 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg, val);
512 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
517 static void reserve_ds_buffers(void);
518 static void release_ds_buffers(void);
520 static void hw_perf_event_destroy(struct perf_event *event)
522 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
523 release_pmc_hardware();
524 release_ds_buffers();
525 mutex_unlock(&pmc_reserve_mutex);
529 static inline int x86_pmu_initialized(void)
531 return x86_pmu.handle_irq != NULL;
535 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
537 struct perf_event_attr *attr = &event->attr;
538 unsigned int cache_type, cache_op, cache_result;
541 config = attr->config;
543 cache_type = (config >> 0) & 0xff;
544 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
547 cache_op = (config >> 8) & 0xff;
548 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
551 cache_result = (config >> 16) & 0xff;
552 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
555 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
564 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
565 return x86_pmu_extra_regs(val, event);
568 static int x86_setup_perfctr(struct perf_event *event)
570 struct perf_event_attr *attr = &event->attr;
571 struct hw_perf_event *hwc = &event->hw;
574 if (!is_sampling_event(event)) {
575 hwc->sample_period = x86_pmu.max_period;
576 hwc->last_period = hwc->sample_period;
577 local64_set(&hwc->period_left, hwc->sample_period);
580 * If we have a PMU initialized but no APIC
581 * interrupts, we cannot sample hardware
582 * events (user-space has to fall back and
583 * sample via a hrtimer based software event):
590 * Do not allow config1 (extended registers) to propagate,
591 * there's no sane user-space generalization yet:
593 if (attr->type == PERF_TYPE_RAW)
596 if (attr->type == PERF_TYPE_HW_CACHE)
597 return set_ext_hw_attr(hwc, event);
599 if (attr->config >= x86_pmu.max_events)
605 config = x86_pmu.event_map(attr->config);
616 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
617 !attr->freq && hwc->sample_period == 1) {
618 /* BTS is not supported by this architecture. */
619 if (!x86_pmu.bts_active)
622 /* BTS is currently only allowed for user-mode. */
623 if (!attr->exclude_kernel)
627 hwc->config |= config;
632 static int x86_pmu_hw_config(struct perf_event *event)
634 if (event->attr.precise_ip) {
637 /* Support for constant skid */
638 if (x86_pmu.pebs_active) {
641 /* Support for IP fixup */
646 if (event->attr.precise_ip > precise)
652 * (keep 'enabled' bit clear for now)
654 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
657 * Count user and OS events unless requested not to
659 if (!event->attr.exclude_user)
660 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
661 if (!event->attr.exclude_kernel)
662 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
664 if (event->attr.type == PERF_TYPE_RAW)
665 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
667 return x86_setup_perfctr(event);
671 * Setup the hardware configuration for a given attr_type
673 static int __x86_pmu_event_init(struct perf_event *event)
677 if (!x86_pmu_initialized())
681 if (!atomic_inc_not_zero(&active_events)) {
682 mutex_lock(&pmc_reserve_mutex);
683 if (atomic_read(&active_events) == 0) {
684 if (!reserve_pmc_hardware())
687 reserve_ds_buffers();
690 atomic_inc(&active_events);
691 mutex_unlock(&pmc_reserve_mutex);
696 event->destroy = hw_perf_event_destroy;
699 event->hw.last_cpu = -1;
700 event->hw.last_tag = ~0ULL;
702 return x86_pmu.hw_config(event);
705 static void x86_pmu_disable_all(void)
707 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
710 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
713 if (!test_bit(idx, cpuc->active_mask))
715 rdmsrl(x86_pmu_config_addr(idx), val);
716 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
718 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
719 wrmsrl(x86_pmu_config_addr(idx), val);
723 static void x86_pmu_disable(struct pmu *pmu)
725 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
727 if (!x86_pmu_initialized())
737 x86_pmu.disable_all();
740 static inline void __x86_pmu_enable_event(struct hw_perf_event *hwc,
744 wrmsrl(hwc->extra_reg, hwc->extra_config);
745 wrmsrl(hwc->config_base, hwc->config | enable_mask);
748 static void x86_pmu_enable_all(int added)
750 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
753 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
754 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
756 if (!test_bit(idx, cpuc->active_mask))
759 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
763 static struct pmu pmu;
765 static inline int is_x86_event(struct perf_event *event)
767 return event->pmu == &pmu;
770 static int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
772 struct event_constraint *c, *constraints[X86_PMC_IDX_MAX];
773 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
774 int i, j, w, wmax, num = 0;
775 struct hw_perf_event *hwc;
777 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
779 for (i = 0; i < n; i++) {
780 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
785 * fastpath, try to reuse previous register
787 for (i = 0; i < n; i++) {
788 hwc = &cpuc->event_list[i]->hw;
795 /* constraint still honored */
796 if (!test_bit(hwc->idx, c->idxmsk))
799 /* not already used */
800 if (test_bit(hwc->idx, used_mask))
803 __set_bit(hwc->idx, used_mask);
805 assign[i] = hwc->idx;
814 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
817 * weight = number of possible counters
819 * 1 = most constrained, only works on one counter
820 * wmax = least constrained, works on any counter
822 * assign events to counters starting with most
823 * constrained events.
825 wmax = x86_pmu.num_counters;
828 * when fixed event counters are present,
829 * wmax is incremented by 1 to account
830 * for one more choice
832 if (x86_pmu.num_counters_fixed)
835 for (w = 1, num = n; num && w <= wmax; w++) {
837 for (i = 0; num && i < n; i++) {
839 hwc = &cpuc->event_list[i]->hw;
844 for_each_set_bit(j, c->idxmsk, X86_PMC_IDX_MAX) {
845 if (!test_bit(j, used_mask))
849 if (j == X86_PMC_IDX_MAX)
852 __set_bit(j, used_mask);
861 * scheduling failed or is just a simulation,
862 * free resources if necessary
864 if (!assign || num) {
865 for (i = 0; i < n; i++) {
866 if (x86_pmu.put_event_constraints)
867 x86_pmu.put_event_constraints(cpuc, cpuc->event_list[i]);
870 return num ? -ENOSPC : 0;
874 * dogrp: true if must collect siblings events (group)
875 * returns total number of events and error code
877 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
879 struct perf_event *event;
882 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
884 /* current number of events already accepted */
887 if (is_x86_event(leader)) {
890 cpuc->event_list[n] = leader;
896 list_for_each_entry(event, &leader->sibling_list, group_entry) {
897 if (!is_x86_event(event) ||
898 event->state <= PERF_EVENT_STATE_OFF)
904 cpuc->event_list[n] = event;
910 static inline void x86_assign_hw_event(struct perf_event *event,
911 struct cpu_hw_events *cpuc, int i)
913 struct hw_perf_event *hwc = &event->hw;
915 hwc->idx = cpuc->assign[i];
916 hwc->last_cpu = smp_processor_id();
917 hwc->last_tag = ++cpuc->tags[i];
919 if (hwc->idx == X86_PMC_IDX_FIXED_BTS) {
920 hwc->config_base = 0;
922 } else if (hwc->idx >= X86_PMC_IDX_FIXED) {
923 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
924 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - X86_PMC_IDX_FIXED);
926 hwc->config_base = x86_pmu_config_addr(hwc->idx);
927 hwc->event_base = x86_pmu_event_addr(hwc->idx);
931 static inline int match_prev_assignment(struct hw_perf_event *hwc,
932 struct cpu_hw_events *cpuc,
935 return hwc->idx == cpuc->assign[i] &&
936 hwc->last_cpu == smp_processor_id() &&
937 hwc->last_tag == cpuc->tags[i];
940 static void x86_pmu_start(struct perf_event *event, int flags);
941 static void x86_pmu_stop(struct perf_event *event, int flags);
943 static void x86_pmu_enable(struct pmu *pmu)
945 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
946 struct perf_event *event;
947 struct hw_perf_event *hwc;
948 int i, added = cpuc->n_added;
950 if (!x86_pmu_initialized())
957 int n_running = cpuc->n_events - cpuc->n_added;
959 * apply assignment obtained either from
960 * hw_perf_group_sched_in() or x86_pmu_enable()
962 * step1: save events moving to new counters
963 * step2: reprogram moved events into new counters
965 for (i = 0; i < n_running; i++) {
966 event = cpuc->event_list[i];
970 * we can avoid reprogramming counter if:
971 * - assigned same counter as last time
972 * - running on same CPU as last time
973 * - no other event has used the counter since
975 if (hwc->idx == -1 ||
976 match_prev_assignment(hwc, cpuc, i))
980 * Ensure we don't accidentally enable a stopped
981 * counter simply because we rescheduled.
983 if (hwc->state & PERF_HES_STOPPED)
984 hwc->state |= PERF_HES_ARCH;
986 x86_pmu_stop(event, PERF_EF_UPDATE);
989 for (i = 0; i < cpuc->n_events; i++) {
990 event = cpuc->event_list[i];
993 if (!match_prev_assignment(hwc, cpuc, i))
994 x86_assign_hw_event(event, cpuc, i);
995 else if (i < n_running)
998 if (hwc->state & PERF_HES_ARCH)
1001 x86_pmu_start(event, PERF_EF_RELOAD);
1004 perf_events_lapic_init();
1010 x86_pmu.enable_all(added);
1013 static inline void x86_pmu_disable_event(struct perf_event *event)
1015 struct hw_perf_event *hwc = &event->hw;
1017 wrmsrl(hwc->config_base, hwc->config);
1020 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1023 * Set the next IRQ period, based on the hwc->period_left value.
1024 * To be called with the event disabled in hw:
1027 x86_perf_event_set_period(struct perf_event *event)
1029 struct hw_perf_event *hwc = &event->hw;
1030 s64 left = local64_read(&hwc->period_left);
1031 s64 period = hwc->sample_period;
1032 int ret = 0, idx = hwc->idx;
1034 if (idx == X86_PMC_IDX_FIXED_BTS)
1038 * If we are way outside a reasonable range then just skip forward:
1040 if (unlikely(left <= -period)) {
1042 local64_set(&hwc->period_left, left);
1043 hwc->last_period = period;
1047 if (unlikely(left <= 0)) {
1049 local64_set(&hwc->period_left, left);
1050 hwc->last_period = period;
1054 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1056 if (unlikely(left < 2))
1059 if (left > x86_pmu.max_period)
1060 left = x86_pmu.max_period;
1062 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1065 * The hw event starts counting from this event offset,
1066 * mark it to be able to extra future deltas:
1068 local64_set(&hwc->prev_count, (u64)-left);
1070 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1073 * Due to erratum on certan cpu we need
1074 * a second write to be sure the register
1075 * is updated properly
1077 if (x86_pmu.perfctr_second_write) {
1078 wrmsrl(hwc->event_base,
1079 (u64)(-left) & x86_pmu.cntval_mask);
1082 perf_event_update_userpage(event);
1087 static void x86_pmu_enable_event(struct perf_event *event)
1089 if (__this_cpu_read(cpu_hw_events.enabled))
1090 __x86_pmu_enable_event(&event->hw,
1091 ARCH_PERFMON_EVENTSEL_ENABLE);
1095 * Add a single event to the PMU.
1097 * The event is added to the group of enabled events
1098 * but only if it can be scehduled with existing events.
1100 static int x86_pmu_add(struct perf_event *event, int flags)
1102 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1103 struct hw_perf_event *hwc;
1104 int assign[X86_PMC_IDX_MAX];
1109 perf_pmu_disable(event->pmu);
1110 n0 = cpuc->n_events;
1111 ret = n = collect_events(cpuc, event, false);
1115 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1116 if (!(flags & PERF_EF_START))
1117 hwc->state |= PERF_HES_ARCH;
1120 * If group events scheduling transaction was started,
1121 * skip the schedulability test here, it will be performed
1122 * at commit time (->commit_txn) as a whole
1124 if (cpuc->group_flag & PERF_EVENT_TXN)
1127 ret = x86_pmu.schedule_events(cpuc, n, assign);
1131 * copy new assignment, now we know it is possible
1132 * will be used by hw_perf_enable()
1134 memcpy(cpuc->assign, assign, n*sizeof(int));
1138 cpuc->n_added += n - n0;
1139 cpuc->n_txn += n - n0;
1143 perf_pmu_enable(event->pmu);
1147 static void x86_pmu_start(struct perf_event *event, int flags)
1149 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1150 int idx = event->hw.idx;
1152 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1155 if (WARN_ON_ONCE(idx == -1))
1158 if (flags & PERF_EF_RELOAD) {
1159 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1160 x86_perf_event_set_period(event);
1163 event->hw.state = 0;
1165 cpuc->events[idx] = event;
1166 __set_bit(idx, cpuc->active_mask);
1167 __set_bit(idx, cpuc->running);
1168 x86_pmu.enable(event);
1169 perf_event_update_userpage(event);
1172 void perf_event_print_debug(void)
1174 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1176 struct cpu_hw_events *cpuc;
1177 unsigned long flags;
1180 if (!x86_pmu.num_counters)
1183 local_irq_save(flags);
1185 cpu = smp_processor_id();
1186 cpuc = &per_cpu(cpu_hw_events, cpu);
1188 if (x86_pmu.version >= 2) {
1189 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1190 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1191 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1192 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1193 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1196 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1197 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1198 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1199 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1200 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1202 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1204 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1205 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1206 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1208 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1210 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1211 cpu, idx, pmc_ctrl);
1212 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1213 cpu, idx, pmc_count);
1214 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1215 cpu, idx, prev_left);
1217 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1218 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1220 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1221 cpu, idx, pmc_count);
1223 local_irq_restore(flags);
1226 static void x86_pmu_stop(struct perf_event *event, int flags)
1228 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1229 struct hw_perf_event *hwc = &event->hw;
1231 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1232 x86_pmu.disable(event);
1233 cpuc->events[hwc->idx] = NULL;
1234 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1235 hwc->state |= PERF_HES_STOPPED;
1238 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1240 * Drain the remaining delta count out of a event
1241 * that we are disabling:
1243 x86_perf_event_update(event);
1244 hwc->state |= PERF_HES_UPTODATE;
1248 static void x86_pmu_del(struct perf_event *event, int flags)
1250 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1254 * If we're called during a txn, we don't need to do anything.
1255 * The events never got scheduled and ->cancel_txn will truncate
1258 if (cpuc->group_flag & PERF_EVENT_TXN)
1261 x86_pmu_stop(event, PERF_EF_UPDATE);
1263 for (i = 0; i < cpuc->n_events; i++) {
1264 if (event == cpuc->event_list[i]) {
1266 if (x86_pmu.put_event_constraints)
1267 x86_pmu.put_event_constraints(cpuc, event);
1269 while (++i < cpuc->n_events)
1270 cpuc->event_list[i-1] = cpuc->event_list[i];
1276 perf_event_update_userpage(event);
1279 static int x86_pmu_handle_irq(struct pt_regs *regs)
1281 struct perf_sample_data data;
1282 struct cpu_hw_events *cpuc;
1283 struct perf_event *event;
1284 int idx, handled = 0;
1287 perf_sample_data_init(&data, 0);
1289 cpuc = &__get_cpu_var(cpu_hw_events);
1292 * Some chipsets need to unmask the LVTPC in a particular spot
1293 * inside the nmi handler. As a result, the unmasking was pushed
1294 * into all the nmi handlers.
1296 * This generic handler doesn't seem to have any issues where the
1297 * unmasking occurs so it was left at the top.
1299 apic_write(APIC_LVTPC, APIC_DM_NMI);
1301 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1302 if (!test_bit(idx, cpuc->active_mask)) {
1304 * Though we deactivated the counter some cpus
1305 * might still deliver spurious interrupts still
1306 * in flight. Catch them:
1308 if (__test_and_clear_bit(idx, cpuc->running))
1313 event = cpuc->events[idx];
1315 val = x86_perf_event_update(event);
1316 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1323 data.period = event->hw.last_period;
1325 if (!x86_perf_event_set_period(event))
1328 if (perf_event_overflow(event, 1, &data, regs))
1329 x86_pmu_stop(event, 0);
1333 inc_irq_stat(apic_perf_irqs);
1338 void perf_events_lapic_init(void)
1340 if (!x86_pmu.apic || !x86_pmu_initialized())
1344 * Always use NMI for PMU
1346 apic_write(APIC_LVTPC, APIC_DM_NMI);
1349 struct pmu_nmi_state {
1350 unsigned int marked;
1354 static DEFINE_PER_CPU(struct pmu_nmi_state, pmu_nmi);
1356 static int __kprobes
1357 perf_event_nmi_handler(struct notifier_block *self,
1358 unsigned long cmd, void *__args)
1360 struct die_args *args = __args;
1361 unsigned int this_nmi;
1364 if (!atomic_read(&active_events))
1370 case DIE_NMIUNKNOWN:
1371 this_nmi = percpu_read(irq_stat.__nmi_count);
1372 if (this_nmi != __this_cpu_read(pmu_nmi.marked))
1373 /* let the kernel handle the unknown nmi */
1376 * This one is a PMU back-to-back nmi. Two events
1377 * trigger 'simultaneously' raising two back-to-back
1378 * NMIs. If the first NMI handles both, the latter
1379 * will be empty and daze the CPU. So, we drop it to
1380 * avoid false-positive 'unknown nmi' messages.
1387 handled = x86_pmu.handle_irq(args->regs);
1391 this_nmi = percpu_read(irq_stat.__nmi_count);
1392 if ((handled > 1) ||
1393 /* the next nmi could be a back-to-back nmi */
1394 ((__this_cpu_read(pmu_nmi.marked) == this_nmi) &&
1395 (__this_cpu_read(pmu_nmi.handled) > 1))) {
1397 * We could have two subsequent back-to-back nmis: The
1398 * first handles more than one counter, the 2nd
1399 * handles only one counter and the 3rd handles no
1402 * This is the 2nd nmi because the previous was
1403 * handling more than one counter. We will mark the
1404 * next (3rd) and then drop it if unhandled.
1406 __this_cpu_write(pmu_nmi.marked, this_nmi + 1);
1407 __this_cpu_write(pmu_nmi.handled, handled);
1413 static __read_mostly struct notifier_block perf_event_nmi_notifier = {
1414 .notifier_call = perf_event_nmi_handler,
1416 .priority = NMI_LOCAL_LOW_PRIOR,
1419 static struct event_constraint unconstrained;
1420 static struct event_constraint emptyconstraint;
1422 static struct event_constraint *
1423 x86_get_event_constraints(struct cpu_hw_events *cpuc, struct perf_event *event)
1425 struct event_constraint *c;
1427 if (x86_pmu.event_constraints) {
1428 for_each_event_constraint(c, x86_pmu.event_constraints) {
1429 if ((event->hw.config & c->cmask) == c->code)
1434 return &unconstrained;
1437 #include "perf_event_amd.c"
1438 #include "perf_event_p6.c"
1439 #include "perf_event_p4.c"
1440 #include "perf_event_intel_lbr.c"
1441 #include "perf_event_intel_ds.c"
1442 #include "perf_event_intel.c"
1444 static int __cpuinit
1445 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1447 unsigned int cpu = (long)hcpu;
1448 int ret = NOTIFY_OK;
1450 switch (action & ~CPU_TASKS_FROZEN) {
1451 case CPU_UP_PREPARE:
1452 if (x86_pmu.cpu_prepare)
1453 ret = x86_pmu.cpu_prepare(cpu);
1457 if (x86_pmu.cpu_starting)
1458 x86_pmu.cpu_starting(cpu);
1462 if (x86_pmu.cpu_dying)
1463 x86_pmu.cpu_dying(cpu);
1466 case CPU_UP_CANCELED:
1468 if (x86_pmu.cpu_dead)
1469 x86_pmu.cpu_dead(cpu);
1479 static void __init pmu_check_apic(void)
1485 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1486 pr_info("no hardware sampling interrupt available.\n");
1489 static int __init init_hw_perf_events(void)
1491 struct event_constraint *c;
1494 pr_info("Performance Events: ");
1496 switch (boot_cpu_data.x86_vendor) {
1497 case X86_VENDOR_INTEL:
1498 err = intel_pmu_init();
1500 case X86_VENDOR_AMD:
1501 err = amd_pmu_init();
1507 pr_cont("no PMU driver, software events only.\n");
1513 /* sanity check that the hardware exists or is emulated */
1514 if (!check_hw_exists())
1517 pr_cont("%s PMU driver.\n", x86_pmu.name);
1522 if (x86_pmu.num_counters > X86_PMC_MAX_GENERIC) {
1523 WARN(1, KERN_ERR "hw perf events %d > max(%d), clipping!",
1524 x86_pmu.num_counters, X86_PMC_MAX_GENERIC);
1525 x86_pmu.num_counters = X86_PMC_MAX_GENERIC;
1527 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1529 if (x86_pmu.num_counters_fixed > X86_PMC_MAX_FIXED) {
1530 WARN(1, KERN_ERR "hw perf events fixed %d > max(%d), clipping!",
1531 x86_pmu.num_counters_fixed, X86_PMC_MAX_FIXED);
1532 x86_pmu.num_counters_fixed = X86_PMC_MAX_FIXED;
1535 x86_pmu.intel_ctrl |=
1536 ((1LL << x86_pmu.num_counters_fixed)-1) << X86_PMC_IDX_FIXED;
1538 perf_events_lapic_init();
1539 register_die_notifier(&perf_event_nmi_notifier);
1541 unconstrained = (struct event_constraint)
1542 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1543 0, x86_pmu.num_counters);
1545 if (x86_pmu.event_constraints) {
1546 for_each_event_constraint(c, x86_pmu.event_constraints) {
1547 if (c->cmask != X86_RAW_EVENT_MASK)
1550 c->idxmsk64 |= (1ULL << x86_pmu.num_counters) - 1;
1551 c->weight += x86_pmu.num_counters;
1555 pr_info("... version: %d\n", x86_pmu.version);
1556 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1557 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1558 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1559 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1560 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1561 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1563 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1564 perf_cpu_notifier(x86_pmu_notifier);
1568 early_initcall(init_hw_perf_events);
1570 static inline void x86_pmu_read(struct perf_event *event)
1572 x86_perf_event_update(event);
1576 * Start group events scheduling transaction
1577 * Set the flag to make pmu::enable() not perform the
1578 * schedulability test, it will be performed at commit time
1580 static void x86_pmu_start_txn(struct pmu *pmu)
1582 perf_pmu_disable(pmu);
1583 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1584 __this_cpu_write(cpu_hw_events.n_txn, 0);
1588 * Stop group events scheduling transaction
1589 * Clear the flag and pmu::enable() will perform the
1590 * schedulability test.
1592 static void x86_pmu_cancel_txn(struct pmu *pmu)
1594 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1596 * Truncate the collected events.
1598 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1599 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1600 perf_pmu_enable(pmu);
1604 * Commit group events scheduling transaction
1605 * Perform the group schedulability test as a whole
1606 * Return 0 if success
1608 static int x86_pmu_commit_txn(struct pmu *pmu)
1610 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1611 int assign[X86_PMC_IDX_MAX];
1616 if (!x86_pmu_initialized())
1619 ret = x86_pmu.schedule_events(cpuc, n, assign);
1624 * copy new assignment, now we know it is possible
1625 * will be used by hw_perf_enable()
1627 memcpy(cpuc->assign, assign, n*sizeof(int));
1629 cpuc->group_flag &= ~PERF_EVENT_TXN;
1630 perf_pmu_enable(pmu);
1635 * validate that we can schedule this event
1637 static int validate_event(struct perf_event *event)
1639 struct cpu_hw_events *fake_cpuc;
1640 struct event_constraint *c;
1643 fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1647 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1649 if (!c || !c->weight)
1652 if (x86_pmu.put_event_constraints)
1653 x86_pmu.put_event_constraints(fake_cpuc, event);
1661 * validate a single event group
1663 * validation include:
1664 * - check events are compatible which each other
1665 * - events do not compete for the same counter
1666 * - number of events <= number of counters
1668 * validation ensures the group can be loaded onto the
1669 * PMU if it was the only group available.
1671 static int validate_group(struct perf_event *event)
1673 struct perf_event *leader = event->group_leader;
1674 struct cpu_hw_events *fake_cpuc;
1678 fake_cpuc = kmalloc(sizeof(*fake_cpuc), GFP_KERNEL | __GFP_ZERO);
1683 * the event is not yet connected with its
1684 * siblings therefore we must first collect
1685 * existing siblings, then add the new event
1686 * before we can simulate the scheduling
1689 n = collect_events(fake_cpuc, leader, true);
1693 fake_cpuc->n_events = n;
1694 n = collect_events(fake_cpuc, event, false);
1698 fake_cpuc->n_events = n;
1700 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1708 static int x86_pmu_event_init(struct perf_event *event)
1713 switch (event->attr.type) {
1715 case PERF_TYPE_HARDWARE:
1716 case PERF_TYPE_HW_CACHE:
1723 err = __x86_pmu_event_init(event);
1726 * we temporarily connect event to its pmu
1727 * such that validate_group() can classify
1728 * it as an x86 event using is_x86_event()
1733 if (event->group_leader != event)
1734 err = validate_group(event);
1736 err = validate_event(event);
1742 event->destroy(event);
1748 static struct pmu pmu = {
1749 .pmu_enable = x86_pmu_enable,
1750 .pmu_disable = x86_pmu_disable,
1752 .event_init = x86_pmu_event_init,
1756 .start = x86_pmu_start,
1757 .stop = x86_pmu_stop,
1758 .read = x86_pmu_read,
1760 .start_txn = x86_pmu_start_txn,
1761 .cancel_txn = x86_pmu_cancel_txn,
1762 .commit_txn = x86_pmu_commit_txn,
1770 backtrace_warning_symbol(void *data, char *msg, unsigned long symbol)
1772 /* Ignore warnings */
1775 static void backtrace_warning(void *data, char *msg)
1777 /* Ignore warnings */
1780 static int backtrace_stack(void *data, char *name)
1785 static void backtrace_address(void *data, unsigned long addr, int reliable)
1787 struct perf_callchain_entry *entry = data;
1789 perf_callchain_store(entry, addr);
1792 static const struct stacktrace_ops backtrace_ops = {
1793 .warning = backtrace_warning,
1794 .warning_symbol = backtrace_warning_symbol,
1795 .stack = backtrace_stack,
1796 .address = backtrace_address,
1797 .walk_stack = print_context_stack_bp,
1801 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1803 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1804 /* TODO: We don't support guest os callchain now */
1808 perf_callchain_store(entry, regs->ip);
1810 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1813 #ifdef CONFIG_COMPAT
1815 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1817 /* 32-bit process in 64-bit kernel. */
1818 struct stack_frame_ia32 frame;
1819 const void __user *fp;
1821 if (!test_thread_flag(TIF_IA32))
1824 fp = compat_ptr(regs->bp);
1825 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1826 unsigned long bytes;
1827 frame.next_frame = 0;
1828 frame.return_address = 0;
1830 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1831 if (bytes != sizeof(frame))
1834 if (fp < compat_ptr(regs->sp))
1837 perf_callchain_store(entry, frame.return_address);
1838 fp = compat_ptr(frame.next_frame);
1844 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
1851 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
1853 struct stack_frame frame;
1854 const void __user *fp;
1856 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1857 /* TODO: We don't support guest os callchain now */
1861 fp = (void __user *)regs->bp;
1863 perf_callchain_store(entry, regs->ip);
1865 if (perf_callchain_user32(regs, entry))
1868 while (entry->nr < PERF_MAX_STACK_DEPTH) {
1869 unsigned long bytes;
1870 frame.next_frame = NULL;
1871 frame.return_address = 0;
1873 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
1874 if (bytes != sizeof(frame))
1877 if ((unsigned long)fp < regs->sp)
1880 perf_callchain_store(entry, frame.return_address);
1881 fp = frame.next_frame;
1885 unsigned long perf_instruction_pointer(struct pt_regs *regs)
1889 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
1890 ip = perf_guest_cbs->get_guest_ip();
1892 ip = instruction_pointer(regs);
1897 unsigned long perf_misc_flags(struct pt_regs *regs)
1901 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1902 if (perf_guest_cbs->is_user_mode())
1903 misc |= PERF_RECORD_MISC_GUEST_USER;
1905 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
1907 if (user_mode(regs))
1908 misc |= PERF_RECORD_MISC_USER;
1910 misc |= PERF_RECORD_MISC_KERNEL;
1913 if (regs->flags & PERF_EFLAGS_EXACT)
1914 misc |= PERF_RECORD_MISC_EXACT_IP;