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/timer.h>
38 #include "perf_event.h"
40 struct x86_pmu x86_pmu __read_mostly;
42 DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
46 u64 __read_mostly hw_cache_event_ids
47 [PERF_COUNT_HW_CACHE_MAX]
48 [PERF_COUNT_HW_CACHE_OP_MAX]
49 [PERF_COUNT_HW_CACHE_RESULT_MAX];
50 u64 __read_mostly hw_cache_extra_regs
51 [PERF_COUNT_HW_CACHE_MAX]
52 [PERF_COUNT_HW_CACHE_OP_MAX]
53 [PERF_COUNT_HW_CACHE_RESULT_MAX];
56 * Propagate event elapsed time into the generic event.
57 * Can only be executed on the CPU where the event is active.
58 * Returns the delta events processed.
60 u64 x86_perf_event_update(struct perf_event *event)
62 struct hw_perf_event *hwc = &event->hw;
63 int shift = 64 - x86_pmu.cntval_bits;
64 u64 prev_raw_count, new_raw_count;
68 if (idx == INTEL_PMC_IDX_FIXED_BTS)
72 * Careful: an NMI might modify the previous event value.
74 * Our tactic to handle this is to first atomically read and
75 * exchange a new raw count - then add that new-prev delta
76 * count to the generic event atomically:
79 prev_raw_count = local64_read(&hwc->prev_count);
80 rdpmcl(hwc->event_base_rdpmc, new_raw_count);
82 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
83 new_raw_count) != prev_raw_count)
87 * Now we have the new raw value and have updated the prev
88 * timestamp already. We can now calculate the elapsed delta
89 * (event-)time and add that to the generic event.
91 * Careful, not all hw sign-extends above the physical width
94 delta = (new_raw_count << shift) - (prev_raw_count << shift);
97 local64_add(delta, &event->count);
98 local64_sub(delta, &hwc->period_left);
100 return new_raw_count;
104 * Find and validate any extra registers to set up.
106 static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
108 struct hw_perf_event_extra *reg;
109 struct extra_reg *er;
111 reg = &event->hw.extra_reg;
113 if (!x86_pmu.extra_regs)
116 for (er = x86_pmu.extra_regs; er->msr; er++) {
117 if (er->event != (config & er->config_mask))
119 if (event->attr.config1 & ~er->valid_mask)
121 /* Check if the extra msrs can be safely accessed*/
122 if (!er->extra_msr_access)
126 reg->config = event->attr.config1;
133 static atomic_t active_events;
134 static DEFINE_MUTEX(pmc_reserve_mutex);
136 #ifdef CONFIG_X86_LOCAL_APIC
138 static bool reserve_pmc_hardware(void)
142 for (i = 0; i < x86_pmu.num_counters; i++) {
143 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
147 for (i = 0; i < x86_pmu.num_counters; i++) {
148 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
155 for (i--; i >= 0; i--)
156 release_evntsel_nmi(x86_pmu_config_addr(i));
158 i = x86_pmu.num_counters;
161 for (i--; i >= 0; i--)
162 release_perfctr_nmi(x86_pmu_event_addr(i));
167 static void release_pmc_hardware(void)
171 for (i = 0; i < x86_pmu.num_counters; i++) {
172 release_perfctr_nmi(x86_pmu_event_addr(i));
173 release_evntsel_nmi(x86_pmu_config_addr(i));
179 static bool reserve_pmc_hardware(void) { return true; }
180 static void release_pmc_hardware(void) {}
184 static bool check_hw_exists(void)
186 u64 val, val_fail, val_new= ~0;
187 int i, reg, reg_fail, ret = 0;
191 * Check to see if the BIOS enabled any of the counters, if so
194 for (i = 0; i < x86_pmu.num_counters; i++) {
195 reg = x86_pmu_config_addr(i);
196 ret = rdmsrl_safe(reg, &val);
199 if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
206 if (x86_pmu.num_counters_fixed) {
207 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
208 ret = rdmsrl_safe(reg, &val);
211 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
212 if (val & (0x03 << i*4)) {
221 * Read the current value, change it and read it back to see if it
222 * matches, this is needed to detect certain hardware emulators
223 * (qemu/kvm) that don't trap on the MSR access and always return 0s.
225 reg = x86_pmu_event_addr(0);
226 if (rdmsrl_safe(reg, &val))
229 ret = wrmsrl_safe(reg, val);
230 ret |= rdmsrl_safe(reg, &val_new);
231 if (ret || val != val_new)
235 * We still allow the PMU driver to operate:
238 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
239 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg_fail, val_fail);
245 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
246 printk(boot_cpu_has(X86_FEATURE_HYPERVISOR) ? KERN_INFO : KERN_ERR
247 "Failed to access perfctr msr (MSR %x is %Lx)\n", reg, val_new);
252 static void hw_perf_event_destroy(struct perf_event *event)
254 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
255 release_pmc_hardware();
256 release_ds_buffers();
257 mutex_unlock(&pmc_reserve_mutex);
261 static inline int x86_pmu_initialized(void)
263 return x86_pmu.handle_irq != NULL;
267 set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
269 struct perf_event_attr *attr = &event->attr;
270 unsigned int cache_type, cache_op, cache_result;
273 config = attr->config;
275 cache_type = (config >> 0) & 0xff;
276 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
279 cache_op = (config >> 8) & 0xff;
280 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
283 cache_result = (config >> 16) & 0xff;
284 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
287 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
296 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
297 return x86_pmu_extra_regs(val, event);
300 int x86_setup_perfctr(struct perf_event *event)
302 struct perf_event_attr *attr = &event->attr;
303 struct hw_perf_event *hwc = &event->hw;
306 if (!is_sampling_event(event)) {
307 hwc->sample_period = x86_pmu.max_period;
308 hwc->last_period = hwc->sample_period;
309 local64_set(&hwc->period_left, hwc->sample_period);
312 if (attr->type == PERF_TYPE_RAW)
313 return x86_pmu_extra_regs(event->attr.config, event);
315 if (attr->type == PERF_TYPE_HW_CACHE)
316 return set_ext_hw_attr(hwc, event);
318 if (attr->config >= x86_pmu.max_events)
324 config = x86_pmu.event_map(attr->config);
335 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
336 !attr->freq && hwc->sample_period == 1) {
337 /* BTS is not supported by this architecture. */
338 if (!x86_pmu.bts_active)
341 /* BTS is currently only allowed for user-mode. */
342 if (!attr->exclude_kernel)
346 hwc->config |= config;
352 * check that branch_sample_type is compatible with
353 * settings needed for precise_ip > 1 which implies
354 * using the LBR to capture ALL taken branches at the
355 * priv levels of the measurement
357 static inline int precise_br_compat(struct perf_event *event)
359 u64 m = event->attr.branch_sample_type;
362 /* must capture all branches */
363 if (!(m & PERF_SAMPLE_BRANCH_ANY))
366 m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
368 if (!event->attr.exclude_user)
369 b |= PERF_SAMPLE_BRANCH_USER;
371 if (!event->attr.exclude_kernel)
372 b |= PERF_SAMPLE_BRANCH_KERNEL;
375 * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
381 int x86_pmu_hw_config(struct perf_event *event)
383 if (event->attr.precise_ip) {
386 /* Support for constant skid */
387 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
390 /* Support for IP fixup */
391 if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
395 if (event->attr.precise_ip > precise)
398 * check that PEBS LBR correction does not conflict with
399 * whatever the user is asking with attr->branch_sample_type
401 if (event->attr.precise_ip > 1 &&
402 x86_pmu.intel_cap.pebs_format < 2) {
403 u64 *br_type = &event->attr.branch_sample_type;
405 if (has_branch_stack(event)) {
406 if (!precise_br_compat(event))
409 /* branch_sample_type is compatible */
413 * user did not specify branch_sample_type
415 * For PEBS fixups, we capture all
416 * the branches at the priv level of the
419 *br_type = PERF_SAMPLE_BRANCH_ANY;
421 if (!event->attr.exclude_user)
422 *br_type |= PERF_SAMPLE_BRANCH_USER;
424 if (!event->attr.exclude_kernel)
425 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
432 * (keep 'enabled' bit clear for now)
434 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
437 * Count user and OS events unless requested not to
439 if (!event->attr.exclude_user)
440 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
441 if (!event->attr.exclude_kernel)
442 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
444 if (event->attr.type == PERF_TYPE_RAW)
445 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
447 if (event->attr.sample_period && x86_pmu.limit_period) {
448 if (x86_pmu.limit_period(event, event->attr.sample_period) >
449 event->attr.sample_period)
453 return x86_setup_perfctr(event);
457 * Setup the hardware configuration for a given attr_type
459 static int __x86_pmu_event_init(struct perf_event *event)
463 if (!x86_pmu_initialized())
467 if (!atomic_inc_not_zero(&active_events)) {
468 mutex_lock(&pmc_reserve_mutex);
469 if (atomic_read(&active_events) == 0) {
470 if (!reserve_pmc_hardware())
473 reserve_ds_buffers();
476 atomic_inc(&active_events);
477 mutex_unlock(&pmc_reserve_mutex);
482 event->destroy = hw_perf_event_destroy;
485 event->hw.last_cpu = -1;
486 event->hw.last_tag = ~0ULL;
489 event->hw.extra_reg.idx = EXTRA_REG_NONE;
490 event->hw.branch_reg.idx = EXTRA_REG_NONE;
492 return x86_pmu.hw_config(event);
495 void x86_pmu_disable_all(void)
497 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
500 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
503 if (!test_bit(idx, cpuc->active_mask))
505 rdmsrl(x86_pmu_config_addr(idx), val);
506 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
508 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
509 wrmsrl(x86_pmu_config_addr(idx), val);
513 static void x86_pmu_disable(struct pmu *pmu)
515 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
517 if (!x86_pmu_initialized())
527 x86_pmu.disable_all();
530 void x86_pmu_enable_all(int added)
532 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
535 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
536 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
538 if (!test_bit(idx, cpuc->active_mask))
541 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
545 static struct pmu pmu;
547 static inline int is_x86_event(struct perf_event *event)
549 return event->pmu == &pmu;
553 * Event scheduler state:
555 * Assign events iterating over all events and counters, beginning
556 * with events with least weights first. Keep the current iterator
557 * state in struct sched_state.
561 int event; /* event index */
562 int counter; /* counter index */
563 int unassigned; /* number of events to be assigned left */
564 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
567 /* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
568 #define SCHED_STATES_MAX 2
573 struct perf_event **events;
574 struct sched_state state;
576 struct sched_state saved[SCHED_STATES_MAX];
580 * Initialize interator that runs through all events and counters.
582 static void perf_sched_init(struct perf_sched *sched, struct perf_event **events,
583 int num, int wmin, int wmax)
587 memset(sched, 0, sizeof(*sched));
588 sched->max_events = num;
589 sched->max_weight = wmax;
590 sched->events = events;
592 for (idx = 0; idx < num; idx++) {
593 if (events[idx]->hw.constraint->weight == wmin)
597 sched->state.event = idx; /* start with min weight */
598 sched->state.weight = wmin;
599 sched->state.unassigned = num;
602 static void perf_sched_save_state(struct perf_sched *sched)
604 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
607 sched->saved[sched->saved_states] = sched->state;
608 sched->saved_states++;
611 static bool perf_sched_restore_state(struct perf_sched *sched)
613 if (!sched->saved_states)
616 sched->saved_states--;
617 sched->state = sched->saved[sched->saved_states];
619 /* continue with next counter: */
620 clear_bit(sched->state.counter++, sched->state.used);
626 * Select a counter for the current event to schedule. Return true on
629 static bool __perf_sched_find_counter(struct perf_sched *sched)
631 struct event_constraint *c;
634 if (!sched->state.unassigned)
637 if (sched->state.event >= sched->max_events)
640 c = sched->events[sched->state.event]->hw.constraint;
641 /* Prefer fixed purpose counters */
642 if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
643 idx = INTEL_PMC_IDX_FIXED;
644 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
645 if (!__test_and_set_bit(idx, sched->state.used))
649 /* Grab the first unused counter starting with idx */
650 idx = sched->state.counter;
651 for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
652 if (!__test_and_set_bit(idx, sched->state.used))
659 sched->state.counter = idx;
662 perf_sched_save_state(sched);
667 static bool perf_sched_find_counter(struct perf_sched *sched)
669 while (!__perf_sched_find_counter(sched)) {
670 if (!perf_sched_restore_state(sched))
678 * Go through all unassigned events and find the next one to schedule.
679 * Take events with the least weight first. Return true on success.
681 static bool perf_sched_next_event(struct perf_sched *sched)
683 struct event_constraint *c;
685 if (!sched->state.unassigned || !--sched->state.unassigned)
690 sched->state.event++;
691 if (sched->state.event >= sched->max_events) {
693 sched->state.event = 0;
694 sched->state.weight++;
695 if (sched->state.weight > sched->max_weight)
698 c = sched->events[sched->state.event]->hw.constraint;
699 } while (c->weight != sched->state.weight);
701 sched->state.counter = 0; /* start with first counter */
707 * Assign a counter for each event.
709 int perf_assign_events(struct perf_event **events, int n,
710 int wmin, int wmax, int *assign)
712 struct perf_sched sched;
714 perf_sched_init(&sched, events, n, wmin, wmax);
717 if (!perf_sched_find_counter(&sched))
720 assign[sched.state.event] = sched.state.counter;
721 } while (perf_sched_next_event(&sched));
723 return sched.state.unassigned;
725 EXPORT_SYMBOL_GPL(perf_assign_events);
727 int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
729 struct event_constraint *c;
730 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
731 struct perf_event *e;
732 int i, wmin, wmax, num = 0;
733 struct hw_perf_event *hwc;
735 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
737 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
738 hwc = &cpuc->event_list[i]->hw;
739 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
742 wmin = min(wmin, c->weight);
743 wmax = max(wmax, c->weight);
747 * fastpath, try to reuse previous register
749 for (i = 0; i < n; i++) {
750 hwc = &cpuc->event_list[i]->hw;
757 /* constraint still honored */
758 if (!test_bit(hwc->idx, c->idxmsk))
761 /* not already used */
762 if (test_bit(hwc->idx, used_mask))
765 __set_bit(hwc->idx, used_mask);
767 assign[i] = hwc->idx;
772 num = perf_assign_events(cpuc->event_list, n, wmin,
776 * Mark the event as committed, so we do not put_constraint()
777 * in case new events are added and fail scheduling.
779 if (!num && assign) {
780 for (i = 0; i < n; i++) {
781 e = cpuc->event_list[i];
782 e->hw.flags |= PERF_X86_EVENT_COMMITTED;
786 * scheduling failed or is just a simulation,
787 * free resources if necessary
789 if (!assign || num) {
790 for (i = 0; i < n; i++) {
791 e = cpuc->event_list[i];
793 * do not put_constraint() on comitted events,
794 * because they are good to go
796 if ((e->hw.flags & PERF_X86_EVENT_COMMITTED))
799 if (x86_pmu.put_event_constraints)
800 x86_pmu.put_event_constraints(cpuc, e);
803 return num ? -EINVAL : 0;
807 * dogrp: true if must collect siblings events (group)
808 * returns total number of events and error code
810 static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
812 struct perf_event *event;
815 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
817 /* current number of events already accepted */
820 if (is_x86_event(leader)) {
823 cpuc->event_list[n] = leader;
829 list_for_each_entry(event, &leader->sibling_list, group_entry) {
830 if (!is_x86_event(event) ||
831 event->state <= PERF_EVENT_STATE_OFF)
837 cpuc->event_list[n] = event;
843 static inline void x86_assign_hw_event(struct perf_event *event,
844 struct cpu_hw_events *cpuc, int i)
846 struct hw_perf_event *hwc = &event->hw;
848 hwc->idx = cpuc->assign[i];
849 hwc->last_cpu = smp_processor_id();
850 hwc->last_tag = ++cpuc->tags[i];
852 if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
853 hwc->config_base = 0;
855 } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
856 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
857 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
858 hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
860 hwc->config_base = x86_pmu_config_addr(hwc->idx);
861 hwc->event_base = x86_pmu_event_addr(hwc->idx);
862 hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
866 static inline int match_prev_assignment(struct hw_perf_event *hwc,
867 struct cpu_hw_events *cpuc,
870 return hwc->idx == cpuc->assign[i] &&
871 hwc->last_cpu == smp_processor_id() &&
872 hwc->last_tag == cpuc->tags[i];
875 static void x86_pmu_start(struct perf_event *event, int flags);
877 static void x86_pmu_enable(struct pmu *pmu)
879 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
880 struct perf_event *event;
881 struct hw_perf_event *hwc;
882 int i, added = cpuc->n_added;
884 if (!x86_pmu_initialized())
891 int n_running = cpuc->n_events - cpuc->n_added;
893 * apply assignment obtained either from
894 * hw_perf_group_sched_in() or x86_pmu_enable()
896 * step1: save events moving to new counters
898 for (i = 0; i < n_running; i++) {
899 event = cpuc->event_list[i];
903 * we can avoid reprogramming counter if:
904 * - assigned same counter as last time
905 * - running on same CPU as last time
906 * - no other event has used the counter since
908 if (hwc->idx == -1 ||
909 match_prev_assignment(hwc, cpuc, i))
913 * Ensure we don't accidentally enable a stopped
914 * counter simply because we rescheduled.
916 if (hwc->state & PERF_HES_STOPPED)
917 hwc->state |= PERF_HES_ARCH;
919 x86_pmu_stop(event, PERF_EF_UPDATE);
923 * step2: reprogram moved events into new counters
925 for (i = 0; i < cpuc->n_events; i++) {
926 event = cpuc->event_list[i];
929 if (!match_prev_assignment(hwc, cpuc, i))
930 x86_assign_hw_event(event, cpuc, i);
931 else if (i < n_running)
934 if (hwc->state & PERF_HES_ARCH)
937 x86_pmu_start(event, PERF_EF_RELOAD);
940 perf_events_lapic_init();
946 x86_pmu.enable_all(added);
949 static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
952 * Set the next IRQ period, based on the hwc->period_left value.
953 * To be called with the event disabled in hw:
955 int x86_perf_event_set_period(struct perf_event *event)
957 struct hw_perf_event *hwc = &event->hw;
958 s64 left = local64_read(&hwc->period_left);
959 s64 period = hwc->sample_period;
960 int ret = 0, idx = hwc->idx;
962 if (idx == INTEL_PMC_IDX_FIXED_BTS)
966 * If we are way outside a reasonable range then just skip forward:
968 if (unlikely(left <= -period)) {
970 local64_set(&hwc->period_left, left);
971 hwc->last_period = period;
975 if (unlikely(left <= 0)) {
977 local64_set(&hwc->period_left, left);
978 hwc->last_period = period;
982 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
984 if (unlikely(left < 2))
987 if (left > x86_pmu.max_period)
988 left = x86_pmu.max_period;
990 if (x86_pmu.limit_period)
991 left = x86_pmu.limit_period(event, left);
993 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
996 * The hw event starts counting from this event offset,
997 * mark it to be able to extra future deltas:
999 local64_set(&hwc->prev_count, (u64)-left);
1001 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1004 * Due to erratum on certan cpu we need
1005 * a second write to be sure the register
1006 * is updated properly
1008 if (x86_pmu.perfctr_second_write) {
1009 wrmsrl(hwc->event_base,
1010 (u64)(-left) & x86_pmu.cntval_mask);
1013 perf_event_update_userpage(event);
1018 void x86_pmu_enable_event(struct perf_event *event)
1020 if (__this_cpu_read(cpu_hw_events.enabled))
1021 __x86_pmu_enable_event(&event->hw,
1022 ARCH_PERFMON_EVENTSEL_ENABLE);
1026 * Add a single event to the PMU.
1028 * The event is added to the group of enabled events
1029 * but only if it can be scehduled with existing events.
1031 static int x86_pmu_add(struct perf_event *event, int flags)
1033 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1034 struct hw_perf_event *hwc;
1035 int assign[X86_PMC_IDX_MAX];
1040 perf_pmu_disable(event->pmu);
1041 n0 = cpuc->n_events;
1042 ret = n = collect_events(cpuc, event, false);
1046 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1047 if (!(flags & PERF_EF_START))
1048 hwc->state |= PERF_HES_ARCH;
1051 * If group events scheduling transaction was started,
1052 * skip the schedulability test here, it will be performed
1053 * at commit time (->commit_txn) as a whole.
1055 if (cpuc->group_flag & PERF_EVENT_TXN)
1058 ret = x86_pmu.schedule_events(cpuc, n, assign);
1062 * copy new assignment, now we know it is possible
1063 * will be used by hw_perf_enable()
1065 memcpy(cpuc->assign, assign, n*sizeof(int));
1069 * Commit the collect_events() state. See x86_pmu_del() and
1073 cpuc->n_added += n - n0;
1074 cpuc->n_txn += n - n0;
1078 perf_pmu_enable(event->pmu);
1082 static void x86_pmu_start(struct perf_event *event, int flags)
1084 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1085 int idx = event->hw.idx;
1087 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1090 if (WARN_ON_ONCE(idx == -1))
1093 if (flags & PERF_EF_RELOAD) {
1094 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1095 x86_perf_event_set_period(event);
1098 event->hw.state = 0;
1100 cpuc->events[idx] = event;
1101 __set_bit(idx, cpuc->active_mask);
1102 __set_bit(idx, cpuc->running);
1103 x86_pmu.enable(event);
1104 perf_event_update_userpage(event);
1107 void perf_event_print_debug(void)
1109 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1111 struct cpu_hw_events *cpuc;
1112 unsigned long flags;
1115 if (!x86_pmu.num_counters)
1118 local_irq_save(flags);
1120 cpu = smp_processor_id();
1121 cpuc = &per_cpu(cpu_hw_events, cpu);
1123 if (x86_pmu.version >= 2) {
1124 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1125 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1126 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1127 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1128 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1131 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1132 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1133 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1134 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1135 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1137 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1139 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1140 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1141 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
1143 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1145 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1146 cpu, idx, pmc_ctrl);
1147 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1148 cpu, idx, pmc_count);
1149 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1150 cpu, idx, prev_left);
1152 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
1153 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1155 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1156 cpu, idx, pmc_count);
1158 local_irq_restore(flags);
1161 void x86_pmu_stop(struct perf_event *event, int flags)
1163 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1164 struct hw_perf_event *hwc = &event->hw;
1166 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1167 x86_pmu.disable(event);
1168 cpuc->events[hwc->idx] = NULL;
1169 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1170 hwc->state |= PERF_HES_STOPPED;
1173 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1175 * Drain the remaining delta count out of a event
1176 * that we are disabling:
1178 x86_perf_event_update(event);
1179 hwc->state |= PERF_HES_UPTODATE;
1183 static void x86_pmu_del(struct perf_event *event, int flags)
1185 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1189 * event is descheduled
1191 event->hw.flags &= ~PERF_X86_EVENT_COMMITTED;
1194 * If we're called during a txn, we don't need to do anything.
1195 * The events never got scheduled and ->cancel_txn will truncate
1198 * XXX assumes any ->del() called during a TXN will only be on
1199 * an event added during that same TXN.
1201 if (cpuc->group_flag & PERF_EVENT_TXN)
1205 * Not a TXN, therefore cleanup properly.
1207 x86_pmu_stop(event, PERF_EF_UPDATE);
1209 for (i = 0; i < cpuc->n_events; i++) {
1210 if (event == cpuc->event_list[i])
1214 if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1217 /* If we have a newly added event; make sure to decrease n_added. */
1218 if (i >= cpuc->n_events - cpuc->n_added)
1221 if (x86_pmu.put_event_constraints)
1222 x86_pmu.put_event_constraints(cpuc, event);
1224 /* Delete the array entry. */
1225 while (++i < cpuc->n_events)
1226 cpuc->event_list[i-1] = cpuc->event_list[i];
1229 perf_event_update_userpage(event);
1232 int x86_pmu_handle_irq(struct pt_regs *regs)
1234 struct perf_sample_data data;
1235 struct cpu_hw_events *cpuc;
1236 struct perf_event *event;
1237 int idx, handled = 0;
1240 cpuc = &__get_cpu_var(cpu_hw_events);
1243 * Some chipsets need to unmask the LVTPC in a particular spot
1244 * inside the nmi handler. As a result, the unmasking was pushed
1245 * into all the nmi handlers.
1247 * This generic handler doesn't seem to have any issues where the
1248 * unmasking occurs so it was left at the top.
1250 apic_write(APIC_LVTPC, APIC_DM_NMI);
1252 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
1253 if (!test_bit(idx, cpuc->active_mask)) {
1255 * Though we deactivated the counter some cpus
1256 * might still deliver spurious interrupts still
1257 * in flight. Catch them:
1259 if (__test_and_clear_bit(idx, cpuc->running))
1264 event = cpuc->events[idx];
1266 val = x86_perf_event_update(event);
1267 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1274 perf_sample_data_init(&data, 0, event->hw.last_period);
1276 if (!x86_perf_event_set_period(event))
1279 if (perf_event_overflow(event, &data, regs))
1280 x86_pmu_stop(event, 0);
1284 inc_irq_stat(apic_perf_irqs);
1289 void perf_events_lapic_init(void)
1291 if (!x86_pmu.apic || !x86_pmu_initialized())
1295 * Always use NMI for PMU
1297 apic_write(APIC_LVTPC, APIC_DM_NMI);
1301 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1307 if (!atomic_read(&active_events))
1310 start_clock = sched_clock();
1311 ret = x86_pmu.handle_irq(regs);
1312 finish_clock = sched_clock();
1314 perf_sample_event_took(finish_clock - start_clock);
1318 NOKPROBE_SYMBOL(perf_event_nmi_handler);
1320 struct event_constraint emptyconstraint;
1321 struct event_constraint unconstrained;
1324 x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1326 unsigned int cpu = (long)hcpu;
1327 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1328 int ret = NOTIFY_OK;
1330 switch (action & ~CPU_TASKS_FROZEN) {
1331 case CPU_UP_PREPARE:
1332 cpuc->kfree_on_online = NULL;
1333 if (x86_pmu.cpu_prepare)
1334 ret = x86_pmu.cpu_prepare(cpu);
1338 if (x86_pmu.attr_rdpmc)
1339 set_in_cr4(X86_CR4_PCE);
1340 if (x86_pmu.cpu_starting)
1341 x86_pmu.cpu_starting(cpu);
1345 kfree(cpuc->kfree_on_online);
1349 if (x86_pmu.cpu_dying)
1350 x86_pmu.cpu_dying(cpu);
1353 case CPU_UP_CANCELED:
1355 if (x86_pmu.cpu_dead)
1356 x86_pmu.cpu_dead(cpu);
1366 static void __init pmu_check_apic(void)
1372 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1373 pr_info("no hardware sampling interrupt available.\n");
1376 * If we have a PMU initialized but no APIC
1377 * interrupts, we cannot sample hardware
1378 * events (user-space has to fall back and
1379 * sample via a hrtimer based software event):
1381 pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1385 static struct attribute_group x86_pmu_format_group = {
1391 * Remove all undefined events (x86_pmu.event_map(id) == 0)
1392 * out of events_attr attributes.
1394 static void __init filter_events(struct attribute **attrs)
1396 struct device_attribute *d;
1397 struct perf_pmu_events_attr *pmu_attr;
1400 for (i = 0; attrs[i]; i++) {
1401 d = (struct device_attribute *)attrs[i];
1402 pmu_attr = container_of(d, struct perf_pmu_events_attr, attr);
1404 if (pmu_attr->event_str)
1406 if (x86_pmu.event_map(i))
1409 for (j = i; attrs[j]; j++)
1410 attrs[j] = attrs[j + 1];
1412 /* Check the shifted attr. */
1417 /* Merge two pointer arrays */
1418 static __init struct attribute **merge_attr(struct attribute **a, struct attribute **b)
1420 struct attribute **new;
1423 for (j = 0; a[j]; j++)
1425 for (i = 0; b[i]; i++)
1429 new = kmalloc(sizeof(struct attribute *) * j, GFP_KERNEL);
1434 for (i = 0; a[i]; i++)
1436 for (i = 0; b[i]; i++)
1443 ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr,
1446 struct perf_pmu_events_attr *pmu_attr = \
1447 container_of(attr, struct perf_pmu_events_attr, attr);
1448 u64 config = x86_pmu.event_map(pmu_attr->id);
1450 /* string trumps id */
1451 if (pmu_attr->event_str)
1452 return sprintf(page, "%s", pmu_attr->event_str);
1454 return x86_pmu.events_sysfs_show(page, config);
1457 EVENT_ATTR(cpu-cycles, CPU_CYCLES );
1458 EVENT_ATTR(instructions, INSTRUCTIONS );
1459 EVENT_ATTR(cache-references, CACHE_REFERENCES );
1460 EVENT_ATTR(cache-misses, CACHE_MISSES );
1461 EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
1462 EVENT_ATTR(branch-misses, BRANCH_MISSES );
1463 EVENT_ATTR(bus-cycles, BUS_CYCLES );
1464 EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
1465 EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
1466 EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
1468 static struct attribute *empty_attrs;
1470 static struct attribute *events_attr[] = {
1471 EVENT_PTR(CPU_CYCLES),
1472 EVENT_PTR(INSTRUCTIONS),
1473 EVENT_PTR(CACHE_REFERENCES),
1474 EVENT_PTR(CACHE_MISSES),
1475 EVENT_PTR(BRANCH_INSTRUCTIONS),
1476 EVENT_PTR(BRANCH_MISSES),
1477 EVENT_PTR(BUS_CYCLES),
1478 EVENT_PTR(STALLED_CYCLES_FRONTEND),
1479 EVENT_PTR(STALLED_CYCLES_BACKEND),
1480 EVENT_PTR(REF_CPU_CYCLES),
1484 static struct attribute_group x86_pmu_events_group = {
1486 .attrs = events_attr,
1489 ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
1491 u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
1492 u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
1493 bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
1494 bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
1495 bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
1496 bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
1500 * We have whole page size to spend and just little data
1501 * to write, so we can safely use sprintf.
1503 ret = sprintf(page, "event=0x%02llx", event);
1506 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
1509 ret += sprintf(page + ret, ",edge");
1512 ret += sprintf(page + ret, ",pc");
1515 ret += sprintf(page + ret, ",any");
1518 ret += sprintf(page + ret, ",inv");
1521 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
1523 ret += sprintf(page + ret, "\n");
1528 static int __init init_hw_perf_events(void)
1530 struct x86_pmu_quirk *quirk;
1533 pr_info("Performance Events: ");
1535 switch (boot_cpu_data.x86_vendor) {
1536 case X86_VENDOR_INTEL:
1537 err = intel_pmu_init();
1539 case X86_VENDOR_AMD:
1540 err = amd_pmu_init();
1546 pr_cont("no PMU driver, software events only.\n");
1552 /* sanity check that the hardware exists or is emulated */
1553 if (!check_hw_exists())
1556 pr_cont("%s PMU driver.\n", x86_pmu.name);
1558 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1560 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1563 if (!x86_pmu.intel_ctrl)
1564 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
1566 perf_events_lapic_init();
1567 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1569 unconstrained = (struct event_constraint)
1570 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
1571 0, x86_pmu.num_counters, 0, 0);
1573 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
1575 if (x86_pmu.event_attrs)
1576 x86_pmu_events_group.attrs = x86_pmu.event_attrs;
1578 if (!x86_pmu.events_sysfs_show)
1579 x86_pmu_events_group.attrs = &empty_attrs;
1581 filter_events(x86_pmu_events_group.attrs);
1583 if (x86_pmu.cpu_events) {
1584 struct attribute **tmp;
1586 tmp = merge_attr(x86_pmu_events_group.attrs, x86_pmu.cpu_events);
1588 x86_pmu_events_group.attrs = tmp;
1591 pr_info("... version: %d\n", x86_pmu.version);
1592 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1593 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1594 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
1595 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
1596 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
1597 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
1599 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
1600 perf_cpu_notifier(x86_pmu_notifier);
1604 early_initcall(init_hw_perf_events);
1606 static inline void x86_pmu_read(struct perf_event *event)
1608 x86_perf_event_update(event);
1612 * Start group events scheduling transaction
1613 * Set the flag to make pmu::enable() not perform the
1614 * schedulability test, it will be performed at commit time
1616 static void x86_pmu_start_txn(struct pmu *pmu)
1618 perf_pmu_disable(pmu);
1619 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1620 __this_cpu_write(cpu_hw_events.n_txn, 0);
1624 * Stop group events scheduling transaction
1625 * Clear the flag and pmu::enable() will perform the
1626 * schedulability test.
1628 static void x86_pmu_cancel_txn(struct pmu *pmu)
1630 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
1632 * Truncate collected array by the number of events added in this
1633 * transaction. See x86_pmu_add() and x86_pmu_*_txn().
1635 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1636 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
1637 perf_pmu_enable(pmu);
1641 * Commit group events scheduling transaction
1642 * Perform the group schedulability test as a whole
1643 * Return 0 if success
1645 * Does not cancel the transaction on failure; expects the caller to do this.
1647 static int x86_pmu_commit_txn(struct pmu *pmu)
1649 struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
1650 int assign[X86_PMC_IDX_MAX];
1655 if (!x86_pmu_initialized())
1658 ret = x86_pmu.schedule_events(cpuc, n, assign);
1663 * copy new assignment, now we know it is possible
1664 * will be used by hw_perf_enable()
1666 memcpy(cpuc->assign, assign, n*sizeof(int));
1668 cpuc->group_flag &= ~PERF_EVENT_TXN;
1669 perf_pmu_enable(pmu);
1673 * a fake_cpuc is used to validate event groups. Due to
1674 * the extra reg logic, we need to also allocate a fake
1675 * per_core and per_cpu structure. Otherwise, group events
1676 * using extra reg may conflict without the kernel being
1677 * able to catch this when the last event gets added to
1680 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1682 kfree(cpuc->shared_regs);
1686 static struct cpu_hw_events *allocate_fake_cpuc(void)
1688 struct cpu_hw_events *cpuc;
1689 int cpu = raw_smp_processor_id();
1691 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1693 return ERR_PTR(-ENOMEM);
1695 /* only needed, if we have extra_regs */
1696 if (x86_pmu.extra_regs) {
1697 cpuc->shared_regs = allocate_shared_regs(cpu);
1698 if (!cpuc->shared_regs)
1704 free_fake_cpuc(cpuc);
1705 return ERR_PTR(-ENOMEM);
1709 * validate that we can schedule this event
1711 static int validate_event(struct perf_event *event)
1713 struct cpu_hw_events *fake_cpuc;
1714 struct event_constraint *c;
1717 fake_cpuc = allocate_fake_cpuc();
1718 if (IS_ERR(fake_cpuc))
1719 return PTR_ERR(fake_cpuc);
1721 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1723 if (!c || !c->weight)
1726 if (x86_pmu.put_event_constraints)
1727 x86_pmu.put_event_constraints(fake_cpuc, event);
1729 free_fake_cpuc(fake_cpuc);
1735 * validate a single event group
1737 * validation include:
1738 * - check events are compatible which each other
1739 * - events do not compete for the same counter
1740 * - number of events <= number of counters
1742 * validation ensures the group can be loaded onto the
1743 * PMU if it was the only group available.
1745 static int validate_group(struct perf_event *event)
1747 struct perf_event *leader = event->group_leader;
1748 struct cpu_hw_events *fake_cpuc;
1749 int ret = -EINVAL, n;
1751 fake_cpuc = allocate_fake_cpuc();
1752 if (IS_ERR(fake_cpuc))
1753 return PTR_ERR(fake_cpuc);
1755 * the event is not yet connected with its
1756 * siblings therefore we must first collect
1757 * existing siblings, then add the new event
1758 * before we can simulate the scheduling
1760 n = collect_events(fake_cpuc, leader, true);
1764 fake_cpuc->n_events = n;
1765 n = collect_events(fake_cpuc, event, false);
1769 fake_cpuc->n_events = n;
1771 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
1774 free_fake_cpuc(fake_cpuc);
1778 static int x86_pmu_event_init(struct perf_event *event)
1783 switch (event->attr.type) {
1785 case PERF_TYPE_HARDWARE:
1786 case PERF_TYPE_HW_CACHE:
1793 err = __x86_pmu_event_init(event);
1796 * we temporarily connect event to its pmu
1797 * such that validate_group() can classify
1798 * it as an x86 event using is_x86_event()
1803 if (event->group_leader != event)
1804 err = validate_group(event);
1806 err = validate_event(event);
1812 event->destroy(event);
1818 static int x86_pmu_event_idx(struct perf_event *event)
1820 int idx = event->hw.idx;
1822 if (!x86_pmu.attr_rdpmc)
1825 if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
1826 idx -= INTEL_PMC_IDX_FIXED;
1833 static ssize_t get_attr_rdpmc(struct device *cdev,
1834 struct device_attribute *attr,
1837 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1840 static void change_rdpmc(void *info)
1842 bool enable = !!(unsigned long)info;
1845 set_in_cr4(X86_CR4_PCE);
1847 clear_in_cr4(X86_CR4_PCE);
1850 static ssize_t set_attr_rdpmc(struct device *cdev,
1851 struct device_attribute *attr,
1852 const char *buf, size_t count)
1857 ret = kstrtoul(buf, 0, &val);
1861 if (x86_pmu.attr_rdpmc_broken)
1864 if (!!val != !!x86_pmu.attr_rdpmc) {
1865 x86_pmu.attr_rdpmc = !!val;
1866 on_each_cpu(change_rdpmc, (void *)val, 1);
1872 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
1874 static struct attribute *x86_pmu_attrs[] = {
1875 &dev_attr_rdpmc.attr,
1879 static struct attribute_group x86_pmu_attr_group = {
1880 .attrs = x86_pmu_attrs,
1883 static const struct attribute_group *x86_pmu_attr_groups[] = {
1884 &x86_pmu_attr_group,
1885 &x86_pmu_format_group,
1886 &x86_pmu_events_group,
1890 static void x86_pmu_flush_branch_stack(void)
1892 if (x86_pmu.flush_branch_stack)
1893 x86_pmu.flush_branch_stack();
1896 void perf_check_microcode(void)
1898 if (x86_pmu.check_microcode)
1899 x86_pmu.check_microcode();
1901 EXPORT_SYMBOL_GPL(perf_check_microcode);
1903 static struct pmu pmu = {
1904 .pmu_enable = x86_pmu_enable,
1905 .pmu_disable = x86_pmu_disable,
1907 .attr_groups = x86_pmu_attr_groups,
1909 .event_init = x86_pmu_event_init,
1913 .start = x86_pmu_start,
1914 .stop = x86_pmu_stop,
1915 .read = x86_pmu_read,
1917 .start_txn = x86_pmu_start_txn,
1918 .cancel_txn = x86_pmu_cancel_txn,
1919 .commit_txn = x86_pmu_commit_txn,
1921 .event_idx = x86_pmu_event_idx,
1922 .flush_branch_stack = x86_pmu_flush_branch_stack,
1925 void arch_perf_update_userpage(struct perf_event_mmap_page *userpg, u64 now)
1927 struct cyc2ns_data *data;
1929 userpg->cap_user_time = 0;
1930 userpg->cap_user_time_zero = 0;
1931 userpg->cap_user_rdpmc = x86_pmu.attr_rdpmc;
1932 userpg->pmc_width = x86_pmu.cntval_bits;
1934 if (!sched_clock_stable())
1937 data = cyc2ns_read_begin();
1939 userpg->cap_user_time = 1;
1940 userpg->time_mult = data->cyc2ns_mul;
1941 userpg->time_shift = data->cyc2ns_shift;
1942 userpg->time_offset = data->cyc2ns_offset - now;
1944 userpg->cap_user_time_zero = 1;
1945 userpg->time_zero = data->cyc2ns_offset;
1947 cyc2ns_read_end(data);
1954 static int backtrace_stack(void *data, char *name)
1959 static void backtrace_address(void *data, unsigned long addr, int reliable)
1961 struct perf_callchain_entry *entry = data;
1963 perf_callchain_store(entry, addr);
1966 static const struct stacktrace_ops backtrace_ops = {
1967 .stack = backtrace_stack,
1968 .address = backtrace_address,
1969 .walk_stack = print_context_stack_bp,
1973 perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
1975 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
1976 /* TODO: We don't support guest os callchain now */
1980 perf_callchain_store(entry, regs->ip);
1982 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
1986 valid_user_frame(const void __user *fp, unsigned long size)
1988 return (__range_not_ok(fp, size, TASK_SIZE) == 0);
1991 static unsigned long get_segment_base(unsigned int segment)
1993 struct desc_struct *desc;
1994 int idx = segment >> 3;
1996 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
1997 if (idx > LDT_ENTRIES)
2000 if (idx > current->active_mm->context.size)
2003 desc = current->active_mm->context.ldt;
2005 if (idx > GDT_ENTRIES)
2008 desc = __this_cpu_ptr(&gdt_page.gdt[0]);
2011 return get_desc_base(desc + idx);
2014 #ifdef CONFIG_COMPAT
2016 #include <asm/compat.h>
2019 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2021 /* 32-bit process in 64-bit kernel. */
2022 unsigned long ss_base, cs_base;
2023 struct stack_frame_ia32 frame;
2024 const void __user *fp;
2026 if (!test_thread_flag(TIF_IA32))
2029 cs_base = get_segment_base(regs->cs);
2030 ss_base = get_segment_base(regs->ss);
2032 fp = compat_ptr(ss_base + regs->bp);
2033 while (entry->nr < PERF_MAX_STACK_DEPTH) {
2034 unsigned long bytes;
2035 frame.next_frame = 0;
2036 frame.return_address = 0;
2038 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2042 if (!valid_user_frame(fp, sizeof(frame)))
2045 perf_callchain_store(entry, cs_base + frame.return_address);
2046 fp = compat_ptr(ss_base + frame.next_frame);
2052 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2059 perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
2061 struct stack_frame frame;
2062 const void __user *fp;
2064 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2065 /* TODO: We don't support guest os callchain now */
2070 * We don't know what to do with VM86 stacks.. ignore them for now.
2072 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2075 fp = (void __user *)regs->bp;
2077 perf_callchain_store(entry, regs->ip);
2082 if (perf_callchain_user32(regs, entry))
2085 while (entry->nr < PERF_MAX_STACK_DEPTH) {
2086 unsigned long bytes;
2087 frame.next_frame = NULL;
2088 frame.return_address = 0;
2090 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
2094 if (!valid_user_frame(fp, sizeof(frame)))
2097 perf_callchain_store(entry, frame.return_address);
2098 fp = frame.next_frame;
2103 * Deal with code segment offsets for the various execution modes:
2105 * VM86 - the good olde 16 bit days, where the linear address is
2106 * 20 bits and we use regs->ip + 0x10 * regs->cs.
2108 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
2109 * to figure out what the 32bit base address is.
2111 * X32 - has TIF_X32 set, but is running in x86_64
2113 * X86_64 - CS,DS,SS,ES are all zero based.
2115 static unsigned long code_segment_base(struct pt_regs *regs)
2118 * If we are in VM86 mode, add the segment offset to convert to a
2121 if (regs->flags & X86_VM_MASK)
2122 return 0x10 * regs->cs;
2125 * For IA32 we look at the GDT/LDT segment base to convert the
2126 * effective IP to a linear address.
2128 #ifdef CONFIG_X86_32
2129 if (user_mode(regs) && regs->cs != __USER_CS)
2130 return get_segment_base(regs->cs);
2132 if (test_thread_flag(TIF_IA32)) {
2133 if (user_mode(regs) && regs->cs != __USER32_CS)
2134 return get_segment_base(regs->cs);
2140 unsigned long perf_instruction_pointer(struct pt_regs *regs)
2142 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
2143 return perf_guest_cbs->get_guest_ip();
2145 return regs->ip + code_segment_base(regs);
2148 unsigned long perf_misc_flags(struct pt_regs *regs)
2152 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2153 if (perf_guest_cbs->is_user_mode())
2154 misc |= PERF_RECORD_MISC_GUEST_USER;
2156 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
2158 if (user_mode(regs))
2159 misc |= PERF_RECORD_MISC_USER;
2161 misc |= PERF_RECORD_MISC_KERNEL;
2164 if (regs->flags & PERF_EFLAGS_EXACT)
2165 misc |= PERF_RECORD_MISC_EXACT_IP;
2170 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
2172 cap->version = x86_pmu.version;
2173 cap->num_counters_gp = x86_pmu.num_counters;
2174 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
2175 cap->bit_width_gp = x86_pmu.cntval_bits;
2176 cap->bit_width_fixed = x86_pmu.cntval_bits;
2177 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
2178 cap->events_mask_len = x86_pmu.events_mask_len;
2180 EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);