2 * Performance events x86 architecture code
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2009 Jaswinder Singh Rajput
7 * Copyright (C) 2009 Advanced Micro Devices, Inc., Robert Richter
8 * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
9 * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
10 * Copyright (C) 2009 Google, Inc., Stephane Eranian
12 * For licencing details see kernel-base/COPYING
15 #include <linux/perf_event.h>
16 #include <linux/capability.h>
17 #include <linux/notifier.h>
18 #include <linux/hardirq.h>
19 #include <linux/kprobes.h>
20 #include <linux/module.h>
21 #include <linux/kdebug.h>
22 #include <linux/sched.h>
23 #include <linux/uaccess.h>
24 #include <linux/slab.h>
25 #include <linux/cpu.h>
26 #include <linux/bitops.h>
27 #include <linux/device.h>
30 #include <asm/stacktrace.h>
33 #include <asm/alternative.h>
34 #include <asm/mmu_context.h>
35 #include <asm/tlbflush.h>
36 #include <asm/timer.h>
40 #include "perf_event.h"
42 struct x86_pmu x86_pmu __read_mostly;
44 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
48 struct static_key rdpmc_always_available = STATIC_KEY_INIT_FALSE;
50 u64 __read_mostly hw_cache_event_ids
51 [PERF_COUNT_HW_CACHE_MAX]
52 [PERF_COUNT_HW_CACHE_OP_MAX]
53 [PERF_COUNT_HW_CACHE_RESULT_MAX];
54 u64 __read_mostly hw_cache_extra_regs
55 [PERF_COUNT_HW_CACHE_MAX]
56 [PERF_COUNT_HW_CACHE_OP_MAX]
57 [PERF_COUNT_HW_CACHE_RESULT_MAX];
60 * Propagate event elapsed time into the generic event.
61 * Can only be executed on the CPU where the event is active.
62 * Returns the delta events processed.
64 u64 x86_perf_event_update(struct perf_event *event)
66 struct hw_perf_event *hwc = &event->hw;
67 int shift = 64 - x86_pmu.cntval_bits;
68 u64 prev_raw_count, new_raw_count;
72 if (idx == INTEL_PMC_IDX_FIXED_BTS)
76 * Careful: an NMI might modify the previous event value.
78 * Our tactic to handle this is to first atomically read and
79 * exchange a new raw count - then add that new-prev delta
80 * count to the generic event atomically:
83 prev_raw_count = local64_read(&hwc->prev_count);
84 rdpmcl(hwc->event_base_rdpmc, new_raw_count);
86 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
87 new_raw_count) != prev_raw_count)
91 * Now we have the new raw value and have updated the prev
92 * timestamp already. We can now calculate the elapsed delta
93 * (event-)time and add that to the generic event.
95 * Careful, not all hw sign-extends above the physical width
98 delta = (new_raw_count << shift) - (prev_raw_count << shift);
101 local64_add(delta, &event->count);
102 local64_sub(delta, &hwc->period_left);
104 return new_raw_count;
108 * Find and validate any extra registers to set up.
110 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
112 struct hw_perf_event_extra *reg;
113 struct extra_reg *er;
115 reg = &event->hw.extra_reg;
117 if (!x86_pmu.extra_regs)
120 for (er = x86_pmu.extra_regs; er->msr; er++) {
121 if (er->event != (config & er->config_mask))
123 if (event->attr.config1 & ~er->valid_mask)
125 /* Check if the extra msrs can be safely accessed*/
126 if (!er->extra_msr_access)
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_fail, val_new= ~0;
191 int i, reg, reg_fail, ret = 0;
196 * Check to see if the BIOS enabled any of the counters, if so
199 for (i = 0; i < x86_pmu.num_counters; i++) {
200 reg = x86_pmu_config_addr(i);
201 ret = rdmsrl_safe(reg, &val);
204 if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
213 if (x86_pmu.num_counters_fixed) {
214 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
215 ret = rdmsrl_safe(reg, &val);
218 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
219 if (val & (0x03 << i*4)) {
228 * If all the counters are enabled, the below test will always
229 * fail. The tools will also become useless in this scenario.
230 * Just fail and disable the hardware counters.
233 if (reg_safe == -1) {
239 * Read the current value, change it and read it back to see if it
240 * matches, this is needed to detect certain hardware emulators
241 * (qemu/kvm) that don't trap on the MSR access and always return 0s.
243 reg = x86_pmu_event_addr(reg_safe);
244 if (rdmsrl_safe(reg, &val))
247 ret = wrmsrl_safe(reg, val);
248 ret |= rdmsrl_safe(reg, &val_new);
249 if (ret || val != val_new)
253 * We still allow the PMU driver to operate:
256 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
257 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg_fail, val_fail);
263 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
264 printk("%sFailed to access perfctr msr (MSR %x is %Lx)\n",
265 boot_cpu_has(X86_FEATURE_HYPERVISOR) ? KERN_INFO : KERN_ERR,
271 static void hw_perf_event_destroy(struct perf_event *event)
273 x86_release_hardware();
276 void hw_perf_lbr_event_destroy(struct perf_event *event)
278 hw_perf_event_destroy(event);
280 /* undo the lbr/bts event accounting */
281 x86_del_exclusive(x86_lbr_exclusive_lbr);
284 static inline int x86_pmu_initialized(void)
286 return x86_pmu.handle_irq != NULL;
290 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
292 struct perf_event_attr *attr = &event->attr;
293 unsigned int cache_type, cache_op, cache_result;
296 config = attr->config;
298 cache_type = (config >> 0) & 0xff;
299 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
302 cache_op = (config >> 8) & 0xff;
303 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
306 cache_result = (config >> 16) & 0xff;
307 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
310 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
319 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
320 return x86_pmu_extra_regs(val, event);
323 int x86_reserve_hardware(void)
327 if (!atomic_inc_not_zero(&active_events)) {
328 mutex_lock(&pmc_reserve_mutex);
329 if (atomic_read(&active_events) == 0) {
330 if (!reserve_pmc_hardware())
333 reserve_ds_buffers();
336 atomic_inc(&active_events);
337 mutex_unlock(&pmc_reserve_mutex);
343 void x86_release_hardware(void)
345 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
346 release_pmc_hardware();
347 release_ds_buffers();
348 mutex_unlock(&pmc_reserve_mutex);
353 * Check if we can create event of a certain type (that no conflicting events
356 int x86_add_exclusive(unsigned int what)
360 if (atomic_inc_not_zero(&x86_pmu.lbr_exclusive[what]))
363 mutex_lock(&pmc_reserve_mutex);
364 for (i = 0; i < ARRAY_SIZE(x86_pmu.lbr_exclusive); i++) {
365 if (i != what && atomic_read(&x86_pmu.lbr_exclusive[i]))
369 atomic_inc(&x86_pmu.lbr_exclusive[what]);
373 mutex_unlock(&pmc_reserve_mutex);
377 void x86_del_exclusive(unsigned int what)
379 atomic_dec(&x86_pmu.lbr_exclusive[what]);
382 int x86_setup_perfctr(struct perf_event *event)
384 struct perf_event_attr *attr = &event->attr;
385 struct hw_perf_event *hwc = &event->hw;
388 if (!is_sampling_event(event)) {
389 hwc->sample_period = x86_pmu.max_period;
390 hwc->last_period = hwc->sample_period;
391 local64_set(&hwc->period_left, hwc->sample_period);
394 if (attr->type == PERF_TYPE_RAW)
395 return x86_pmu_extra_regs(event->attr.config, event);
397 if (attr->type == PERF_TYPE_HW_CACHE)
398 return set_ext_hw_attr(hwc, event);
400 if (attr->config >= x86_pmu.max_events)
406 config = x86_pmu.event_map(attr->config);
417 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
418 !attr->freq && hwc->sample_period == 1) {
419 /* BTS is not supported by this architecture. */
420 if (!x86_pmu.bts_active)
423 /* BTS is currently only allowed for user-mode. */
424 if (!attr->exclude_kernel)
427 /* disallow bts if conflicting events are present */
428 if (x86_add_exclusive(x86_lbr_exclusive_lbr))
431 event->destroy = hw_perf_lbr_event_destroy;
434 hwc->config |= config;
440 * check that branch_sample_type is compatible with
441 * settings needed for precise_ip > 1 which implies
442 * using the LBR to capture ALL taken branches at the
443 * priv levels of the measurement
445 static inline int precise_br_compat(struct perf_event *event)
447 u64 m = event->attr.branch_sample_type;
450 /* must capture all branches */
451 if (!(m & PERF_SAMPLE_BRANCH_ANY))
454 m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
456 if (!event->attr.exclude_user)
457 b |= PERF_SAMPLE_BRANCH_USER;
459 if (!event->attr.exclude_kernel)
460 b |= PERF_SAMPLE_BRANCH_KERNEL;
463 * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
469 int x86_pmu_hw_config(struct perf_event *event)
471 if (event->attr.precise_ip) {
474 /* Support for constant skid */
475 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
478 /* Support for IP fixup */
479 if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
483 if (event->attr.precise_ip > precise)
487 * check that PEBS LBR correction does not conflict with
488 * whatever the user is asking with attr->branch_sample_type
490 if (event->attr.precise_ip > 1 && x86_pmu.intel_cap.pebs_format < 2) {
491 u64 *br_type = &event->attr.branch_sample_type;
493 if (has_branch_stack(event)) {
494 if (!precise_br_compat(event))
497 /* branch_sample_type is compatible */
501 * user did not specify branch_sample_type
503 * For PEBS fixups, we capture all
504 * the branches at the priv level of the
507 *br_type = PERF_SAMPLE_BRANCH_ANY;
509 if (!event->attr.exclude_user)
510 *br_type |= PERF_SAMPLE_BRANCH_USER;
512 if (!event->attr.exclude_kernel)
513 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
517 if (event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_CALL_STACK)
518 event->attach_state |= PERF_ATTACH_TASK_DATA;
522 * (keep 'enabled' bit clear for now)
524 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
527 * Count user and OS events unless requested not to
529 if (!event->attr.exclude_user)
530 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
531 if (!event->attr.exclude_kernel)
532 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
534 if (event->attr.type == PERF_TYPE_RAW)
535 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
537 if (event->attr.sample_period && x86_pmu.limit_period) {
538 if (x86_pmu.limit_period(event, event->attr.sample_period) >
539 event->attr.sample_period)
543 return x86_setup_perfctr(event);
547 * Setup the hardware configuration for a given attr_type
549 static int __x86_pmu_event_init(struct perf_event *event)
553 if (!x86_pmu_initialized())
556 err = x86_reserve_hardware();
560 event->destroy = hw_perf_event_destroy;
563 event->hw.last_cpu = -1;
564 event->hw.last_tag = ~0ULL;
567 event->hw.extra_reg.idx = EXTRA_REG_NONE;
568 event->hw.branch_reg.idx = EXTRA_REG_NONE;
570 return x86_pmu.hw_config(event);
573 void x86_pmu_disable_all(void)
575 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
578 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
581 if (!test_bit(idx, cpuc->active_mask))
583 rdmsrl(x86_pmu_config_addr(idx), val);
584 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
586 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
587 wrmsrl(x86_pmu_config_addr(idx), val);
591 static void x86_pmu_disable(struct pmu *pmu)
593 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
595 if (!x86_pmu_initialized())
605 x86_pmu.disable_all();
608 void x86_pmu_enable_all(int added)
610 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
613 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
614 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
616 if (!test_bit(idx, cpuc->active_mask))
619 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
623 static struct pmu pmu;
625 static inline int is_x86_event(struct perf_event *event)
627 return event->pmu == &pmu;
631 * Event scheduler state:
633 * Assign events iterating over all events and counters, beginning
634 * with events with least weights first. Keep the current iterator
635 * state in struct sched_state.
639 int event; /* event index */
640 int counter; /* counter index */
641 int unassigned; /* number of events to be assigned left */
642 int nr_gp; /* number of GP counters used */
643 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
646 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
647 #define SCHED_STATES_MAX 2
654 struct event_constraint **constraints;
655 struct sched_state state;
656 struct sched_state saved[SCHED_STATES_MAX];
660 * Initialize interator that runs through all events and counters.
662 static void perf_sched_init(struct perf_sched *sched, struct event_constraint **constraints,
663 int num, int wmin, int wmax, int gpmax)
667 memset(sched, 0, sizeof(*sched));
668 sched->max_events = num;
669 sched->max_weight = wmax;
670 sched->max_gp = gpmax;
671 sched->constraints = constraints;
673 for (idx = 0; idx < num; idx++) {
674 if (constraints[idx]->weight == wmin)
678 sched->state.event = idx; /* start with min weight */
679 sched->state.weight = wmin;
680 sched->state.unassigned = num;
683 static void perf_sched_save_state(struct perf_sched *sched)
685 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
688 sched->saved[sched->saved_states] = sched->state;
689 sched->saved_states++;
692 static bool perf_sched_restore_state(struct perf_sched *sched)
694 if (!sched->saved_states)
697 sched->saved_states--;
698 sched->state = sched->saved[sched->saved_states];
700 /* continue with next counter: */
701 clear_bit(sched->state.counter++, sched->state.used);
707 * Select a counter for the current event to schedule. Return true on
710 static bool __perf_sched_find_counter(struct perf_sched *sched)
712 struct event_constraint *c;
715 if (!sched->state.unassigned)
718 if (sched->state.event >= sched->max_events)
721 c = sched->constraints[sched->state.event];
722 /* Prefer fixed purpose counters */
723 if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
724 idx = INTEL_PMC_IDX_FIXED;
725 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
726 if (!__test_and_set_bit(idx, sched->state.used))
731 /* Grab the first unused counter starting with idx */
732 idx = sched->state.counter;
733 for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
734 if (!__test_and_set_bit(idx, sched->state.used)) {
735 if (sched->state.nr_gp++ >= sched->max_gp)
745 sched->state.counter = idx;
748 perf_sched_save_state(sched);
753 static bool perf_sched_find_counter(struct perf_sched *sched)
755 while (!__perf_sched_find_counter(sched)) {
756 if (!perf_sched_restore_state(sched))
764 * Go through all unassigned events and find the next one to schedule.
765 * Take events with the least weight first. Return true on success.
767 static bool perf_sched_next_event(struct perf_sched *sched)
769 struct event_constraint *c;
771 if (!sched->state.unassigned || !--sched->state.unassigned)
776 sched->state.event++;
777 if (sched->state.event >= sched->max_events) {
779 sched->state.event = 0;
780 sched->state.weight++;
781 if (sched->state.weight > sched->max_weight)
784 c = sched->constraints[sched->state.event];
785 } while (c->weight != sched->state.weight);
787 sched->state.counter = 0; /* start with first counter */
793 * Assign a counter for each event.
795 int perf_assign_events(struct event_constraint **constraints, int n,
796 int wmin, int wmax, int gpmax, int *assign)
798 struct perf_sched sched;
800 perf_sched_init(&sched, constraints, n, wmin, wmax, gpmax);
803 if (!perf_sched_find_counter(&sched))
806 assign[sched.state.event] = sched.state.counter;
807 } while (perf_sched_next_event(&sched));
809 return sched.state.unassigned;
811 EXPORT_SYMBOL_GPL(perf_assign_events);
813 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
815 struct event_constraint *c;
816 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
817 struct perf_event *e;
818 int i, wmin, wmax, unsched = 0;
819 struct hw_perf_event *hwc;
821 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
823 if (x86_pmu.start_scheduling)
824 x86_pmu.start_scheduling(cpuc);
826 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
827 cpuc->event_constraint[i] = NULL;
828 c = x86_pmu.get_event_constraints(cpuc, i, cpuc->event_list[i]);
829 cpuc->event_constraint[i] = c;
831 wmin = min(wmin, c->weight);
832 wmax = max(wmax, c->weight);
836 * fastpath, try to reuse previous register
838 for (i = 0; i < n; i++) {
839 hwc = &cpuc->event_list[i]->hw;
840 c = cpuc->event_constraint[i];
846 /* constraint still honored */
847 if (!test_bit(hwc->idx, c->idxmsk))
850 /* not already used */
851 if (test_bit(hwc->idx, used_mask))
854 __set_bit(hwc->idx, used_mask);
856 assign[i] = hwc->idx;
861 int gpmax = x86_pmu.num_counters;
864 * Do not allow scheduling of more than half the available
867 * This helps avoid counter starvation of sibling thread by
868 * ensuring at most half the counters cannot be in exclusive
869 * mode. There is no designated counters for the limits. Any
870 * N/2 counters can be used. This helps with events with
871 * specific counter constraints.
873 if (is_ht_workaround_enabled() && !cpuc->is_fake &&
874 READ_ONCE(cpuc->excl_cntrs->exclusive_present))
877 unsched = perf_assign_events(cpuc->event_constraint, n, wmin,
878 wmax, gpmax, assign);
882 * In case of success (unsched = 0), mark events as committed,
883 * so we do not put_constraint() in case new events are added
884 * and fail to be scheduled
886 * We invoke the lower level commit callback to lock the resource
888 * We do not need to do all of this in case we are called to
889 * validate an event group (assign == NULL)
891 if (!unsched && assign) {
892 for (i = 0; i < n; i++) {
893 e = cpuc->event_list[i];
894 e->hw.flags |= PERF_X86_EVENT_COMMITTED;
895 if (x86_pmu.commit_scheduling)
896 x86_pmu.commit_scheduling(cpuc, i, assign[i]);
900 if (!assign || unsched) {
902 for (i = 0; i < n; i++) {
903 e = cpuc->event_list[i];
905 * do not put_constraint() on comitted events,
906 * because they are good to go
908 if ((e->hw.flags & PERF_X86_EVENT_COMMITTED))
912 * release events that failed scheduling
914 if (x86_pmu.put_event_constraints)
915 x86_pmu.put_event_constraints(cpuc, e);
919 if (x86_pmu.stop_scheduling)
920 x86_pmu.stop_scheduling(cpuc);
922 return unsched ? -EINVAL : 0;
926 * dogrp: true if must collect siblings events (group)
927 * returns total number of events and error code
929 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
931 struct perf_event *event;
934 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
936 /* current number of events already accepted */
939 if (is_x86_event(leader)) {
942 cpuc->event_list[n] = leader;
948 list_for_each_entry(event, &leader->sibling_list, group_entry) {
949 if (!is_x86_event(event) ||
950 event->state <= PERF_EVENT_STATE_OFF)
956 cpuc->event_list[n] = event;
962 static inline void x86_assign_hw_event(struct perf_event *event,
963 struct cpu_hw_events *cpuc, int i)
965 struct hw_perf_event *hwc = &event->hw;
967 hwc->idx = cpuc->assign[i];
968 hwc->last_cpu = smp_processor_id();
969 hwc->last_tag = ++cpuc->tags[i];
971 if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
972 hwc->config_base = 0;
974 } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
975 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
976 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
977 hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
979 hwc->config_base = x86_pmu_config_addr(hwc->idx);
980 hwc->event_base = x86_pmu_event_addr(hwc->idx);
981 hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
985 static inline int match_prev_assignment(struct hw_perf_event *hwc,
986 struct cpu_hw_events *cpuc,
989 return hwc->idx == cpuc->assign[i] &&
990 hwc->last_cpu == smp_processor_id() &&
991 hwc->last_tag == cpuc->tags[i];
994 static void x86_pmu_start(struct perf_event *event, int flags);
996 static void x86_pmu_enable(struct pmu *pmu)
998 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
999 struct perf_event *event;
1000 struct hw_perf_event *hwc;
1001 int i, added = cpuc->n_added;
1003 if (!x86_pmu_initialized())
1009 if (cpuc->n_added) {
1010 int n_running = cpuc->n_events - cpuc->n_added;
1012 * apply assignment obtained either from
1013 * hw_perf_group_sched_in() or x86_pmu_enable()
1015 * step1: save events moving to new counters
1017 for (i = 0; i < n_running; i++) {
1018 event = cpuc->event_list[i];
1022 * we can avoid reprogramming counter if:
1023 * - assigned same counter as last time
1024 * - running on same CPU as last time
1025 * - no other event has used the counter since
1027 if (hwc->idx == -1 ||
1028 match_prev_assignment(hwc, cpuc, i))
1032 * Ensure we don't accidentally enable a stopped
1033 * counter simply because we rescheduled.
1035 if (hwc->state & PERF_HES_STOPPED)
1036 hwc->state |= PERF_HES_ARCH;
1038 x86_pmu_stop(event, PERF_EF_UPDATE);
1042 * step2: reprogram moved events into new counters
1044 for (i = 0; i < cpuc->n_events; i++) {
1045 event = cpuc->event_list[i];
1048 if (!match_prev_assignment(hwc, cpuc, i))
1049 x86_assign_hw_event(event, cpuc, i);
1050 else if (i < n_running)
1053 if (hwc->state & PERF_HES_ARCH)
1056 x86_pmu_start(event, PERF_EF_RELOAD);
1059 perf_events_lapic_init();
1065 x86_pmu.enable_all(added);
1068 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1071 * Set the next IRQ period, based on the hwc->period_left value.
1072 * To be called with the event disabled in hw:
1074 int x86_perf_event_set_period(struct perf_event *event)
1076 struct hw_perf_event *hwc = &event->hw;
1077 s64 left = local64_read(&hwc->period_left);
1078 s64 period = hwc->sample_period;
1079 int ret = 0, idx = hwc->idx;
1081 if (idx == INTEL_PMC_IDX_FIXED_BTS)
1085 * If we are way outside a reasonable range then just skip forward:
1087 if (unlikely(left <= -period)) {
1089 local64_set(&hwc->period_left, left);
1090 hwc->last_period = period;
1094 if (unlikely(left <= 0)) {
1096 local64_set(&hwc->period_left, left);
1097 hwc->last_period = period;
1101 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1103 if (unlikely(left < 2))
1106 if (left > x86_pmu.max_period)
1107 left = x86_pmu.max_period;
1109 if (x86_pmu.limit_period)
1110 left = x86_pmu.limit_period(event, left);
1112 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
1115 * The hw event starts counting from this event offset,
1116 * mark it to be able to extra future deltas:
1118 local64_set(&hwc->prev_count, (u64)-left);
1120 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1123 * Due to erratum on certan cpu we need
1124 * a second write to be sure the register
1125 * is updated properly
1127 if (x86_pmu.perfctr_second_write) {
1128 wrmsrl(hwc->event_base,
1129 (u64)(-left) & x86_pmu.cntval_mask);
1132 perf_event_update_userpage(event);
1137 void x86_pmu_enable_event(struct perf_event *event)
1139 if (__this_cpu_read(cpu_hw_events.enabled))
1140 __x86_pmu_enable_event(&event->hw,
1141 ARCH_PERFMON_EVENTSEL_ENABLE);
1145 * Add a single event to the PMU.
1147 * The event is added to the group of enabled events
1148 * but only if it can be scehduled with existing events.
1150 static int x86_pmu_add(struct perf_event *event, int flags)
1152 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1153 struct hw_perf_event *hwc;
1154 int assign[X86_PMC_IDX_MAX];
1159 n0 = cpuc->n_events;
1160 ret = n = collect_events(cpuc, event, false);
1164 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1165 if (!(flags & PERF_EF_START))
1166 hwc->state |= PERF_HES_ARCH;
1169 * If group events scheduling transaction was started,
1170 * skip the schedulability test here, it will be performed
1171 * at commit time (->commit_txn) as a whole.
1173 if (cpuc->group_flag & PERF_EVENT_TXN)
1176 ret = x86_pmu.schedule_events(cpuc, n, assign);
1180 * copy new assignment, now we know it is possible
1181 * will be used by hw_perf_enable()
1183 memcpy(cpuc->assign, assign, n*sizeof(int));
1187 * Commit the collect_events() state. See x86_pmu_del() and
1191 cpuc->n_added += n - n0;
1192 cpuc->n_txn += n - n0;
1199 static void x86_pmu_start(struct perf_event *event, int flags)
1201 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1202 int idx = event->hw.idx;
1204 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1207 if (WARN_ON_ONCE(idx == -1))
1210 if (flags & PERF_EF_RELOAD) {
1211 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1212 x86_perf_event_set_period(event);
1215 event->hw.state = 0;
1217 cpuc->events[idx] = event;
1218 __set_bit(idx, cpuc->active_mask);
1219 __set_bit(idx, cpuc->running);
1220 x86_pmu.enable(event);
1221 perf_event_update_userpage(event);
1224 void perf_event_print_debug(void)
1226 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1228 struct cpu_hw_events *cpuc;
1229 unsigned long flags;
1232 if (!x86_pmu.num_counters)
1235 local_irq_save(flags);
1237 cpu = smp_processor_id();
1238 cpuc = &per_cpu(cpu_hw_events, cpu);
1240 if (x86_pmu.version >= 2) {
1241 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1242 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1243 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1244 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1247 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1248 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1249 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1250 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1251 if (x86_pmu.pebs_constraints) {
1252 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1253 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1255 if (x86_pmu.lbr_nr) {
1256 rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1257 pr_info("CPU#%d: debugctl: %016llx\n", cpu, debugctl);
1260 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1262 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1263 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1264 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1266 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1268 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1269 cpu, idx, pmc_ctrl);
1270 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1271 cpu, idx, pmc_count);
1272 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1273 cpu, idx, prev_left);
1275 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1276 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1278 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1279 cpu, idx, pmc_count);
1281 local_irq_restore(flags);
1284 void x86_pmu_stop(struct perf_event *event, int flags)
1286 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1287 struct hw_perf_event *hwc = &event->hw;
1289 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1290 x86_pmu.disable(event);
1291 cpuc->events[hwc->idx] = NULL;
1292 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1293 hwc->state |= PERF_HES_STOPPED;
1296 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1298 * Drain the remaining delta count out of a event
1299 * that we are disabling:
1301 x86_perf_event_update(event);
1302 hwc->state |= PERF_HES_UPTODATE;
1306 static void x86_pmu_del(struct perf_event *event, int flags)
1308 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1312 * event is descheduled
1314 event->hw.flags &= ~PERF_X86_EVENT_COMMITTED;
1317 * If we're called during a txn, we don't need to do anything.
1318 * The events never got scheduled and ->cancel_txn will truncate
1321 * XXX assumes any ->del() called during a TXN will only be on
1322 * an event added during that same TXN.
1324 if (cpuc->group_flag & PERF_EVENT_TXN)
1328 * Not a TXN, therefore cleanup properly.
1330 x86_pmu_stop(event, PERF_EF_UPDATE);
1332 for (i = 0; i < cpuc->n_events; i++) {
1333 if (event == cpuc->event_list[i])
1337 if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1340 /* If we have a newly added event; make sure to decrease n_added. */
1341 if (i >= cpuc->n_events - cpuc->n_added)
1344 if (x86_pmu.put_event_constraints)
1345 x86_pmu.put_event_constraints(cpuc, event);
1347 /* Delete the array entry. */
1348 while (++i < cpuc->n_events) {
1349 cpuc->event_list[i-1] = cpuc->event_list[i];
1350 cpuc->event_constraint[i-1] = cpuc->event_constraint[i];
1354 perf_event_update_userpage(event);
1357 int x86_pmu_handle_irq(struct pt_regs *regs)
1359 struct perf_sample_data data;
1360 struct cpu_hw_events *cpuc;
1361 struct perf_event *event;
1362 int idx, handled = 0;
1365 cpuc = this_cpu_ptr(&cpu_hw_events);
1368 * Some chipsets need to unmask the LVTPC in a particular spot
1369 * inside the nmi handler. As a result, the unmasking was pushed
1370 * into all the nmi handlers.
1372 * This generic handler doesn't seem to have any issues where the
1373 * unmasking occurs so it was left at the top.
1375 apic_write(APIC_LVTPC, APIC_DM_NMI);
1377 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1378 if (!test_bit(idx, cpuc->active_mask)) {
1380 * Though we deactivated the counter some cpus
1381 * might still deliver spurious interrupts still
1382 * in flight. Catch them:
1384 if (__test_and_clear_bit(idx, cpuc->running))
1389 event = cpuc->events[idx];
1391 val = x86_perf_event_update(event);
1392 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1399 perf_sample_data_init(&data, 0, event->hw.last_period);
1401 if (!x86_perf_event_set_period(event))
1404 if (perf_event_overflow(event, &data, regs))
1405 x86_pmu_stop(event, 0);
1409 inc_irq_stat(apic_perf_irqs);
1414 void perf_events_lapic_init(void)
1416 if (!x86_pmu.apic || !x86_pmu_initialized())
1420 * Always use NMI for PMU
1422 apic_write(APIC_LVTPC, APIC_DM_NMI);
1426 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1432 if (!atomic_read(&active_events))
1435 start_clock = sched_clock();
1436 ret = x86_pmu.handle_irq(regs);
1437 finish_clock = sched_clock();
1439 perf_sample_event_took(finish_clock - start_clock);
1443 NOKPROBE_SYMBOL(perf_event_nmi_handler);
1445 struct event_constraint emptyconstraint;
1446 struct event_constraint unconstrained;
1449 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1451 unsigned int cpu = (long)hcpu;
1452 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1453 int i, ret = NOTIFY_OK;
1455 switch (action & ~CPU_TASKS_FROZEN) {
1456 case CPU_UP_PREPARE:
1457 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++)
1458 cpuc->kfree_on_online[i] = NULL;
1459 if (x86_pmu.cpu_prepare)
1460 ret = x86_pmu.cpu_prepare(cpu);
1464 if (x86_pmu.cpu_starting)
1465 x86_pmu.cpu_starting(cpu);
1469 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++) {
1470 kfree(cpuc->kfree_on_online[i]);
1471 cpuc->kfree_on_online[i] = NULL;
1476 if (x86_pmu.cpu_dying)
1477 x86_pmu.cpu_dying(cpu);
1480 case CPU_UP_CANCELED:
1482 if (x86_pmu.cpu_dead)
1483 x86_pmu.cpu_dead(cpu);
1493 static void __init pmu_check_apic(void)
1499 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1500 pr_info("no hardware sampling interrupt available.\n");
1503 * If we have a PMU initialized but no APIC
1504 * interrupts, we cannot sample hardware
1505 * events (user-space has to fall back and
1506 * sample via a hrtimer based software event):
1508 pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1512 static struct attribute_group x86_pmu_format_group = {
1518 * Remove all undefined events (x86_pmu.event_map(id) == 0)
1519 * out of events_attr attributes.
1521 static void __init filter_events(struct attribute **attrs)
1523 struct device_attribute *d;
1524 struct perf_pmu_events_attr *pmu_attr;
1527 for (i = 0; attrs[i]; i++) {
1528 d = (struct device_attribute *)attrs[i];
1529 pmu_attr = container_of(d, struct perf_pmu_events_attr, attr);
1531 if (pmu_attr->event_str)
1533 if (x86_pmu.event_map(i))
1536 for (j = i; attrs[j]; j++)
1537 attrs[j] = attrs[j + 1];
1539 /* Check the shifted attr. */
1544 /* Merge two pointer arrays */
1545 static __init struct attribute **merge_attr(struct attribute **a, struct attribute **b)
1547 struct attribute **new;
1550 for (j = 0; a[j]; j++)
1552 for (i = 0; b[i]; i++)
1556 new = kmalloc(sizeof(struct attribute *) * j, GFP_KERNEL);
1561 for (i = 0; a[i]; i++)
1563 for (i = 0; b[i]; i++)
1570 ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr,
1573 struct perf_pmu_events_attr *pmu_attr = \
1574 container_of(attr, struct perf_pmu_events_attr, attr);
1575 u64 config = x86_pmu.event_map(pmu_attr->id);
1577 /* string trumps id */
1578 if (pmu_attr->event_str)
1579 return sprintf(page, "%s", pmu_attr->event_str);
1581 return x86_pmu.events_sysfs_show(page, config);
1584 EVENT_ATTR(cpu-cycles, CPU_CYCLES );
1585 EVENT_ATTR(instructions, INSTRUCTIONS );
1586 EVENT_ATTR(cache-references, CACHE_REFERENCES );
1587 EVENT_ATTR(cache-misses, CACHE_MISSES );
1588 EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
1589 EVENT_ATTR(branch-misses, BRANCH_MISSES );
1590 EVENT_ATTR(bus-cycles, BUS_CYCLES );
1591 EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
1592 EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
1593 EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
1595 static struct attribute *empty_attrs;
1597 static struct attribute *events_attr[] = {
1598 EVENT_PTR(CPU_CYCLES),
1599 EVENT_PTR(INSTRUCTIONS),
1600 EVENT_PTR(CACHE_REFERENCES),
1601 EVENT_PTR(CACHE_MISSES),
1602 EVENT_PTR(BRANCH_INSTRUCTIONS),
1603 EVENT_PTR(BRANCH_MISSES),
1604 EVENT_PTR(BUS_CYCLES),
1605 EVENT_PTR(STALLED_CYCLES_FRONTEND),
1606 EVENT_PTR(STALLED_CYCLES_BACKEND),
1607 EVENT_PTR(REF_CPU_CYCLES),
1611 static struct attribute_group x86_pmu_events_group = {
1613 .attrs = events_attr,
1616 ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
1618 u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
1619 u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
1620 bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
1621 bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
1622 bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
1623 bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
1627 * We have whole page size to spend and just little data
1628 * to write, so we can safely use sprintf.
1630 ret = sprintf(page, "event=0x%02llx", event);
1633 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
1636 ret += sprintf(page + ret, ",edge");
1639 ret += sprintf(page + ret, ",pc");
1642 ret += sprintf(page + ret, ",any");
1645 ret += sprintf(page + ret, ",inv");
1648 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
1650 ret += sprintf(page + ret, "\n");
1655 static int __init init_hw_perf_events(void)
1657 struct x86_pmu_quirk *quirk;
1660 pr_info("Performance Events: ");
1662 switch (boot_cpu_data.x86_vendor) {
1663 case X86_VENDOR_INTEL:
1664 err = intel_pmu_init();
1666 case X86_VENDOR_AMD:
1667 err = amd_pmu_init();
1673 pr_cont("no PMU driver, software events only.\n");
1679 /* sanity check that the hardware exists or is emulated */
1680 if (!check_hw_exists())
1683 pr_cont("%s PMU driver.\n", x86_pmu.name);
1685 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1687 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1690 if (!x86_pmu.intel_ctrl)
1691 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1693 perf_events_lapic_init();
1694 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1696 unconstrained = (struct event_constraint)
1697 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1698 0, x86_pmu.num_counters, 0, 0);
1700 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
1702 if (x86_pmu.event_attrs)
1703 x86_pmu_events_group.attrs = x86_pmu.event_attrs;
1705 if (!x86_pmu.events_sysfs_show)
1706 x86_pmu_events_group.attrs = &empty_attrs;
1708 filter_events(x86_pmu_events_group.attrs);
1710 if (x86_pmu.cpu_events) {
1711 struct attribute **tmp;
1713 tmp = merge_attr(x86_pmu_events_group.attrs, x86_pmu.cpu_events);
1715 x86_pmu_events_group.attrs = tmp;
1718 pr_info("... version: %d\n", x86_pmu.version);
1719 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1720 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1721 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1722 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1723 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1724 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1726 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1727 perf_cpu_notifier(x86_pmu_notifier);
1731 early_initcall(init_hw_perf_events);
1733 static inline void x86_pmu_read(struct perf_event *event)
1735 x86_perf_event_update(event);
1739 * Start group events scheduling transaction
1740 * Set the flag to make pmu::enable() not perform the
1741 * schedulability test, it will be performed at commit time
1743 static void x86_pmu_start_txn(struct pmu *pmu)
1745 perf_pmu_disable(pmu);
1746 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1747 __this_cpu_write(cpu_hw_events.n_txn, 0);
1751 * Stop group events scheduling transaction
1752 * Clear the flag and pmu::enable() will perform the
1753 * schedulability test.
1755 static void x86_pmu_cancel_txn(struct pmu *pmu)
1757 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1759 * Truncate collected array by the number of events added in this
1760 * transaction. See x86_pmu_add() and x86_pmu_*_txn().
1762 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1763 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1764 perf_pmu_enable(pmu);
1768 * Commit group events scheduling transaction
1769 * Perform the group schedulability test as a whole
1770 * Return 0 if success
1772 * Does not cancel the transaction on failure; expects the caller to do this.
1774 static int x86_pmu_commit_txn(struct pmu *pmu)
1776 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1777 int assign[X86_PMC_IDX_MAX];
1782 if (!x86_pmu_initialized())
1785 ret = x86_pmu.schedule_events(cpuc, n, assign);
1790 * copy new assignment, now we know it is possible
1791 * will be used by hw_perf_enable()
1793 memcpy(cpuc->assign, assign, n*sizeof(int));
1795 cpuc->group_flag &= ~PERF_EVENT_TXN;
1796 perf_pmu_enable(pmu);
1800 * a fake_cpuc is used to validate event groups. Due to
1801 * the extra reg logic, we need to also allocate a fake
1802 * per_core and per_cpu structure. Otherwise, group events
1803 * using extra reg may conflict without the kernel being
1804 * able to catch this when the last event gets added to
1807 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1809 kfree(cpuc->shared_regs);
1813 static struct cpu_hw_events *allocate_fake_cpuc(void)
1815 struct cpu_hw_events *cpuc;
1816 int cpu = raw_smp_processor_id();
1818 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1820 return ERR_PTR(-ENOMEM);
1822 /* only needed, if we have extra_regs */
1823 if (x86_pmu.extra_regs) {
1824 cpuc->shared_regs = allocate_shared_regs(cpu);
1825 if (!cpuc->shared_regs)
1831 free_fake_cpuc(cpuc);
1832 return ERR_PTR(-ENOMEM);
1836 * validate that we can schedule this event
1838 static int validate_event(struct perf_event *event)
1840 struct cpu_hw_events *fake_cpuc;
1841 struct event_constraint *c;
1844 fake_cpuc = allocate_fake_cpuc();
1845 if (IS_ERR(fake_cpuc))
1846 return PTR_ERR(fake_cpuc);
1848 c = x86_pmu.get_event_constraints(fake_cpuc, -1, event);
1850 if (!c || !c->weight)
1853 if (x86_pmu.put_event_constraints)
1854 x86_pmu.put_event_constraints(fake_cpuc, event);
1856 free_fake_cpuc(fake_cpuc);
1862 * validate a single event group
1864 * validation include:
1865 * - check events are compatible which each other
1866 * - events do not compete for the same counter
1867 * - number of events <= number of counters
1869 * validation ensures the group can be loaded onto the
1870 * PMU if it was the only group available.
1872 static int validate_group(struct perf_event *event)
1874 struct perf_event *leader = event->group_leader;
1875 struct cpu_hw_events *fake_cpuc;
1876 int ret = -EINVAL, n;
1878 fake_cpuc = allocate_fake_cpuc();
1879 if (IS_ERR(fake_cpuc))
1880 return PTR_ERR(fake_cpuc);
1882 * the event is not yet connected with its
1883 * siblings therefore we must first collect
1884 * existing siblings, then add the new event
1885 * before we can simulate the scheduling
1887 n = collect_events(fake_cpuc, leader, true);
1891 fake_cpuc->n_events = n;
1892 n = collect_events(fake_cpuc, event, false);
1896 fake_cpuc->n_events = n;
1898 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1901 free_fake_cpuc(fake_cpuc);
1905 static int x86_pmu_event_init(struct perf_event *event)
1910 switch (event->attr.type) {
1912 case PERF_TYPE_HARDWARE:
1913 case PERF_TYPE_HW_CACHE:
1920 err = __x86_pmu_event_init(event);
1923 * we temporarily connect event to its pmu
1924 * such that validate_group() can classify
1925 * it as an x86 event using is_x86_event()
1930 if (event->group_leader != event)
1931 err = validate_group(event);
1933 err = validate_event(event);
1939 event->destroy(event);
1942 if (ACCESS_ONCE(x86_pmu.attr_rdpmc))
1943 event->hw.flags |= PERF_X86_EVENT_RDPMC_ALLOWED;
1948 static void refresh_pce(void *ignored)
1951 load_mm_cr4(current->mm);
1954 static void x86_pmu_event_mapped(struct perf_event *event)
1956 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
1959 if (atomic_inc_return(¤t->mm->context.perf_rdpmc_allowed) == 1)
1960 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
1963 static void x86_pmu_event_unmapped(struct perf_event *event)
1968 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
1971 if (atomic_dec_and_test(¤t->mm->context.perf_rdpmc_allowed))
1972 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
1975 static int x86_pmu_event_idx(struct perf_event *event)
1977 int idx = event->hw.idx;
1979 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
1982 if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
1983 idx -= INTEL_PMC_IDX_FIXED;
1990 static ssize_t get_attr_rdpmc(struct device *cdev,
1991 struct device_attribute *attr,
1994 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1997 static ssize_t set_attr_rdpmc(struct device *cdev,
1998 struct device_attribute *attr,
1999 const char *buf, size_t count)
2004 ret = kstrtoul(buf, 0, &val);
2011 if (x86_pmu.attr_rdpmc_broken)
2014 if ((val == 2) != (x86_pmu.attr_rdpmc == 2)) {
2016 * Changing into or out of always available, aka
2017 * perf-event-bypassing mode. This path is extremely slow,
2018 * but only root can trigger it, so it's okay.
2021 static_key_slow_inc(&rdpmc_always_available);
2023 static_key_slow_dec(&rdpmc_always_available);
2024 on_each_cpu(refresh_pce, NULL, 1);
2027 x86_pmu.attr_rdpmc = val;
2032 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
2034 static struct attribute *x86_pmu_attrs[] = {
2035 &dev_attr_rdpmc.attr,
2039 static struct attribute_group x86_pmu_attr_group = {
2040 .attrs = x86_pmu_attrs,
2043 static const struct attribute_group *x86_pmu_attr_groups[] = {
2044 &x86_pmu_attr_group,
2045 &x86_pmu_format_group,
2046 &x86_pmu_events_group,
2050 static void x86_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
2052 if (x86_pmu.sched_task)
2053 x86_pmu.sched_task(ctx, sched_in);
2056 void perf_check_microcode(void)
2058 if (x86_pmu.check_microcode)
2059 x86_pmu.check_microcode();
2061 EXPORT_SYMBOL_GPL(perf_check_microcode);
2063 static struct pmu pmu = {
2064 .pmu_enable = x86_pmu_enable,
2065 .pmu_disable = x86_pmu_disable,
2067 .attr_groups = x86_pmu_attr_groups,
2069 .event_init = x86_pmu_event_init,
2071 .event_mapped = x86_pmu_event_mapped,
2072 .event_unmapped = x86_pmu_event_unmapped,
2076 .start = x86_pmu_start,
2077 .stop = x86_pmu_stop,
2078 .read = x86_pmu_read,
2080 .start_txn = x86_pmu_start_txn,
2081 .cancel_txn = x86_pmu_cancel_txn,
2082 .commit_txn = x86_pmu_commit_txn,
2084 .event_idx = x86_pmu_event_idx,
2085 .sched_task = x86_pmu_sched_task,
2086 .task_ctx_size = sizeof(struct x86_perf_task_context),
2089 void arch_perf_update_userpage(struct perf_event *event,
2090 struct perf_event_mmap_page *userpg, u64 now)
2092 struct cyc2ns_data *data;
2094 userpg->cap_user_time = 0;
2095 userpg->cap_user_time_zero = 0;
2096 userpg->cap_user_rdpmc =
2097 !!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED);
2098 userpg->pmc_width = x86_pmu.cntval_bits;
2100 if (!sched_clock_stable())
2103 data = cyc2ns_read_begin();
2106 * Internal timekeeping for enabled/running/stopped times
2107 * is always in the local_clock domain.
2109 userpg->cap_user_time = 1;
2110 userpg->time_mult = data->cyc2ns_mul;
2111 userpg->time_shift = data->cyc2ns_shift;
2112 userpg->time_offset = data->cyc2ns_offset - now;
2115 * cap_user_time_zero doesn't make sense when we're using a different
2116 * time base for the records.
2118 if (event->clock == &local_clock) {
2119 userpg->cap_user_time_zero = 1;
2120 userpg->time_zero = data->cyc2ns_offset;
2123 cyc2ns_read_end(data);
2130 static int backtrace_stack(void *data, char *name)
2135 static void backtrace_address(void *data, unsigned long addr, int reliable)
2137 struct perf_callchain_entry *entry = data;
2139 perf_callchain_store(entry, addr);
2142 static const struct stacktrace_ops backtrace_ops = {
2143 .stack = backtrace_stack,
2144 .address = backtrace_address,
2145 .walk_stack = print_context_stack_bp,
2149 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
2151 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2152 /* TODO: We don't support guest os callchain now */
2156 perf_callchain_store(entry, regs->ip);
2158 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
2162 valid_user_frame(const void __user *fp, unsigned long size)
2164 return (__range_not_ok(fp, size, TASK_SIZE) == 0);
2167 static unsigned long get_segment_base(unsigned int segment)
2169 struct desc_struct *desc;
2170 int idx = segment >> 3;
2172 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2173 if (idx > LDT_ENTRIES)
2176 if (idx > current->active_mm->context.size)
2179 desc = current->active_mm->context.ldt;
2181 if (idx > GDT_ENTRIES)
2184 desc = raw_cpu_ptr(gdt_page.gdt);
2187 return get_desc_base(desc + idx);
2190 #ifdef CONFIG_COMPAT
2192 #include <asm/compat.h>
2195 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2197 /* 32-bit process in 64-bit kernel. */
2198 unsigned long ss_base, cs_base;
2199 struct stack_frame_ia32 frame;
2200 const void __user *fp;
2202 if (!test_thread_flag(TIF_IA32))
2205 cs_base = get_segment_base(regs->cs);
2206 ss_base = get_segment_base(regs->ss);
2208 fp = compat_ptr(ss_base + regs->bp);
2209 while (entry->nr < PERF_MAX_STACK_DEPTH) {
2210 unsigned long bytes;
2211 frame.next_frame = 0;
2212 frame.return_address = 0;
2214 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2218 if (!valid_user_frame(fp, sizeof(frame)))
2221 perf_callchain_store(entry, cs_base + frame.return_address);
2222 fp = compat_ptr(ss_base + frame.next_frame);
2228 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2235 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
2237 struct stack_frame frame;
2238 const void __user *fp;
2240 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2241 /* TODO: We don't support guest os callchain now */
2246 * We don't know what to do with VM86 stacks.. ignore them for now.
2248 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2251 fp = (void __user *)regs->bp;
2253 perf_callchain_store(entry, regs->ip);
2258 if (perf_callchain_user32(regs, entry))
2261 while (entry->nr < PERF_MAX_STACK_DEPTH) {
2262 unsigned long bytes;
2263 frame.next_frame = NULL;
2264 frame.return_address = 0;
2266 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2270 if (!valid_user_frame(fp, sizeof(frame)))
2273 perf_callchain_store(entry, frame.return_address);
2274 fp = frame.next_frame;
2279 * Deal with code segment offsets for the various execution modes:
2281 * VM86 - the good olde 16 bit days, where the linear address is
2282 * 20 bits and we use regs->ip + 0x10 * regs->cs.
2284 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
2285 * to figure out what the 32bit base address is.
2287 * X32 - has TIF_X32 set, but is running in x86_64
2289 * X86_64 - CS,DS,SS,ES are all zero based.
2291 static unsigned long code_segment_base(struct pt_regs *regs)
2294 * For IA32 we look at the GDT/LDT segment base to convert the
2295 * effective IP to a linear address.
2298 #ifdef CONFIG_X86_32
2300 * If we are in VM86 mode, add the segment offset to convert to a
2303 if (regs->flags & X86_VM_MASK)
2304 return 0x10 * regs->cs;
2306 if (user_mode(regs) && regs->cs != __USER_CS)
2307 return get_segment_base(regs->cs);
2309 if (user_mode(regs) && !user_64bit_mode(regs) &&
2310 regs->cs != __USER32_CS)
2311 return get_segment_base(regs->cs);
2316 unsigned long perf_instruction_pointer(struct pt_regs *regs)
2318 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
2319 return perf_guest_cbs->get_guest_ip();
2321 return regs->ip + code_segment_base(regs);
2324 unsigned long perf_misc_flags(struct pt_regs *regs)
2328 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2329 if (perf_guest_cbs->is_user_mode())
2330 misc |= PERF_RECORD_MISC_GUEST_USER;
2332 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
2334 if (user_mode(regs))
2335 misc |= PERF_RECORD_MISC_USER;
2337 misc |= PERF_RECORD_MISC_KERNEL;
2340 if (regs->flags & PERF_EFLAGS_EXACT)
2341 misc |= PERF_RECORD_MISC_EXACT_IP;
2346 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
2348 cap->version = x86_pmu.version;
2349 cap->num_counters_gp = x86_pmu.num_counters;
2350 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
2351 cap->bit_width_gp = x86_pmu.cntval_bits;
2352 cap->bit_width_fixed = x86_pmu.cntval_bits;
2353 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
2354 cap->events_mask_len = x86_pmu.events_mask_len;
2356 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);