]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - arch/x86/kernel/cpu/perf_event.c
Merge branch 'perf/core' into perf/timer, before applying new changes
[mirror_ubuntu-bionic-kernel.git] / arch / x86 / kernel / cpu / perf_event.c
CommitLineData
241771ef 1/*
cdd6c482 2 * Performance events x86 architecture code
241771ef 3 *
98144511
IM
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>
30dd568c 9 * Copyright (C) 2009 Intel Corporation, <markus.t.metzger@intel.com>
1da53e02 10 * Copyright (C) 2009 Google, Inc., Stephane Eranian
241771ef
IM
11 *
12 * For licencing details see kernel-base/COPYING
13 */
14
cdd6c482 15#include <linux/perf_event.h>
241771ef
IM
16#include <linux/capability.h>
17#include <linux/notifier.h>
18#include <linux/hardirq.h>
19#include <linux/kprobes.h>
4ac13294 20#include <linux/module.h>
241771ef
IM
21#include <linux/kdebug.h>
22#include <linux/sched.h>
d7d59fb3 23#include <linux/uaccess.h>
5a0e3ad6 24#include <linux/slab.h>
30dd568c 25#include <linux/cpu.h>
272d30be 26#include <linux/bitops.h>
0c9d42ed 27#include <linux/device.h>
241771ef 28
241771ef 29#include <asm/apic.h>
d7d59fb3 30#include <asm/stacktrace.h>
4e935e47 31#include <asm/nmi.h>
69092624 32#include <asm/smp.h>
c8e5910e 33#include <asm/alternative.h>
7911d3f7 34#include <asm/mmu_context.h>
375074cc 35#include <asm/tlbflush.h>
e3f3541c 36#include <asm/timer.h>
d07bdfd3
PZ
37#include <asm/desc.h>
38#include <asm/ldt.h>
241771ef 39
de0428a7
KW
40#include "perf_event.h"
41
de0428a7 42struct x86_pmu x86_pmu __read_mostly;
efc9f05d 43
de0428a7 44DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
b0f3f28e
PZ
45 .enabled = 1,
46};
241771ef 47
a6673429
AL
48struct static_key rdpmc_always_available = STATIC_KEY_INIT_FALSE;
49
de0428a7 50u64 __read_mostly hw_cache_event_ids
8326f44d
IM
51 [PERF_COUNT_HW_CACHE_MAX]
52 [PERF_COUNT_HW_CACHE_OP_MAX]
53 [PERF_COUNT_HW_CACHE_RESULT_MAX];
de0428a7 54u64 __read_mostly hw_cache_extra_regs
e994d7d2
AK
55 [PERF_COUNT_HW_CACHE_MAX]
56 [PERF_COUNT_HW_CACHE_OP_MAX]
57 [PERF_COUNT_HW_CACHE_RESULT_MAX];
8326f44d 58
ee06094f 59/*
cdd6c482
IM
60 * Propagate event elapsed time into the generic event.
61 * Can only be executed on the CPU where the event is active.
ee06094f
IM
62 * Returns the delta events processed.
63 */
de0428a7 64u64 x86_perf_event_update(struct perf_event *event)
ee06094f 65{
cc2ad4ba 66 struct hw_perf_event *hwc = &event->hw;
948b1bb8 67 int shift = 64 - x86_pmu.cntval_bits;
ec3232bd 68 u64 prev_raw_count, new_raw_count;
cc2ad4ba 69 int idx = hwc->idx;
ec3232bd 70 s64 delta;
ee06094f 71
15c7ad51 72 if (idx == INTEL_PMC_IDX_FIXED_BTS)
30dd568c
MM
73 return 0;
74
ee06094f 75 /*
cdd6c482 76 * Careful: an NMI might modify the previous event value.
ee06094f
IM
77 *
78 * Our tactic to handle this is to first atomically read and
79 * exchange a new raw count - then add that new-prev delta
cdd6c482 80 * count to the generic event atomically:
ee06094f
IM
81 */
82again:
e7850595 83 prev_raw_count = local64_read(&hwc->prev_count);
c48b6053 84 rdpmcl(hwc->event_base_rdpmc, new_raw_count);
ee06094f 85
e7850595 86 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
ee06094f
IM
87 new_raw_count) != prev_raw_count)
88 goto again;
89
90 /*
91 * Now we have the new raw value and have updated the prev
92 * timestamp already. We can now calculate the elapsed delta
cdd6c482 93 * (event-)time and add that to the generic event.
ee06094f
IM
94 *
95 * Careful, not all hw sign-extends above the physical width
ec3232bd 96 * of the count.
ee06094f 97 */
ec3232bd
PZ
98 delta = (new_raw_count << shift) - (prev_raw_count << shift);
99 delta >>= shift;
ee06094f 100
e7850595
PZ
101 local64_add(delta, &event->count);
102 local64_sub(delta, &hwc->period_left);
4b7bfd0d
RR
103
104 return new_raw_count;
ee06094f
IM
105}
106
a7e3ed1e
AK
107/*
108 * Find and validate any extra registers to set up.
109 */
110static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
111{
efc9f05d 112 struct hw_perf_event_extra *reg;
a7e3ed1e
AK
113 struct extra_reg *er;
114
efc9f05d 115 reg = &event->hw.extra_reg;
a7e3ed1e
AK
116
117 if (!x86_pmu.extra_regs)
118 return 0;
119
120 for (er = x86_pmu.extra_regs; er->msr; er++) {
121 if (er->event != (config & er->config_mask))
122 continue;
123 if (event->attr.config1 & ~er->valid_mask)
124 return -EINVAL;
338b522c
KL
125 /* Check if the extra msrs can be safely accessed*/
126 if (!er->extra_msr_access)
127 return -ENXIO;
efc9f05d
SE
128
129 reg->idx = er->idx;
130 reg->config = event->attr.config1;
131 reg->reg = er->msr;
a7e3ed1e
AK
132 break;
133 }
134 return 0;
135}
136
cdd6c482 137static atomic_t active_events;
4e935e47
PZ
138static DEFINE_MUTEX(pmc_reserve_mutex);
139
b27ea29c
RR
140#ifdef CONFIG_X86_LOCAL_APIC
141
4e935e47
PZ
142static bool reserve_pmc_hardware(void)
143{
144 int i;
145
948b1bb8 146 for (i = 0; i < x86_pmu.num_counters; i++) {
41bf4989 147 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
4e935e47
PZ
148 goto perfctr_fail;
149 }
150
948b1bb8 151 for (i = 0; i < x86_pmu.num_counters; i++) {
41bf4989 152 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
4e935e47
PZ
153 goto eventsel_fail;
154 }
155
156 return true;
157
158eventsel_fail:
159 for (i--; i >= 0; i--)
41bf4989 160 release_evntsel_nmi(x86_pmu_config_addr(i));
4e935e47 161
948b1bb8 162 i = x86_pmu.num_counters;
4e935e47
PZ
163
164perfctr_fail:
165 for (i--; i >= 0; i--)
41bf4989 166 release_perfctr_nmi(x86_pmu_event_addr(i));
4e935e47 167
4e935e47
PZ
168 return false;
169}
170
171static void release_pmc_hardware(void)
172{
173 int i;
174
948b1bb8 175 for (i = 0; i < x86_pmu.num_counters; i++) {
41bf4989
RR
176 release_perfctr_nmi(x86_pmu_event_addr(i));
177 release_evntsel_nmi(x86_pmu_config_addr(i));
4e935e47 178 }
4e935e47
PZ
179}
180
b27ea29c
RR
181#else
182
183static bool reserve_pmc_hardware(void) { return true; }
184static void release_pmc_hardware(void) {}
185
186#endif
187
33c6d6a7
DZ
188static bool check_hw_exists(void)
189{
a5ebe0ba
GD
190 u64 val, val_fail, val_new= ~0;
191 int i, reg, reg_fail, ret = 0;
192 int bios_fail = 0;
33c6d6a7 193
4407204c
PZ
194 /*
195 * Check to see if the BIOS enabled any of the counters, if so
196 * complain and bail.
197 */
198 for (i = 0; i < x86_pmu.num_counters; i++) {
41bf4989 199 reg = x86_pmu_config_addr(i);
4407204c
PZ
200 ret = rdmsrl_safe(reg, &val);
201 if (ret)
202 goto msr_fail;
a5ebe0ba
GD
203 if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
204 bios_fail = 1;
205 val_fail = val;
206 reg_fail = reg;
207 }
4407204c
PZ
208 }
209
210 if (x86_pmu.num_counters_fixed) {
211 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
212 ret = rdmsrl_safe(reg, &val);
213 if (ret)
214 goto msr_fail;
215 for (i = 0; i < x86_pmu.num_counters_fixed; i++) {
a5ebe0ba
GD
216 if (val & (0x03 << i*4)) {
217 bios_fail = 1;
218 val_fail = val;
219 reg_fail = reg;
220 }
4407204c
PZ
221 }
222 }
223
224 /*
bffd5fc2
AP
225 * Read the current value, change it and read it back to see if it
226 * matches, this is needed to detect certain hardware emulators
227 * (qemu/kvm) that don't trap on the MSR access and always return 0s.
4407204c 228 */
f285f92f 229 reg = x86_pmu_event_addr(0);
bffd5fc2
AP
230 if (rdmsrl_safe(reg, &val))
231 goto msr_fail;
232 val ^= 0xffffUL;
f285f92f
RR
233 ret = wrmsrl_safe(reg, val);
234 ret |= rdmsrl_safe(reg, &val_new);
33c6d6a7 235 if (ret || val != val_new)
4407204c 236 goto msr_fail;
33c6d6a7 237
45daae57
IM
238 /*
239 * We still allow the PMU driver to operate:
240 */
a5ebe0ba
GD
241 if (bios_fail) {
242 printk(KERN_CONT "Broken BIOS detected, complain to your hardware vendor.\n");
243 printk(KERN_ERR FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n", reg_fail, val_fail);
244 }
45daae57
IM
245
246 return true;
4407204c
PZ
247
248msr_fail:
249 printk(KERN_CONT "Broken PMU hardware detected, using software events only.\n");
65d71fe1
PZI
250 printk("%sFailed to access perfctr msr (MSR %x is %Lx)\n",
251 boot_cpu_has(X86_FEATURE_HYPERVISOR) ? KERN_INFO : KERN_ERR,
252 reg, val_new);
45daae57 253
4407204c 254 return false;
33c6d6a7
DZ
255}
256
cdd6c482 257static void hw_perf_event_destroy(struct perf_event *event)
4e935e47 258{
cdd6c482 259 if (atomic_dec_and_mutex_lock(&active_events, &pmc_reserve_mutex)) {
4e935e47 260 release_pmc_hardware();
ca037701 261 release_ds_buffers();
4e935e47
PZ
262 mutex_unlock(&pmc_reserve_mutex);
263 }
264}
265
85cf9dba
RR
266static inline int x86_pmu_initialized(void)
267{
268 return x86_pmu.handle_irq != NULL;
269}
270
8326f44d 271static inline int
e994d7d2 272set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
8326f44d 273{
e994d7d2 274 struct perf_event_attr *attr = &event->attr;
8326f44d
IM
275 unsigned int cache_type, cache_op, cache_result;
276 u64 config, val;
277
278 config = attr->config;
279
280 cache_type = (config >> 0) & 0xff;
281 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
282 return -EINVAL;
283
284 cache_op = (config >> 8) & 0xff;
285 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
286 return -EINVAL;
287
288 cache_result = (config >> 16) & 0xff;
289 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
290 return -EINVAL;
291
292 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
293
294 if (val == 0)
295 return -ENOENT;
296
297 if (val == -1)
298 return -EINVAL;
299
300 hwc->config |= val;
e994d7d2
AK
301 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
302 return x86_pmu_extra_regs(val, event);
8326f44d
IM
303}
304
de0428a7 305int x86_setup_perfctr(struct perf_event *event)
c1726f34
RR
306{
307 struct perf_event_attr *attr = &event->attr;
308 struct hw_perf_event *hwc = &event->hw;
309 u64 config;
310
6c7e550f 311 if (!is_sampling_event(event)) {
c1726f34
RR
312 hwc->sample_period = x86_pmu.max_period;
313 hwc->last_period = hwc->sample_period;
e7850595 314 local64_set(&hwc->period_left, hwc->sample_period);
c1726f34
RR
315 }
316
317 if (attr->type == PERF_TYPE_RAW)
ed13ec58 318 return x86_pmu_extra_regs(event->attr.config, event);
c1726f34
RR
319
320 if (attr->type == PERF_TYPE_HW_CACHE)
e994d7d2 321 return set_ext_hw_attr(hwc, event);
c1726f34
RR
322
323 if (attr->config >= x86_pmu.max_events)
324 return -EINVAL;
325
326 /*
327 * The generic map:
328 */
329 config = x86_pmu.event_map(attr->config);
330
331 if (config == 0)
332 return -ENOENT;
333
334 if (config == -1LL)
335 return -EINVAL;
336
337 /*
338 * Branch tracing:
339 */
18a073a3
PZ
340 if (attr->config == PERF_COUNT_HW_BRANCH_INSTRUCTIONS &&
341 !attr->freq && hwc->sample_period == 1) {
c1726f34 342 /* BTS is not supported by this architecture. */
6809b6ea 343 if (!x86_pmu.bts_active)
c1726f34
RR
344 return -EOPNOTSUPP;
345
346 /* BTS is currently only allowed for user-mode. */
347 if (!attr->exclude_kernel)
348 return -EOPNOTSUPP;
349 }
350
351 hwc->config |= config;
352
353 return 0;
354}
4261e0e0 355
ff3fb511
SE
356/*
357 * check that branch_sample_type is compatible with
358 * settings needed for precise_ip > 1 which implies
359 * using the LBR to capture ALL taken branches at the
360 * priv levels of the measurement
361 */
362static inline int precise_br_compat(struct perf_event *event)
363{
364 u64 m = event->attr.branch_sample_type;
365 u64 b = 0;
366
367 /* must capture all branches */
368 if (!(m & PERF_SAMPLE_BRANCH_ANY))
369 return 0;
370
371 m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
372
373 if (!event->attr.exclude_user)
374 b |= PERF_SAMPLE_BRANCH_USER;
375
376 if (!event->attr.exclude_kernel)
377 b |= PERF_SAMPLE_BRANCH_KERNEL;
378
379 /*
380 * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
381 */
382
383 return m == b;
384}
385
de0428a7 386int x86_pmu_hw_config(struct perf_event *event)
a072738e 387{
ab608344
PZ
388 if (event->attr.precise_ip) {
389 int precise = 0;
390
391 /* Support for constant skid */
c93dc84c 392 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
ab608344
PZ
393 precise++;
394
5553be26 395 /* Support for IP fixup */
03de874a 396 if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
5553be26
PZ
397 precise++;
398 }
ab608344
PZ
399
400 if (event->attr.precise_ip > precise)
401 return -EOPNOTSUPP;
4b854900
YZ
402 }
403 /*
404 * check that PEBS LBR correction does not conflict with
405 * whatever the user is asking with attr->branch_sample_type
406 */
407 if (event->attr.precise_ip > 1 && x86_pmu.intel_cap.pebs_format < 2) {
408 u64 *br_type = &event->attr.branch_sample_type;
409
410 if (has_branch_stack(event)) {
411 if (!precise_br_compat(event))
412 return -EOPNOTSUPP;
413
414 /* branch_sample_type is compatible */
415
416 } else {
417 /*
418 * user did not specify branch_sample_type
419 *
420 * For PEBS fixups, we capture all
421 * the branches at the priv level of the
422 * event.
423 */
424 *br_type = PERF_SAMPLE_BRANCH_ANY;
425
426 if (!event->attr.exclude_user)
427 *br_type |= PERF_SAMPLE_BRANCH_USER;
428
429 if (!event->attr.exclude_kernel)
430 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
ff3fb511 431 }
ab608344
PZ
432 }
433
e18bf526
YZ
434 if (event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_CALL_STACK)
435 event->attach_state |= PERF_ATTACH_TASK_DATA;
436
a072738e
CG
437 /*
438 * Generate PMC IRQs:
439 * (keep 'enabled' bit clear for now)
440 */
b4cdc5c2 441 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
a072738e
CG
442
443 /*
444 * Count user and OS events unless requested not to
445 */
b4cdc5c2
PZ
446 if (!event->attr.exclude_user)
447 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
448 if (!event->attr.exclude_kernel)
449 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
a072738e 450
b4cdc5c2
PZ
451 if (event->attr.type == PERF_TYPE_RAW)
452 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
a072738e 453
294fe0f5
AK
454 if (event->attr.sample_period && x86_pmu.limit_period) {
455 if (x86_pmu.limit_period(event, event->attr.sample_period) >
456 event->attr.sample_period)
457 return -EINVAL;
458 }
459
9d0fcba6 460 return x86_setup_perfctr(event);
a098f448
RR
461}
462
241771ef 463/*
0d48696f 464 * Setup the hardware configuration for a given attr_type
241771ef 465 */
b0a873eb 466static int __x86_pmu_event_init(struct perf_event *event)
241771ef 467{
4e935e47 468 int err;
241771ef 469
85cf9dba
RR
470 if (!x86_pmu_initialized())
471 return -ENODEV;
241771ef 472
4e935e47 473 err = 0;
cdd6c482 474 if (!atomic_inc_not_zero(&active_events)) {
4e935e47 475 mutex_lock(&pmc_reserve_mutex);
cdd6c482 476 if (atomic_read(&active_events) == 0) {
30dd568c
MM
477 if (!reserve_pmc_hardware())
478 err = -EBUSY;
f80c9e30
PZ
479 else
480 reserve_ds_buffers();
30dd568c
MM
481 }
482 if (!err)
cdd6c482 483 atomic_inc(&active_events);
4e935e47
PZ
484 mutex_unlock(&pmc_reserve_mutex);
485 }
486 if (err)
487 return err;
488
cdd6c482 489 event->destroy = hw_perf_event_destroy;
a1792cda 490
4261e0e0
RR
491 event->hw.idx = -1;
492 event->hw.last_cpu = -1;
493 event->hw.last_tag = ~0ULL;
b690081d 494
efc9f05d
SE
495 /* mark unused */
496 event->hw.extra_reg.idx = EXTRA_REG_NONE;
b36817e8
SE
497 event->hw.branch_reg.idx = EXTRA_REG_NONE;
498
9d0fcba6 499 return x86_pmu.hw_config(event);
4261e0e0
RR
500}
501
de0428a7 502void x86_pmu_disable_all(void)
f87ad35d 503{
89cbc767 504 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
9e35ad38
PZ
505 int idx;
506
948b1bb8 507 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
b0f3f28e
PZ
508 u64 val;
509
43f6201a 510 if (!test_bit(idx, cpuc->active_mask))
4295ee62 511 continue;
41bf4989 512 rdmsrl(x86_pmu_config_addr(idx), val);
bb1165d6 513 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
4295ee62 514 continue;
bb1165d6 515 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
41bf4989 516 wrmsrl(x86_pmu_config_addr(idx), val);
f87ad35d 517 }
f87ad35d
JSR
518}
519
a4eaf7f1 520static void x86_pmu_disable(struct pmu *pmu)
b56a3802 521{
89cbc767 522 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02 523
85cf9dba 524 if (!x86_pmu_initialized())
9e35ad38 525 return;
1da53e02 526
1a6e21f7
PZ
527 if (!cpuc->enabled)
528 return;
529
530 cpuc->n_added = 0;
531 cpuc->enabled = 0;
532 barrier();
1da53e02
SE
533
534 x86_pmu.disable_all();
b56a3802 535}
241771ef 536
de0428a7 537void x86_pmu_enable_all(int added)
f87ad35d 538{
89cbc767 539 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
f87ad35d
JSR
540 int idx;
541
948b1bb8 542 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
d45dd923 543 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
b0f3f28e 544
43f6201a 545 if (!test_bit(idx, cpuc->active_mask))
4295ee62 546 continue;
984b838c 547
d45dd923 548 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
f87ad35d
JSR
549 }
550}
551
51b0fe39 552static struct pmu pmu;
1da53e02
SE
553
554static inline int is_x86_event(struct perf_event *event)
555{
556 return event->pmu == &pmu;
557}
558
1e2ad28f
RR
559/*
560 * Event scheduler state:
561 *
562 * Assign events iterating over all events and counters, beginning
563 * with events with least weights first. Keep the current iterator
564 * state in struct sched_state.
565 */
566struct sched_state {
567 int weight;
568 int event; /* event index */
569 int counter; /* counter index */
570 int unassigned; /* number of events to be assigned left */
571 unsigned long used[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
572};
573
bc1738f6
RR
574/* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
575#define SCHED_STATES_MAX 2
576
1e2ad28f
RR
577struct perf_sched {
578 int max_weight;
579 int max_events;
43b45780 580 struct perf_event **events;
1e2ad28f 581 struct sched_state state;
bc1738f6
RR
582 int saved_states;
583 struct sched_state saved[SCHED_STATES_MAX];
1e2ad28f
RR
584};
585
586/*
587 * Initialize interator that runs through all events and counters.
588 */
43b45780 589static void perf_sched_init(struct perf_sched *sched, struct perf_event **events,
1e2ad28f
RR
590 int num, int wmin, int wmax)
591{
592 int idx;
593
594 memset(sched, 0, sizeof(*sched));
595 sched->max_events = num;
596 sched->max_weight = wmax;
43b45780 597 sched->events = events;
1e2ad28f
RR
598
599 for (idx = 0; idx < num; idx++) {
43b45780 600 if (events[idx]->hw.constraint->weight == wmin)
1e2ad28f
RR
601 break;
602 }
603
604 sched->state.event = idx; /* start with min weight */
605 sched->state.weight = wmin;
606 sched->state.unassigned = num;
607}
608
bc1738f6
RR
609static void perf_sched_save_state(struct perf_sched *sched)
610{
611 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
612 return;
613
614 sched->saved[sched->saved_states] = sched->state;
615 sched->saved_states++;
616}
617
618static bool perf_sched_restore_state(struct perf_sched *sched)
619{
620 if (!sched->saved_states)
621 return false;
622
623 sched->saved_states--;
624 sched->state = sched->saved[sched->saved_states];
625
626 /* continue with next counter: */
627 clear_bit(sched->state.counter++, sched->state.used);
628
629 return true;
630}
631
1e2ad28f
RR
632/*
633 * Select a counter for the current event to schedule. Return true on
634 * success.
635 */
bc1738f6 636static bool __perf_sched_find_counter(struct perf_sched *sched)
1e2ad28f
RR
637{
638 struct event_constraint *c;
639 int idx;
640
641 if (!sched->state.unassigned)
642 return false;
643
644 if (sched->state.event >= sched->max_events)
645 return false;
646
43b45780 647 c = sched->events[sched->state.event]->hw.constraint;
4defea85 648 /* Prefer fixed purpose counters */
15c7ad51
RR
649 if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
650 idx = INTEL_PMC_IDX_FIXED;
307b1cd7 651 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
4defea85
PZ
652 if (!__test_and_set_bit(idx, sched->state.used))
653 goto done;
654 }
655 }
1e2ad28f
RR
656 /* Grab the first unused counter starting with idx */
657 idx = sched->state.counter;
15c7ad51 658 for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
1e2ad28f 659 if (!__test_and_set_bit(idx, sched->state.used))
4defea85 660 goto done;
1e2ad28f 661 }
1e2ad28f 662
4defea85
PZ
663 return false;
664
665done:
666 sched->state.counter = idx;
1e2ad28f 667
bc1738f6
RR
668 if (c->overlap)
669 perf_sched_save_state(sched);
670
671 return true;
672}
673
674static bool perf_sched_find_counter(struct perf_sched *sched)
675{
676 while (!__perf_sched_find_counter(sched)) {
677 if (!perf_sched_restore_state(sched))
678 return false;
679 }
680
1e2ad28f
RR
681 return true;
682}
683
684/*
685 * Go through all unassigned events and find the next one to schedule.
686 * Take events with the least weight first. Return true on success.
687 */
688static bool perf_sched_next_event(struct perf_sched *sched)
689{
690 struct event_constraint *c;
691
692 if (!sched->state.unassigned || !--sched->state.unassigned)
693 return false;
694
695 do {
696 /* next event */
697 sched->state.event++;
698 if (sched->state.event >= sched->max_events) {
699 /* next weight */
700 sched->state.event = 0;
701 sched->state.weight++;
702 if (sched->state.weight > sched->max_weight)
703 return false;
704 }
43b45780 705 c = sched->events[sched->state.event]->hw.constraint;
1e2ad28f
RR
706 } while (c->weight != sched->state.weight);
707
708 sched->state.counter = 0; /* start with first counter */
709
710 return true;
711}
712
713/*
714 * Assign a counter for each event.
715 */
43b45780 716int perf_assign_events(struct perf_event **events, int n,
4b4969b1 717 int wmin, int wmax, int *assign)
1e2ad28f
RR
718{
719 struct perf_sched sched;
720
43b45780 721 perf_sched_init(&sched, events, n, wmin, wmax);
1e2ad28f
RR
722
723 do {
724 if (!perf_sched_find_counter(&sched))
725 break; /* failed */
726 if (assign)
727 assign[sched.state.event] = sched.state.counter;
728 } while (perf_sched_next_event(&sched));
729
730 return sched.state.unassigned;
731}
4a3dc121 732EXPORT_SYMBOL_GPL(perf_assign_events);
1e2ad28f 733
de0428a7 734int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
1da53e02 735{
43b45780 736 struct event_constraint *c;
1da53e02 737 unsigned long used_mask[BITS_TO_LONGS(X86_PMC_IDX_MAX)];
2f7f73a5 738 struct perf_event *e;
1e2ad28f 739 int i, wmin, wmax, num = 0;
1da53e02
SE
740 struct hw_perf_event *hwc;
741
742 bitmap_zero(used_mask, X86_PMC_IDX_MAX);
743
1e2ad28f 744 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
43b45780 745 hwc = &cpuc->event_list[i]->hw;
b622d644 746 c = x86_pmu.get_event_constraints(cpuc, cpuc->event_list[i]);
43b45780
AH
747 hwc->constraint = c;
748
1e2ad28f
RR
749 wmin = min(wmin, c->weight);
750 wmax = max(wmax, c->weight);
1da53e02
SE
751 }
752
8113070d
SE
753 /*
754 * fastpath, try to reuse previous register
755 */
c933c1a6 756 for (i = 0; i < n; i++) {
8113070d 757 hwc = &cpuc->event_list[i]->hw;
43b45780 758 c = hwc->constraint;
8113070d
SE
759
760 /* never assigned */
761 if (hwc->idx == -1)
762 break;
763
764 /* constraint still honored */
63b14649 765 if (!test_bit(hwc->idx, c->idxmsk))
8113070d
SE
766 break;
767
768 /* not already used */
769 if (test_bit(hwc->idx, used_mask))
770 break;
771
34538ee7 772 __set_bit(hwc->idx, used_mask);
8113070d
SE
773 if (assign)
774 assign[i] = hwc->idx;
775 }
8113070d 776
1e2ad28f
RR
777 /* slow path */
778 if (i != n)
43b45780
AH
779 num = perf_assign_events(cpuc->event_list, n, wmin,
780 wmax, assign);
8113070d 781
2f7f73a5
SE
782 /*
783 * Mark the event as committed, so we do not put_constraint()
784 * in case new events are added and fail scheduling.
785 */
786 if (!num && assign) {
787 for (i = 0; i < n; i++) {
788 e = cpuc->event_list[i];
789 e->hw.flags |= PERF_X86_EVENT_COMMITTED;
790 }
791 }
1da53e02
SE
792 /*
793 * scheduling failed or is just a simulation,
794 * free resources if necessary
795 */
796 if (!assign || num) {
797 for (i = 0; i < n; i++) {
2f7f73a5
SE
798 e = cpuc->event_list[i];
799 /*
800 * do not put_constraint() on comitted events,
801 * because they are good to go
802 */
803 if ((e->hw.flags & PERF_X86_EVENT_COMMITTED))
804 continue;
805
1da53e02 806 if (x86_pmu.put_event_constraints)
2f7f73a5 807 x86_pmu.put_event_constraints(cpuc, e);
1da53e02
SE
808 }
809 }
aa2bc1ad 810 return num ? -EINVAL : 0;
1da53e02
SE
811}
812
813/*
814 * dogrp: true if must collect siblings events (group)
815 * returns total number of events and error code
816 */
817static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
818{
819 struct perf_event *event;
820 int n, max_count;
821
948b1bb8 822 max_count = x86_pmu.num_counters + x86_pmu.num_counters_fixed;
1da53e02
SE
823
824 /* current number of events already accepted */
825 n = cpuc->n_events;
826
827 if (is_x86_event(leader)) {
828 if (n >= max_count)
aa2bc1ad 829 return -EINVAL;
1da53e02
SE
830 cpuc->event_list[n] = leader;
831 n++;
832 }
833 if (!dogrp)
834 return n;
835
836 list_for_each_entry(event, &leader->sibling_list, group_entry) {
837 if (!is_x86_event(event) ||
8113070d 838 event->state <= PERF_EVENT_STATE_OFF)
1da53e02
SE
839 continue;
840
841 if (n >= max_count)
aa2bc1ad 842 return -EINVAL;
1da53e02
SE
843
844 cpuc->event_list[n] = event;
845 n++;
846 }
847 return n;
848}
849
1da53e02 850static inline void x86_assign_hw_event(struct perf_event *event,
447a194b 851 struct cpu_hw_events *cpuc, int i)
1da53e02 852{
447a194b
SE
853 struct hw_perf_event *hwc = &event->hw;
854
855 hwc->idx = cpuc->assign[i];
856 hwc->last_cpu = smp_processor_id();
857 hwc->last_tag = ++cpuc->tags[i];
1da53e02 858
15c7ad51 859 if (hwc->idx == INTEL_PMC_IDX_FIXED_BTS) {
1da53e02
SE
860 hwc->config_base = 0;
861 hwc->event_base = 0;
15c7ad51 862 } else if (hwc->idx >= INTEL_PMC_IDX_FIXED) {
1da53e02 863 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
15c7ad51
RR
864 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 + (hwc->idx - INTEL_PMC_IDX_FIXED);
865 hwc->event_base_rdpmc = (hwc->idx - INTEL_PMC_IDX_FIXED) | 1<<30;
1da53e02 866 } else {
73d6e522
RR
867 hwc->config_base = x86_pmu_config_addr(hwc->idx);
868 hwc->event_base = x86_pmu_event_addr(hwc->idx);
0fbdad07 869 hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
1da53e02
SE
870 }
871}
872
447a194b
SE
873static inline int match_prev_assignment(struct hw_perf_event *hwc,
874 struct cpu_hw_events *cpuc,
875 int i)
876{
877 return hwc->idx == cpuc->assign[i] &&
878 hwc->last_cpu == smp_processor_id() &&
879 hwc->last_tag == cpuc->tags[i];
880}
881
a4eaf7f1 882static void x86_pmu_start(struct perf_event *event, int flags);
2e841873 883
a4eaf7f1 884static void x86_pmu_enable(struct pmu *pmu)
ee06094f 885{
89cbc767 886 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02
SE
887 struct perf_event *event;
888 struct hw_perf_event *hwc;
11164cd4 889 int i, added = cpuc->n_added;
1da53e02 890
85cf9dba 891 if (!x86_pmu_initialized())
2b9ff0db 892 return;
1a6e21f7
PZ
893
894 if (cpuc->enabled)
895 return;
896
1da53e02 897 if (cpuc->n_added) {
19925ce7 898 int n_running = cpuc->n_events - cpuc->n_added;
1da53e02
SE
899 /*
900 * apply assignment obtained either from
901 * hw_perf_group_sched_in() or x86_pmu_enable()
902 *
903 * step1: save events moving to new counters
1da53e02 904 */
19925ce7 905 for (i = 0; i < n_running; i++) {
1da53e02
SE
906 event = cpuc->event_list[i];
907 hwc = &event->hw;
908
447a194b
SE
909 /*
910 * we can avoid reprogramming counter if:
911 * - assigned same counter as last time
912 * - running on same CPU as last time
913 * - no other event has used the counter since
914 */
915 if (hwc->idx == -1 ||
916 match_prev_assignment(hwc, cpuc, i))
1da53e02
SE
917 continue;
918
a4eaf7f1
PZ
919 /*
920 * Ensure we don't accidentally enable a stopped
921 * counter simply because we rescheduled.
922 */
923 if (hwc->state & PERF_HES_STOPPED)
924 hwc->state |= PERF_HES_ARCH;
925
926 x86_pmu_stop(event, PERF_EF_UPDATE);
1da53e02
SE
927 }
928
c347a2f1
PZ
929 /*
930 * step2: reprogram moved events into new counters
931 */
1da53e02 932 for (i = 0; i < cpuc->n_events; i++) {
1da53e02
SE
933 event = cpuc->event_list[i];
934 hwc = &event->hw;
935
45e16a68 936 if (!match_prev_assignment(hwc, cpuc, i))
447a194b 937 x86_assign_hw_event(event, cpuc, i);
45e16a68
PZ
938 else if (i < n_running)
939 continue;
1da53e02 940
a4eaf7f1
PZ
941 if (hwc->state & PERF_HES_ARCH)
942 continue;
943
944 x86_pmu_start(event, PERF_EF_RELOAD);
1da53e02
SE
945 }
946 cpuc->n_added = 0;
947 perf_events_lapic_init();
948 }
1a6e21f7
PZ
949
950 cpuc->enabled = 1;
951 barrier();
952
11164cd4 953 x86_pmu.enable_all(added);
ee06094f 954}
ee06094f 955
245b2e70 956static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
241771ef 957
ee06094f
IM
958/*
959 * Set the next IRQ period, based on the hwc->period_left value.
cdd6c482 960 * To be called with the event disabled in hw:
ee06094f 961 */
de0428a7 962int x86_perf_event_set_period(struct perf_event *event)
241771ef 963{
07088edb 964 struct hw_perf_event *hwc = &event->hw;
e7850595 965 s64 left = local64_read(&hwc->period_left);
e4abb5d4 966 s64 period = hwc->sample_period;
7645a24c 967 int ret = 0, idx = hwc->idx;
ee06094f 968
15c7ad51 969 if (idx == INTEL_PMC_IDX_FIXED_BTS)
30dd568c
MM
970 return 0;
971
ee06094f 972 /*
af901ca1 973 * If we are way outside a reasonable range then just skip forward:
ee06094f
IM
974 */
975 if (unlikely(left <= -period)) {
976 left = period;
e7850595 977 local64_set(&hwc->period_left, left);
9e350de3 978 hwc->last_period = period;
e4abb5d4 979 ret = 1;
ee06094f
IM
980 }
981
982 if (unlikely(left <= 0)) {
983 left += period;
e7850595 984 local64_set(&hwc->period_left, left);
9e350de3 985 hwc->last_period = period;
e4abb5d4 986 ret = 1;
ee06094f 987 }
1c80f4b5 988 /*
dfc65094 989 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1c80f4b5
IM
990 */
991 if (unlikely(left < 2))
992 left = 2;
241771ef 993
e4abb5d4
PZ
994 if (left > x86_pmu.max_period)
995 left = x86_pmu.max_period;
996
294fe0f5
AK
997 if (x86_pmu.limit_period)
998 left = x86_pmu.limit_period(event, left);
999
245b2e70 1000 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
ee06094f
IM
1001
1002 /*
cdd6c482 1003 * The hw event starts counting from this event offset,
ee06094f
IM
1004 * mark it to be able to extra future deltas:
1005 */
e7850595 1006 local64_set(&hwc->prev_count, (u64)-left);
ee06094f 1007
73d6e522 1008 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
68aa00ac
CG
1009
1010 /*
1011 * Due to erratum on certan cpu we need
1012 * a second write to be sure the register
1013 * is updated properly
1014 */
1015 if (x86_pmu.perfctr_second_write) {
73d6e522 1016 wrmsrl(hwc->event_base,
948b1bb8 1017 (u64)(-left) & x86_pmu.cntval_mask);
68aa00ac 1018 }
e4abb5d4 1019
cdd6c482 1020 perf_event_update_userpage(event);
194002b2 1021
e4abb5d4 1022 return ret;
2f18d1e8
IM
1023}
1024
de0428a7 1025void x86_pmu_enable_event(struct perf_event *event)
7c90cc45 1026{
0a3aee0d 1027 if (__this_cpu_read(cpu_hw_events.enabled))
31fa58af
RR
1028 __x86_pmu_enable_event(&event->hw,
1029 ARCH_PERFMON_EVENTSEL_ENABLE);
241771ef
IM
1030}
1031
b690081d 1032/*
a4eaf7f1 1033 * Add a single event to the PMU.
1da53e02
SE
1034 *
1035 * The event is added to the group of enabled events
1036 * but only if it can be scehduled with existing events.
fe9081cc 1037 */
a4eaf7f1 1038static int x86_pmu_add(struct perf_event *event, int flags)
fe9081cc 1039{
89cbc767 1040 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02
SE
1041 struct hw_perf_event *hwc;
1042 int assign[X86_PMC_IDX_MAX];
1043 int n, n0, ret;
fe9081cc 1044
1da53e02 1045 hwc = &event->hw;
fe9081cc 1046
1da53e02 1047 n0 = cpuc->n_events;
24cd7f54
PZ
1048 ret = n = collect_events(cpuc, event, false);
1049 if (ret < 0)
1050 goto out;
53b441a5 1051
a4eaf7f1
PZ
1052 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1053 if (!(flags & PERF_EF_START))
1054 hwc->state |= PERF_HES_ARCH;
1055
4d1c52b0
LM
1056 /*
1057 * If group events scheduling transaction was started,
0d2eb44f 1058 * skip the schedulability test here, it will be performed
c347a2f1 1059 * at commit time (->commit_txn) as a whole.
4d1c52b0 1060 */
8d2cacbb 1061 if (cpuc->group_flag & PERF_EVENT_TXN)
24cd7f54 1062 goto done_collect;
4d1c52b0 1063
a072738e 1064 ret = x86_pmu.schedule_events(cpuc, n, assign);
1da53e02 1065 if (ret)
24cd7f54 1066 goto out;
1da53e02
SE
1067 /*
1068 * copy new assignment, now we know it is possible
1069 * will be used by hw_perf_enable()
1070 */
1071 memcpy(cpuc->assign, assign, n*sizeof(int));
7e2ae347 1072
24cd7f54 1073done_collect:
c347a2f1
PZ
1074 /*
1075 * Commit the collect_events() state. See x86_pmu_del() and
1076 * x86_pmu_*_txn().
1077 */
1da53e02 1078 cpuc->n_events = n;
356e1f2e 1079 cpuc->n_added += n - n0;
90151c35 1080 cpuc->n_txn += n - n0;
95cdd2e7 1081
24cd7f54
PZ
1082 ret = 0;
1083out:
24cd7f54 1084 return ret;
241771ef
IM
1085}
1086
a4eaf7f1 1087static void x86_pmu_start(struct perf_event *event, int flags)
d76a0812 1088{
89cbc767 1089 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
c08053e6
PZ
1090 int idx = event->hw.idx;
1091
a4eaf7f1
PZ
1092 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1093 return;
1094
1095 if (WARN_ON_ONCE(idx == -1))
1096 return;
1097
1098 if (flags & PERF_EF_RELOAD) {
1099 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1100 x86_perf_event_set_period(event);
1101 }
1102
1103 event->hw.state = 0;
d76a0812 1104
c08053e6
PZ
1105 cpuc->events[idx] = event;
1106 __set_bit(idx, cpuc->active_mask);
63e6be6d 1107 __set_bit(idx, cpuc->running);
aff3d91a 1108 x86_pmu.enable(event);
c08053e6 1109 perf_event_update_userpage(event);
a78ac325
PZ
1110}
1111
cdd6c482 1112void perf_event_print_debug(void)
241771ef 1113{
2f18d1e8 1114 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
ca037701 1115 u64 pebs;
cdd6c482 1116 struct cpu_hw_events *cpuc;
5bb9efe3 1117 unsigned long flags;
1e125676
IM
1118 int cpu, idx;
1119
948b1bb8 1120 if (!x86_pmu.num_counters)
1e125676 1121 return;
241771ef 1122
5bb9efe3 1123 local_irq_save(flags);
241771ef
IM
1124
1125 cpu = smp_processor_id();
cdd6c482 1126 cpuc = &per_cpu(cpu_hw_events, cpu);
241771ef 1127
faa28ae0 1128 if (x86_pmu.version >= 2) {
a1ef58f4
JSR
1129 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1130 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1131 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1132 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
ca037701 1133 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
a1ef58f4
JSR
1134
1135 pr_info("\n");
1136 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1137 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1138 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1139 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
ca037701 1140 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
f87ad35d 1141 }
7645a24c 1142 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
241771ef 1143
948b1bb8 1144 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
41bf4989
RR
1145 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1146 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
241771ef 1147
245b2e70 1148 prev_left = per_cpu(pmc_prev_left[idx], cpu);
241771ef 1149
a1ef58f4 1150 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
241771ef 1151 cpu, idx, pmc_ctrl);
a1ef58f4 1152 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
241771ef 1153 cpu, idx, pmc_count);
a1ef58f4 1154 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
ee06094f 1155 cpu, idx, prev_left);
241771ef 1156 }
948b1bb8 1157 for (idx = 0; idx < x86_pmu.num_counters_fixed; idx++) {
2f18d1e8
IM
1158 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1159
a1ef58f4 1160 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
2f18d1e8
IM
1161 cpu, idx, pmc_count);
1162 }
5bb9efe3 1163 local_irq_restore(flags);
241771ef
IM
1164}
1165
de0428a7 1166void x86_pmu_stop(struct perf_event *event, int flags)
241771ef 1167{
89cbc767 1168 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
cdd6c482 1169 struct hw_perf_event *hwc = &event->hw;
241771ef 1170
a4eaf7f1
PZ
1171 if (__test_and_clear_bit(hwc->idx, cpuc->active_mask)) {
1172 x86_pmu.disable(event);
1173 cpuc->events[hwc->idx] = NULL;
1174 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1175 hwc->state |= PERF_HES_STOPPED;
1176 }
30dd568c 1177
a4eaf7f1
PZ
1178 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1179 /*
1180 * Drain the remaining delta count out of a event
1181 * that we are disabling:
1182 */
1183 x86_perf_event_update(event);
1184 hwc->state |= PERF_HES_UPTODATE;
1185 }
2e841873
PZ
1186}
1187
a4eaf7f1 1188static void x86_pmu_del(struct perf_event *event, int flags)
2e841873 1189{
89cbc767 1190 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2e841873
PZ
1191 int i;
1192
2f7f73a5
SE
1193 /*
1194 * event is descheduled
1195 */
1196 event->hw.flags &= ~PERF_X86_EVENT_COMMITTED;
1197
90151c35
SE
1198 /*
1199 * If we're called during a txn, we don't need to do anything.
1200 * The events never got scheduled and ->cancel_txn will truncate
1201 * the event_list.
c347a2f1
PZ
1202 *
1203 * XXX assumes any ->del() called during a TXN will only be on
1204 * an event added during that same TXN.
90151c35 1205 */
8d2cacbb 1206 if (cpuc->group_flag & PERF_EVENT_TXN)
90151c35
SE
1207 return;
1208
c347a2f1
PZ
1209 /*
1210 * Not a TXN, therefore cleanup properly.
1211 */
a4eaf7f1 1212 x86_pmu_stop(event, PERF_EF_UPDATE);
194002b2 1213
1da53e02 1214 for (i = 0; i < cpuc->n_events; i++) {
c347a2f1
PZ
1215 if (event == cpuc->event_list[i])
1216 break;
1217 }
1da53e02 1218
c347a2f1
PZ
1219 if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1220 return;
26e61e89 1221
c347a2f1
PZ
1222 /* If we have a newly added event; make sure to decrease n_added. */
1223 if (i >= cpuc->n_events - cpuc->n_added)
1224 --cpuc->n_added;
1da53e02 1225
c347a2f1
PZ
1226 if (x86_pmu.put_event_constraints)
1227 x86_pmu.put_event_constraints(cpuc, event);
1228
1229 /* Delete the array entry. */
1230 while (++i < cpuc->n_events)
1231 cpuc->event_list[i-1] = cpuc->event_list[i];
1232 --cpuc->n_events;
1da53e02 1233
cdd6c482 1234 perf_event_update_userpage(event);
241771ef
IM
1235}
1236
de0428a7 1237int x86_pmu_handle_irq(struct pt_regs *regs)
a29aa8a7 1238{
df1a132b 1239 struct perf_sample_data data;
cdd6c482
IM
1240 struct cpu_hw_events *cpuc;
1241 struct perf_event *event;
11d1578f 1242 int idx, handled = 0;
9029a5e3
IM
1243 u64 val;
1244
89cbc767 1245 cpuc = this_cpu_ptr(&cpu_hw_events);
962bf7a6 1246
2bce5dac
DZ
1247 /*
1248 * Some chipsets need to unmask the LVTPC in a particular spot
1249 * inside the nmi handler. As a result, the unmasking was pushed
1250 * into all the nmi handlers.
1251 *
1252 * This generic handler doesn't seem to have any issues where the
1253 * unmasking occurs so it was left at the top.
1254 */
1255 apic_write(APIC_LVTPC, APIC_DM_NMI);
1256
948b1bb8 1257 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
63e6be6d
RR
1258 if (!test_bit(idx, cpuc->active_mask)) {
1259 /*
1260 * Though we deactivated the counter some cpus
1261 * might still deliver spurious interrupts still
1262 * in flight. Catch them:
1263 */
1264 if (__test_and_clear_bit(idx, cpuc->running))
1265 handled++;
a29aa8a7 1266 continue;
63e6be6d 1267 }
962bf7a6 1268
cdd6c482 1269 event = cpuc->events[idx];
a4016a79 1270
cc2ad4ba 1271 val = x86_perf_event_update(event);
948b1bb8 1272 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
48e22d56 1273 continue;
962bf7a6 1274
9e350de3 1275 /*
cdd6c482 1276 * event overflow
9e350de3 1277 */
4177c42a 1278 handled++;
fd0d000b 1279 perf_sample_data_init(&data, 0, event->hw.last_period);
9e350de3 1280
07088edb 1281 if (!x86_perf_event_set_period(event))
e4abb5d4
PZ
1282 continue;
1283
a8b0ca17 1284 if (perf_event_overflow(event, &data, regs))
a4eaf7f1 1285 x86_pmu_stop(event, 0);
a29aa8a7 1286 }
962bf7a6 1287
9e350de3
PZ
1288 if (handled)
1289 inc_irq_stat(apic_perf_irqs);
1290
a29aa8a7
RR
1291 return handled;
1292}
39d81eab 1293
cdd6c482 1294void perf_events_lapic_init(void)
241771ef 1295{
04da8a43 1296 if (!x86_pmu.apic || !x86_pmu_initialized())
241771ef 1297 return;
85cf9dba 1298
241771ef 1299 /*
c323d95f 1300 * Always use NMI for PMU
241771ef 1301 */
c323d95f 1302 apic_write(APIC_LVTPC, APIC_DM_NMI);
241771ef
IM
1303}
1304
9326638c 1305static int
9c48f1c6 1306perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
241771ef 1307{
14c63f17
DH
1308 u64 start_clock;
1309 u64 finish_clock;
e8a923cc 1310 int ret;
14c63f17 1311
cdd6c482 1312 if (!atomic_read(&active_events))
9c48f1c6 1313 return NMI_DONE;
4177c42a 1314
e8a923cc 1315 start_clock = sched_clock();
14c63f17 1316 ret = x86_pmu.handle_irq(regs);
e8a923cc 1317 finish_clock = sched_clock();
14c63f17
DH
1318
1319 perf_sample_event_took(finish_clock - start_clock);
1320
1321 return ret;
241771ef 1322}
9326638c 1323NOKPROBE_SYMBOL(perf_event_nmi_handler);
241771ef 1324
de0428a7
KW
1325struct event_constraint emptyconstraint;
1326struct event_constraint unconstrained;
f87ad35d 1327
148f9bb8 1328static int
3f6da390
PZ
1329x86_pmu_notifier(struct notifier_block *self, unsigned long action, void *hcpu)
1330{
1331 unsigned int cpu = (long)hcpu;
7fdba1ca 1332 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
b38b24ea 1333 int ret = NOTIFY_OK;
3f6da390
PZ
1334
1335 switch (action & ~CPU_TASKS_FROZEN) {
1336 case CPU_UP_PREPARE:
7fdba1ca 1337 cpuc->kfree_on_online = NULL;
3f6da390 1338 if (x86_pmu.cpu_prepare)
b38b24ea 1339 ret = x86_pmu.cpu_prepare(cpu);
3f6da390
PZ
1340 break;
1341
1342 case CPU_STARTING:
1343 if (x86_pmu.cpu_starting)
1344 x86_pmu.cpu_starting(cpu);
1345 break;
1346
7fdba1ca
PZ
1347 case CPU_ONLINE:
1348 kfree(cpuc->kfree_on_online);
1349 break;
1350
3f6da390
PZ
1351 case CPU_DYING:
1352 if (x86_pmu.cpu_dying)
1353 x86_pmu.cpu_dying(cpu);
1354 break;
1355
b38b24ea 1356 case CPU_UP_CANCELED:
3f6da390
PZ
1357 case CPU_DEAD:
1358 if (x86_pmu.cpu_dead)
1359 x86_pmu.cpu_dead(cpu);
1360 break;
1361
1362 default:
1363 break;
1364 }
1365
b38b24ea 1366 return ret;
3f6da390
PZ
1367}
1368
12558038
CG
1369static void __init pmu_check_apic(void)
1370{
1371 if (cpu_has_apic)
1372 return;
1373
1374 x86_pmu.apic = 0;
1375 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1376 pr_info("no hardware sampling interrupt available.\n");
c184c980
VW
1377
1378 /*
1379 * If we have a PMU initialized but no APIC
1380 * interrupts, we cannot sample hardware
1381 * events (user-space has to fall back and
1382 * sample via a hrtimer based software event):
1383 */
1384 pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1385
12558038
CG
1386}
1387
641cc938
JO
1388static struct attribute_group x86_pmu_format_group = {
1389 .name = "format",
1390 .attrs = NULL,
1391};
1392
8300daa2
JO
1393/*
1394 * Remove all undefined events (x86_pmu.event_map(id) == 0)
1395 * out of events_attr attributes.
1396 */
1397static void __init filter_events(struct attribute **attrs)
1398{
3a54aaa0
SE
1399 struct device_attribute *d;
1400 struct perf_pmu_events_attr *pmu_attr;
8300daa2
JO
1401 int i, j;
1402
1403 for (i = 0; attrs[i]; i++) {
3a54aaa0
SE
1404 d = (struct device_attribute *)attrs[i];
1405 pmu_attr = container_of(d, struct perf_pmu_events_attr, attr);
1406 /* str trumps id */
1407 if (pmu_attr->event_str)
1408 continue;
8300daa2
JO
1409 if (x86_pmu.event_map(i))
1410 continue;
1411
1412 for (j = i; attrs[j]; j++)
1413 attrs[j] = attrs[j + 1];
1414
1415 /* Check the shifted attr. */
1416 i--;
1417 }
1418}
1419
1a6461b1
AK
1420/* Merge two pointer arrays */
1421static __init struct attribute **merge_attr(struct attribute **a, struct attribute **b)
1422{
1423 struct attribute **new;
1424 int j, i;
1425
1426 for (j = 0; a[j]; j++)
1427 ;
1428 for (i = 0; b[i]; i++)
1429 j++;
1430 j++;
1431
1432 new = kmalloc(sizeof(struct attribute *) * j, GFP_KERNEL);
1433 if (!new)
1434 return NULL;
1435
1436 j = 0;
1437 for (i = 0; a[i]; i++)
1438 new[j++] = a[i];
1439 for (i = 0; b[i]; i++)
1440 new[j++] = b[i];
1441 new[j] = NULL;
1442
1443 return new;
1444}
1445
f20093ee 1446ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr,
a4747393
JO
1447 char *page)
1448{
1449 struct perf_pmu_events_attr *pmu_attr = \
1450 container_of(attr, struct perf_pmu_events_attr, attr);
a4747393 1451 u64 config = x86_pmu.event_map(pmu_attr->id);
a4747393 1452
3a54aaa0
SE
1453 /* string trumps id */
1454 if (pmu_attr->event_str)
1455 return sprintf(page, "%s", pmu_attr->event_str);
a4747393 1456
3a54aaa0
SE
1457 return x86_pmu.events_sysfs_show(page, config);
1458}
a4747393
JO
1459
1460EVENT_ATTR(cpu-cycles, CPU_CYCLES );
1461EVENT_ATTR(instructions, INSTRUCTIONS );
1462EVENT_ATTR(cache-references, CACHE_REFERENCES );
1463EVENT_ATTR(cache-misses, CACHE_MISSES );
1464EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
1465EVENT_ATTR(branch-misses, BRANCH_MISSES );
1466EVENT_ATTR(bus-cycles, BUS_CYCLES );
1467EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
1468EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
1469EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
1470
1471static struct attribute *empty_attrs;
1472
95d18aa2 1473static struct attribute *events_attr[] = {
a4747393
JO
1474 EVENT_PTR(CPU_CYCLES),
1475 EVENT_PTR(INSTRUCTIONS),
1476 EVENT_PTR(CACHE_REFERENCES),
1477 EVENT_PTR(CACHE_MISSES),
1478 EVENT_PTR(BRANCH_INSTRUCTIONS),
1479 EVENT_PTR(BRANCH_MISSES),
1480 EVENT_PTR(BUS_CYCLES),
1481 EVENT_PTR(STALLED_CYCLES_FRONTEND),
1482 EVENT_PTR(STALLED_CYCLES_BACKEND),
1483 EVENT_PTR(REF_CPU_CYCLES),
1484 NULL,
1485};
1486
1487static struct attribute_group x86_pmu_events_group = {
1488 .name = "events",
1489 .attrs = events_attr,
1490};
1491
0bf79d44 1492ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
43c032fe 1493{
43c032fe
JO
1494 u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
1495 u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
1496 bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
1497 bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
1498 bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
1499 bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
1500 ssize_t ret;
1501
1502 /*
1503 * We have whole page size to spend and just little data
1504 * to write, so we can safely use sprintf.
1505 */
1506 ret = sprintf(page, "event=0x%02llx", event);
1507
1508 if (umask)
1509 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
1510
1511 if (edge)
1512 ret += sprintf(page + ret, ",edge");
1513
1514 if (pc)
1515 ret += sprintf(page + ret, ",pc");
1516
1517 if (any)
1518 ret += sprintf(page + ret, ",any");
1519
1520 if (inv)
1521 ret += sprintf(page + ret, ",inv");
1522
1523 if (cmask)
1524 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
1525
1526 ret += sprintf(page + ret, "\n");
1527
1528 return ret;
1529}
1530
dda99116 1531static int __init init_hw_perf_events(void)
b56a3802 1532{
c1d6f42f 1533 struct x86_pmu_quirk *quirk;
72eae04d
RR
1534 int err;
1535
cdd6c482 1536 pr_info("Performance Events: ");
1123e3ad 1537
b56a3802
JSR
1538 switch (boot_cpu_data.x86_vendor) {
1539 case X86_VENDOR_INTEL:
72eae04d 1540 err = intel_pmu_init();
b56a3802 1541 break;
f87ad35d 1542 case X86_VENDOR_AMD:
72eae04d 1543 err = amd_pmu_init();
f87ad35d 1544 break;
4138960a 1545 default:
8a3da6c7 1546 err = -ENOTSUPP;
b56a3802 1547 }
1123e3ad 1548 if (err != 0) {
cdd6c482 1549 pr_cont("no PMU driver, software events only.\n");
004417a6 1550 return 0;
1123e3ad 1551 }
b56a3802 1552
12558038
CG
1553 pmu_check_apic();
1554
33c6d6a7 1555 /* sanity check that the hardware exists or is emulated */
4407204c 1556 if (!check_hw_exists())
004417a6 1557 return 0;
33c6d6a7 1558
1123e3ad 1559 pr_cont("%s PMU driver.\n", x86_pmu.name);
faa28ae0 1560
e97df763
PZ
1561 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
1562
c1d6f42f
PZ
1563 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
1564 quirk->func();
3c44780b 1565
a1eac7ac
RR
1566 if (!x86_pmu.intel_ctrl)
1567 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
241771ef 1568
cdd6c482 1569 perf_events_lapic_init();
9c48f1c6 1570 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1123e3ad 1571
63b14649 1572 unconstrained = (struct event_constraint)
948b1bb8 1573 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
9fac2cf3 1574 0, x86_pmu.num_counters, 0, 0);
63b14649 1575
641cc938 1576 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
0c9d42ed 1577
f20093ee
SE
1578 if (x86_pmu.event_attrs)
1579 x86_pmu_events_group.attrs = x86_pmu.event_attrs;
1580
a4747393
JO
1581 if (!x86_pmu.events_sysfs_show)
1582 x86_pmu_events_group.attrs = &empty_attrs;
8300daa2
JO
1583 else
1584 filter_events(x86_pmu_events_group.attrs);
a4747393 1585
1a6461b1
AK
1586 if (x86_pmu.cpu_events) {
1587 struct attribute **tmp;
1588
1589 tmp = merge_attr(x86_pmu_events_group.attrs, x86_pmu.cpu_events);
1590 if (!WARN_ON(!tmp))
1591 x86_pmu_events_group.attrs = tmp;
1592 }
1593
57c0c15b 1594 pr_info("... version: %d\n", x86_pmu.version);
948b1bb8
RR
1595 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
1596 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
1597 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
57c0c15b 1598 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
948b1bb8 1599 pr_info("... fixed-purpose events: %d\n", x86_pmu.num_counters_fixed);
d6dc0b4e 1600 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
3f6da390 1601
2e80a82a 1602 perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
3f6da390 1603 perf_cpu_notifier(x86_pmu_notifier);
004417a6
PZ
1604
1605 return 0;
241771ef 1606}
004417a6 1607early_initcall(init_hw_perf_events);
621a01ea 1608
cdd6c482 1609static inline void x86_pmu_read(struct perf_event *event)
ee06094f 1610{
cc2ad4ba 1611 x86_perf_event_update(event);
ee06094f
IM
1612}
1613
4d1c52b0
LM
1614/*
1615 * Start group events scheduling transaction
1616 * Set the flag to make pmu::enable() not perform the
1617 * schedulability test, it will be performed at commit time
1618 */
51b0fe39 1619static void x86_pmu_start_txn(struct pmu *pmu)
4d1c52b0 1620{
33696fc0 1621 perf_pmu_disable(pmu);
0a3aee0d
TH
1622 __this_cpu_or(cpu_hw_events.group_flag, PERF_EVENT_TXN);
1623 __this_cpu_write(cpu_hw_events.n_txn, 0);
4d1c52b0
LM
1624}
1625
1626/*
1627 * Stop group events scheduling transaction
1628 * Clear the flag and pmu::enable() will perform the
1629 * schedulability test.
1630 */
51b0fe39 1631static void x86_pmu_cancel_txn(struct pmu *pmu)
4d1c52b0 1632{
0a3aee0d 1633 __this_cpu_and(cpu_hw_events.group_flag, ~PERF_EVENT_TXN);
90151c35 1634 /*
c347a2f1
PZ
1635 * Truncate collected array by the number of events added in this
1636 * transaction. See x86_pmu_add() and x86_pmu_*_txn().
90151c35 1637 */
0a3aee0d
TH
1638 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
1639 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
33696fc0 1640 perf_pmu_enable(pmu);
4d1c52b0
LM
1641}
1642
1643/*
1644 * Commit group events scheduling transaction
1645 * Perform the group schedulability test as a whole
1646 * Return 0 if success
c347a2f1
PZ
1647 *
1648 * Does not cancel the transaction on failure; expects the caller to do this.
4d1c52b0 1649 */
51b0fe39 1650static int x86_pmu_commit_txn(struct pmu *pmu)
4d1c52b0 1651{
89cbc767 1652 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
4d1c52b0
LM
1653 int assign[X86_PMC_IDX_MAX];
1654 int n, ret;
1655
1656 n = cpuc->n_events;
1657
1658 if (!x86_pmu_initialized())
1659 return -EAGAIN;
1660
1661 ret = x86_pmu.schedule_events(cpuc, n, assign);
1662 if (ret)
1663 return ret;
1664
1665 /*
1666 * copy new assignment, now we know it is possible
1667 * will be used by hw_perf_enable()
1668 */
1669 memcpy(cpuc->assign, assign, n*sizeof(int));
1670
8d2cacbb 1671 cpuc->group_flag &= ~PERF_EVENT_TXN;
33696fc0 1672 perf_pmu_enable(pmu);
4d1c52b0
LM
1673 return 0;
1674}
cd8a38d3
SE
1675/*
1676 * a fake_cpuc is used to validate event groups. Due to
1677 * the extra reg logic, we need to also allocate a fake
1678 * per_core and per_cpu structure. Otherwise, group events
1679 * using extra reg may conflict without the kernel being
1680 * able to catch this when the last event gets added to
1681 * the group.
1682 */
1683static void free_fake_cpuc(struct cpu_hw_events *cpuc)
1684{
1685 kfree(cpuc->shared_regs);
1686 kfree(cpuc);
1687}
1688
1689static struct cpu_hw_events *allocate_fake_cpuc(void)
1690{
1691 struct cpu_hw_events *cpuc;
1692 int cpu = raw_smp_processor_id();
1693
1694 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
1695 if (!cpuc)
1696 return ERR_PTR(-ENOMEM);
1697
1698 /* only needed, if we have extra_regs */
1699 if (x86_pmu.extra_regs) {
1700 cpuc->shared_regs = allocate_shared_regs(cpu);
1701 if (!cpuc->shared_regs)
1702 goto error;
1703 }
b430f7c4 1704 cpuc->is_fake = 1;
cd8a38d3
SE
1705 return cpuc;
1706error:
1707 free_fake_cpuc(cpuc);
1708 return ERR_PTR(-ENOMEM);
1709}
4d1c52b0 1710
ca037701
PZ
1711/*
1712 * validate that we can schedule this event
1713 */
1714static int validate_event(struct perf_event *event)
1715{
1716 struct cpu_hw_events *fake_cpuc;
1717 struct event_constraint *c;
1718 int ret = 0;
1719
cd8a38d3
SE
1720 fake_cpuc = allocate_fake_cpuc();
1721 if (IS_ERR(fake_cpuc))
1722 return PTR_ERR(fake_cpuc);
ca037701
PZ
1723
1724 c = x86_pmu.get_event_constraints(fake_cpuc, event);
1725
1726 if (!c || !c->weight)
aa2bc1ad 1727 ret = -EINVAL;
ca037701
PZ
1728
1729 if (x86_pmu.put_event_constraints)
1730 x86_pmu.put_event_constraints(fake_cpuc, event);
1731
cd8a38d3 1732 free_fake_cpuc(fake_cpuc);
ca037701
PZ
1733
1734 return ret;
1735}
1736
1da53e02
SE
1737/*
1738 * validate a single event group
1739 *
1740 * validation include:
184f412c
IM
1741 * - check events are compatible which each other
1742 * - events do not compete for the same counter
1743 * - number of events <= number of counters
1da53e02
SE
1744 *
1745 * validation ensures the group can be loaded onto the
1746 * PMU if it was the only group available.
1747 */
fe9081cc
PZ
1748static int validate_group(struct perf_event *event)
1749{
1da53e02 1750 struct perf_event *leader = event->group_leader;
502568d5 1751 struct cpu_hw_events *fake_cpuc;
aa2bc1ad 1752 int ret = -EINVAL, n;
fe9081cc 1753
cd8a38d3
SE
1754 fake_cpuc = allocate_fake_cpuc();
1755 if (IS_ERR(fake_cpuc))
1756 return PTR_ERR(fake_cpuc);
1da53e02
SE
1757 /*
1758 * the event is not yet connected with its
1759 * siblings therefore we must first collect
1760 * existing siblings, then add the new event
1761 * before we can simulate the scheduling
1762 */
502568d5 1763 n = collect_events(fake_cpuc, leader, true);
1da53e02 1764 if (n < 0)
cd8a38d3 1765 goto out;
fe9081cc 1766
502568d5
PZ
1767 fake_cpuc->n_events = n;
1768 n = collect_events(fake_cpuc, event, false);
1da53e02 1769 if (n < 0)
cd8a38d3 1770 goto out;
fe9081cc 1771
502568d5 1772 fake_cpuc->n_events = n;
1da53e02 1773
a072738e 1774 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
502568d5 1775
502568d5 1776out:
cd8a38d3 1777 free_fake_cpuc(fake_cpuc);
502568d5 1778 return ret;
fe9081cc
PZ
1779}
1780
dda99116 1781static int x86_pmu_event_init(struct perf_event *event)
621a01ea 1782{
51b0fe39 1783 struct pmu *tmp;
621a01ea
IM
1784 int err;
1785
b0a873eb
PZ
1786 switch (event->attr.type) {
1787 case PERF_TYPE_RAW:
1788 case PERF_TYPE_HARDWARE:
1789 case PERF_TYPE_HW_CACHE:
1790 break;
1791
1792 default:
1793 return -ENOENT;
1794 }
1795
1796 err = __x86_pmu_event_init(event);
fe9081cc 1797 if (!err) {
8113070d
SE
1798 /*
1799 * we temporarily connect event to its pmu
1800 * such that validate_group() can classify
1801 * it as an x86 event using is_x86_event()
1802 */
1803 tmp = event->pmu;
1804 event->pmu = &pmu;
1805
fe9081cc
PZ
1806 if (event->group_leader != event)
1807 err = validate_group(event);
ca037701
PZ
1808 else
1809 err = validate_event(event);
8113070d
SE
1810
1811 event->pmu = tmp;
fe9081cc 1812 }
a1792cda 1813 if (err) {
cdd6c482
IM
1814 if (event->destroy)
1815 event->destroy(event);
a1792cda 1816 }
621a01ea 1817
7911d3f7
AL
1818 if (ACCESS_ONCE(x86_pmu.attr_rdpmc))
1819 event->hw.flags |= PERF_X86_EVENT_RDPMC_ALLOWED;
1820
b0a873eb 1821 return err;
621a01ea 1822}
d7d59fb3 1823
7911d3f7
AL
1824static void refresh_pce(void *ignored)
1825{
1826 if (current->mm)
1827 load_mm_cr4(current->mm);
1828}
1829
1830static void x86_pmu_event_mapped(struct perf_event *event)
1831{
1832 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
1833 return;
1834
1835 if (atomic_inc_return(&current->mm->context.perf_rdpmc_allowed) == 1)
1836 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
1837}
1838
1839static void x86_pmu_event_unmapped(struct perf_event *event)
1840{
1841 if (!current->mm)
1842 return;
1843
1844 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
1845 return;
1846
1847 if (atomic_dec_and_test(&current->mm->context.perf_rdpmc_allowed))
1848 on_each_cpu_mask(mm_cpumask(current->mm), refresh_pce, NULL, 1);
1849}
1850
fe4a3308
PZ
1851static int x86_pmu_event_idx(struct perf_event *event)
1852{
1853 int idx = event->hw.idx;
1854
7911d3f7 1855 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
c7206205
PZ
1856 return 0;
1857
15c7ad51
RR
1858 if (x86_pmu.num_counters_fixed && idx >= INTEL_PMC_IDX_FIXED) {
1859 idx -= INTEL_PMC_IDX_FIXED;
fe4a3308
PZ
1860 idx |= 1 << 30;
1861 }
1862
1863 return idx + 1;
1864}
1865
0c9d42ed
PZ
1866static ssize_t get_attr_rdpmc(struct device *cdev,
1867 struct device_attribute *attr,
1868 char *buf)
1869{
1870 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
1871}
1872
0c9d42ed
PZ
1873static ssize_t set_attr_rdpmc(struct device *cdev,
1874 struct device_attribute *attr,
1875 const char *buf, size_t count)
1876{
e2b297fc
SK
1877 unsigned long val;
1878 ssize_t ret;
1879
1880 ret = kstrtoul(buf, 0, &val);
1881 if (ret)
1882 return ret;
e97df763 1883
a6673429
AL
1884 if (val > 2)
1885 return -EINVAL;
1886
e97df763
PZ
1887 if (x86_pmu.attr_rdpmc_broken)
1888 return -ENOTSUPP;
0c9d42ed 1889
a6673429
AL
1890 if ((val == 2) != (x86_pmu.attr_rdpmc == 2)) {
1891 /*
1892 * Changing into or out of always available, aka
1893 * perf-event-bypassing mode. This path is extremely slow,
1894 * but only root can trigger it, so it's okay.
1895 */
1896 if (val == 2)
1897 static_key_slow_inc(&rdpmc_always_available);
1898 else
1899 static_key_slow_dec(&rdpmc_always_available);
1900 on_each_cpu(refresh_pce, NULL, 1);
1901 }
1902
1903 x86_pmu.attr_rdpmc = val;
1904
0c9d42ed
PZ
1905 return count;
1906}
1907
1908static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
1909
1910static struct attribute *x86_pmu_attrs[] = {
1911 &dev_attr_rdpmc.attr,
1912 NULL,
1913};
1914
1915static struct attribute_group x86_pmu_attr_group = {
1916 .attrs = x86_pmu_attrs,
1917};
1918
1919static const struct attribute_group *x86_pmu_attr_groups[] = {
1920 &x86_pmu_attr_group,
641cc938 1921 &x86_pmu_format_group,
a4747393 1922 &x86_pmu_events_group,
0c9d42ed
PZ
1923 NULL,
1924};
1925
ba532500
YZ
1926static void x86_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
1927{
1928 if (x86_pmu.sched_task)
1929 x86_pmu.sched_task(ctx, sched_in);
1930}
1931
c93dc84c
PZ
1932void perf_check_microcode(void)
1933{
1934 if (x86_pmu.check_microcode)
1935 x86_pmu.check_microcode();
1936}
1937EXPORT_SYMBOL_GPL(perf_check_microcode);
1938
b0a873eb 1939static struct pmu pmu = {
d010b332
SE
1940 .pmu_enable = x86_pmu_enable,
1941 .pmu_disable = x86_pmu_disable,
a4eaf7f1 1942
c93dc84c 1943 .attr_groups = x86_pmu_attr_groups,
0c9d42ed 1944
c93dc84c 1945 .event_init = x86_pmu_event_init,
a4eaf7f1 1946
7911d3f7
AL
1947 .event_mapped = x86_pmu_event_mapped,
1948 .event_unmapped = x86_pmu_event_unmapped,
1949
d010b332
SE
1950 .add = x86_pmu_add,
1951 .del = x86_pmu_del,
1952 .start = x86_pmu_start,
1953 .stop = x86_pmu_stop,
1954 .read = x86_pmu_read,
a4eaf7f1 1955
c93dc84c
PZ
1956 .start_txn = x86_pmu_start_txn,
1957 .cancel_txn = x86_pmu_cancel_txn,
1958 .commit_txn = x86_pmu_commit_txn,
fe4a3308 1959
c93dc84c 1960 .event_idx = x86_pmu_event_idx,
ba532500 1961 .sched_task = x86_pmu_sched_task,
e18bf526 1962 .task_ctx_size = sizeof(struct x86_perf_task_context),
b0a873eb
PZ
1963};
1964
c1317ec2
AL
1965void arch_perf_update_userpage(struct perf_event *event,
1966 struct perf_event_mmap_page *userpg, u64 now)
e3f3541c 1967{
20d1c86a
PZ
1968 struct cyc2ns_data *data;
1969
fa731587
PZ
1970 userpg->cap_user_time = 0;
1971 userpg->cap_user_time_zero = 0;
7911d3f7
AL
1972 userpg->cap_user_rdpmc =
1973 !!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED);
c7206205
PZ
1974 userpg->pmc_width = x86_pmu.cntval_bits;
1975
35af99e6 1976 if (!sched_clock_stable())
e3f3541c
PZ
1977 return;
1978
20d1c86a
PZ
1979 data = cyc2ns_read_begin();
1980
fa731587 1981 userpg->cap_user_time = 1;
20d1c86a
PZ
1982 userpg->time_mult = data->cyc2ns_mul;
1983 userpg->time_shift = data->cyc2ns_shift;
1984 userpg->time_offset = data->cyc2ns_offset - now;
c73deb6a 1985
d8b11a0c 1986 userpg->cap_user_time_zero = 1;
20d1c86a
PZ
1987 userpg->time_zero = data->cyc2ns_offset;
1988
1989 cyc2ns_read_end(data);
e3f3541c
PZ
1990}
1991
d7d59fb3
PZ
1992/*
1993 * callchain support
1994 */
1995
d7d59fb3
PZ
1996static int backtrace_stack(void *data, char *name)
1997{
038e836e 1998 return 0;
d7d59fb3
PZ
1999}
2000
2001static void backtrace_address(void *data, unsigned long addr, int reliable)
2002{
2003 struct perf_callchain_entry *entry = data;
2004
70791ce9 2005 perf_callchain_store(entry, addr);
d7d59fb3
PZ
2006}
2007
2008static const struct stacktrace_ops backtrace_ops = {
d7d59fb3
PZ
2009 .stack = backtrace_stack,
2010 .address = backtrace_address,
06d65bda 2011 .walk_stack = print_context_stack_bp,
d7d59fb3
PZ
2012};
2013
56962b44
FW
2014void
2015perf_callchain_kernel(struct perf_callchain_entry *entry, struct pt_regs *regs)
d7d59fb3 2016{
927c7a9e
FW
2017 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2018 /* TODO: We don't support guest os callchain now */
ed805261 2019 return;
927c7a9e
FW
2020 }
2021
70791ce9 2022 perf_callchain_store(entry, regs->ip);
d7d59fb3 2023
e8e999cf 2024 dump_trace(NULL, regs, NULL, 0, &backtrace_ops, entry);
d7d59fb3
PZ
2025}
2026
bc6ca7b3
AS
2027static inline int
2028valid_user_frame(const void __user *fp, unsigned long size)
2029{
2030 return (__range_not_ok(fp, size, TASK_SIZE) == 0);
2031}
2032
d07bdfd3
PZ
2033static unsigned long get_segment_base(unsigned int segment)
2034{
2035 struct desc_struct *desc;
2036 int idx = segment >> 3;
2037
2038 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2039 if (idx > LDT_ENTRIES)
2040 return 0;
2041
2042 if (idx > current->active_mm->context.size)
2043 return 0;
2044
2045 desc = current->active_mm->context.ldt;
2046 } else {
2047 if (idx > GDT_ENTRIES)
2048 return 0;
2049
89cbc767 2050 desc = raw_cpu_ptr(gdt_page.gdt);
d07bdfd3
PZ
2051 }
2052
2053 return get_desc_base(desc + idx);
2054}
2055
257ef9d2 2056#ifdef CONFIG_COMPAT
d1a797f3
PA
2057
2058#include <asm/compat.h>
2059
257ef9d2
TE
2060static inline int
2061perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
74193ef0 2062{
257ef9d2 2063 /* 32-bit process in 64-bit kernel. */
d07bdfd3 2064 unsigned long ss_base, cs_base;
257ef9d2
TE
2065 struct stack_frame_ia32 frame;
2066 const void __user *fp;
74193ef0 2067
257ef9d2
TE
2068 if (!test_thread_flag(TIF_IA32))
2069 return 0;
2070
d07bdfd3
PZ
2071 cs_base = get_segment_base(regs->cs);
2072 ss_base = get_segment_base(regs->ss);
2073
2074 fp = compat_ptr(ss_base + regs->bp);
257ef9d2
TE
2075 while (entry->nr < PERF_MAX_STACK_DEPTH) {
2076 unsigned long bytes;
2077 frame.next_frame = 0;
2078 frame.return_address = 0;
2079
2080 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
0a196848 2081 if (bytes != 0)
257ef9d2 2082 break;
74193ef0 2083
bc6ca7b3
AS
2084 if (!valid_user_frame(fp, sizeof(frame)))
2085 break;
2086
d07bdfd3
PZ
2087 perf_callchain_store(entry, cs_base + frame.return_address);
2088 fp = compat_ptr(ss_base + frame.next_frame);
257ef9d2
TE
2089 }
2090 return 1;
d7d59fb3 2091}
257ef9d2
TE
2092#else
2093static inline int
2094perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry *entry)
2095{
2096 return 0;
2097}
2098#endif
d7d59fb3 2099
56962b44
FW
2100void
2101perf_callchain_user(struct perf_callchain_entry *entry, struct pt_regs *regs)
d7d59fb3
PZ
2102{
2103 struct stack_frame frame;
2104 const void __user *fp;
2105
927c7a9e
FW
2106 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2107 /* TODO: We don't support guest os callchain now */
ed805261 2108 return;
927c7a9e 2109 }
5a6cec3a 2110
d07bdfd3
PZ
2111 /*
2112 * We don't know what to do with VM86 stacks.. ignore them for now.
2113 */
2114 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2115 return;
2116
74193ef0 2117 fp = (void __user *)regs->bp;
d7d59fb3 2118
70791ce9 2119 perf_callchain_store(entry, regs->ip);
d7d59fb3 2120
20afc60f
AV
2121 if (!current->mm)
2122 return;
2123
257ef9d2
TE
2124 if (perf_callchain_user32(regs, entry))
2125 return;
2126
f9188e02 2127 while (entry->nr < PERF_MAX_STACK_DEPTH) {
257ef9d2 2128 unsigned long bytes;
038e836e 2129 frame.next_frame = NULL;
d7d59fb3
PZ
2130 frame.return_address = 0;
2131
257ef9d2 2132 bytes = copy_from_user_nmi(&frame, fp, sizeof(frame));
0a196848 2133 if (bytes != 0)
d7d59fb3
PZ
2134 break;
2135
bc6ca7b3
AS
2136 if (!valid_user_frame(fp, sizeof(frame)))
2137 break;
2138
70791ce9 2139 perf_callchain_store(entry, frame.return_address);
038e836e 2140 fp = frame.next_frame;
d7d59fb3
PZ
2141 }
2142}
2143
d07bdfd3
PZ
2144/*
2145 * Deal with code segment offsets for the various execution modes:
2146 *
2147 * VM86 - the good olde 16 bit days, where the linear address is
2148 * 20 bits and we use regs->ip + 0x10 * regs->cs.
2149 *
2150 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
2151 * to figure out what the 32bit base address is.
2152 *
2153 * X32 - has TIF_X32 set, but is running in x86_64
2154 *
2155 * X86_64 - CS,DS,SS,ES are all zero based.
2156 */
2157static unsigned long code_segment_base(struct pt_regs *regs)
39447b38 2158{
d07bdfd3
PZ
2159 /*
2160 * If we are in VM86 mode, add the segment offset to convert to a
2161 * linear address.
2162 */
2163 if (regs->flags & X86_VM_MASK)
2164 return 0x10 * regs->cs;
2165
2166 /*
2167 * For IA32 we look at the GDT/LDT segment base to convert the
2168 * effective IP to a linear address.
2169 */
2170#ifdef CONFIG_X86_32
2171 if (user_mode(regs) && regs->cs != __USER_CS)
2172 return get_segment_base(regs->cs);
2173#else
2174 if (test_thread_flag(TIF_IA32)) {
2175 if (user_mode(regs) && regs->cs != __USER32_CS)
2176 return get_segment_base(regs->cs);
2177 }
2178#endif
2179 return 0;
2180}
dcf46b94 2181
d07bdfd3
PZ
2182unsigned long perf_instruction_pointer(struct pt_regs *regs)
2183{
39447b38 2184 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
d07bdfd3 2185 return perf_guest_cbs->get_guest_ip();
dcf46b94 2186
d07bdfd3 2187 return regs->ip + code_segment_base(regs);
39447b38
ZY
2188}
2189
2190unsigned long perf_misc_flags(struct pt_regs *regs)
2191{
2192 int misc = 0;
dcf46b94 2193
39447b38 2194 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
dcf46b94
ZY
2195 if (perf_guest_cbs->is_user_mode())
2196 misc |= PERF_RECORD_MISC_GUEST_USER;
2197 else
2198 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
2199 } else {
d07bdfd3 2200 if (user_mode(regs))
dcf46b94
ZY
2201 misc |= PERF_RECORD_MISC_USER;
2202 else
2203 misc |= PERF_RECORD_MISC_KERNEL;
2204 }
2205
39447b38 2206 if (regs->flags & PERF_EFLAGS_EXACT)
ab608344 2207 misc |= PERF_RECORD_MISC_EXACT_IP;
39447b38
ZY
2208
2209 return misc;
2210}
b3d9468a
GN
2211
2212void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
2213{
2214 cap->version = x86_pmu.version;
2215 cap->num_counters_gp = x86_pmu.num_counters;
2216 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
2217 cap->bit_width_gp = x86_pmu.cntval_bits;
2218 cap->bit_width_fixed = x86_pmu.cntval_bits;
2219 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
2220 cap->events_mask_len = x86_pmu.events_mask_len;
2221}
2222EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);