perf/x86: Hybrid PMU support for unconstrained
[linux-block.git] / arch / x86 / events / core.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
90eec103 8 * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra
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>
eb008eb6
PG
20#include <linux/export.h>
21#include <linux/init.h>
241771ef 22#include <linux/kdebug.h>
589ee628 23#include <linux/sched/mm.h>
e6017571 24#include <linux/sched/clock.h>
d7d59fb3 25#include <linux/uaccess.h>
5a0e3ad6 26#include <linux/slab.h>
30dd568c 27#include <linux/cpu.h>
272d30be 28#include <linux/bitops.h>
0c9d42ed 29#include <linux/device.h>
46b1b577 30#include <linux/nospec.h>
7c9903c9 31#include <linux/static_call.h>
241771ef 32
241771ef 33#include <asm/apic.h>
d7d59fb3 34#include <asm/stacktrace.h>
4e935e47 35#include <asm/nmi.h>
69092624 36#include <asm/smp.h>
c8e5910e 37#include <asm/alternative.h>
7911d3f7 38#include <asm/mmu_context.h>
375074cc 39#include <asm/tlbflush.h>
e3f3541c 40#include <asm/timer.h>
d07bdfd3
PZ
41#include <asm/desc.h>
42#include <asm/ldt.h>
35f4d9b3 43#include <asm/unwind.h>
241771ef 44
27f6d22b 45#include "perf_event.h"
de0428a7 46
de0428a7 47struct x86_pmu x86_pmu __read_mostly;
61e76d53 48static struct pmu pmu;
efc9f05d 49
de0428a7 50DEFINE_PER_CPU(struct cpu_hw_events, cpu_hw_events) = {
b0f3f28e 51 .enabled = 1,
61e76d53 52 .pmu = &pmu,
b0f3f28e 53};
241771ef 54
405b4537 55DEFINE_STATIC_KEY_FALSE(rdpmc_never_available_key);
631fe154 56DEFINE_STATIC_KEY_FALSE(rdpmc_always_available_key);
d0946a88 57DEFINE_STATIC_KEY_FALSE(perf_is_hybrid);
a6673429 58
7c9903c9
PZ
59/*
60 * This here uses DEFINE_STATIC_CALL_NULL() to get a static_call defined
61 * from just a typename, as opposed to an actual function.
62 */
63DEFINE_STATIC_CALL_NULL(x86_pmu_handle_irq, *x86_pmu.handle_irq);
64DEFINE_STATIC_CALL_NULL(x86_pmu_disable_all, *x86_pmu.disable_all);
65DEFINE_STATIC_CALL_NULL(x86_pmu_enable_all, *x86_pmu.enable_all);
66DEFINE_STATIC_CALL_NULL(x86_pmu_enable, *x86_pmu.enable);
67DEFINE_STATIC_CALL_NULL(x86_pmu_disable, *x86_pmu.disable);
68
69DEFINE_STATIC_CALL_NULL(x86_pmu_add, *x86_pmu.add);
70DEFINE_STATIC_CALL_NULL(x86_pmu_del, *x86_pmu.del);
71DEFINE_STATIC_CALL_NULL(x86_pmu_read, *x86_pmu.read);
72
73DEFINE_STATIC_CALL_NULL(x86_pmu_schedule_events, *x86_pmu.schedule_events);
74DEFINE_STATIC_CALL_NULL(x86_pmu_get_event_constraints, *x86_pmu.get_event_constraints);
75DEFINE_STATIC_CALL_NULL(x86_pmu_put_event_constraints, *x86_pmu.put_event_constraints);
76
77DEFINE_STATIC_CALL_NULL(x86_pmu_start_scheduling, *x86_pmu.start_scheduling);
78DEFINE_STATIC_CALL_NULL(x86_pmu_commit_scheduling, *x86_pmu.commit_scheduling);
79DEFINE_STATIC_CALL_NULL(x86_pmu_stop_scheduling, *x86_pmu.stop_scheduling);
80
81DEFINE_STATIC_CALL_NULL(x86_pmu_sched_task, *x86_pmu.sched_task);
82DEFINE_STATIC_CALL_NULL(x86_pmu_swap_task_ctx, *x86_pmu.swap_task_ctx);
83
84DEFINE_STATIC_CALL_NULL(x86_pmu_drain_pebs, *x86_pmu.drain_pebs);
85DEFINE_STATIC_CALL_NULL(x86_pmu_pebs_aliases, *x86_pmu.pebs_aliases);
86
c8e2fe13
SC
87/*
88 * This one is magic, it will get called even when PMU init fails (because
89 * there is no PMU), in which case it should simply return NULL.
90 */
91DEFINE_STATIC_CALL_RET0(x86_pmu_guest_get_msrs, *x86_pmu.guest_get_msrs);
abd562df 92
de0428a7 93u64 __read_mostly hw_cache_event_ids
8326f44d
IM
94 [PERF_COUNT_HW_CACHE_MAX]
95 [PERF_COUNT_HW_CACHE_OP_MAX]
96 [PERF_COUNT_HW_CACHE_RESULT_MAX];
de0428a7 97u64 __read_mostly hw_cache_extra_regs
e994d7d2
AK
98 [PERF_COUNT_HW_CACHE_MAX]
99 [PERF_COUNT_HW_CACHE_OP_MAX]
100 [PERF_COUNT_HW_CACHE_RESULT_MAX];
8326f44d 101
ee06094f 102/*
cdd6c482
IM
103 * Propagate event elapsed time into the generic event.
104 * Can only be executed on the CPU where the event is active.
ee06094f
IM
105 * Returns the delta events processed.
106 */
de0428a7 107u64 x86_perf_event_update(struct perf_event *event)
ee06094f 108{
cc2ad4ba 109 struct hw_perf_event *hwc = &event->hw;
948b1bb8 110 int shift = 64 - x86_pmu.cntval_bits;
ec3232bd 111 u64 prev_raw_count, new_raw_count;
7f612a7f 112 u64 delta;
ee06094f 113
027440b5 114 if (unlikely(!hwc->event_base))
30dd568c
MM
115 return 0;
116
7b2c05a1
KL
117 if (unlikely(is_topdown_count(event)) && x86_pmu.update_topdown_event)
118 return x86_pmu.update_topdown_event(event);
119
ee06094f 120 /*
cdd6c482 121 * Careful: an NMI might modify the previous event value.
ee06094f
IM
122 *
123 * Our tactic to handle this is to first atomically read and
124 * exchange a new raw count - then add that new-prev delta
cdd6c482 125 * count to the generic event atomically:
ee06094f
IM
126 */
127again:
e7850595 128 prev_raw_count = local64_read(&hwc->prev_count);
c48b6053 129 rdpmcl(hwc->event_base_rdpmc, new_raw_count);
ee06094f 130
e7850595 131 if (local64_cmpxchg(&hwc->prev_count, prev_raw_count,
ee06094f
IM
132 new_raw_count) != prev_raw_count)
133 goto again;
134
135 /*
136 * Now we have the new raw value and have updated the prev
137 * timestamp already. We can now calculate the elapsed delta
cdd6c482 138 * (event-)time and add that to the generic event.
ee06094f
IM
139 *
140 * Careful, not all hw sign-extends above the physical width
ec3232bd 141 * of the count.
ee06094f 142 */
ec3232bd
PZ
143 delta = (new_raw_count << shift) - (prev_raw_count << shift);
144 delta >>= shift;
ee06094f 145
e7850595
PZ
146 local64_add(delta, &event->count);
147 local64_sub(delta, &hwc->period_left);
4b7bfd0d
RR
148
149 return new_raw_count;
ee06094f
IM
150}
151
a7e3ed1e
AK
152/*
153 * Find and validate any extra registers to set up.
154 */
155static int x86_pmu_extra_regs(u64 config, struct perf_event *event)
156{
efc9f05d 157 struct hw_perf_event_extra *reg;
a7e3ed1e
AK
158 struct extra_reg *er;
159
efc9f05d 160 reg = &event->hw.extra_reg;
a7e3ed1e
AK
161
162 if (!x86_pmu.extra_regs)
163 return 0;
164
165 for (er = x86_pmu.extra_regs; er->msr; er++) {
166 if (er->event != (config & er->config_mask))
167 continue;
168 if (event->attr.config1 & ~er->valid_mask)
169 return -EINVAL;
338b522c
KL
170 /* Check if the extra msrs can be safely accessed*/
171 if (!er->extra_msr_access)
172 return -ENXIO;
efc9f05d
SE
173
174 reg->idx = er->idx;
175 reg->config = event->attr.config1;
176 reg->reg = er->msr;
a7e3ed1e
AK
177 break;
178 }
179 return 0;
180}
181
cdd6c482 182static atomic_t active_events;
1b7b938f 183static atomic_t pmc_refcount;
4e935e47
PZ
184static DEFINE_MUTEX(pmc_reserve_mutex);
185
b27ea29c
RR
186#ifdef CONFIG_X86_LOCAL_APIC
187
d4b294bf
KL
188static inline int get_possible_num_counters(void)
189{
190 int i, num_counters = x86_pmu.num_counters;
191
192 if (!is_hybrid())
193 return num_counters;
194
195 for (i = 0; i < x86_pmu.num_hybrid_pmus; i++)
196 num_counters = max_t(int, num_counters, x86_pmu.hybrid_pmu[i].num_counters);
197
198 return num_counters;
199}
200
4e935e47
PZ
201static bool reserve_pmc_hardware(void)
202{
d4b294bf 203 int i, num_counters = get_possible_num_counters();
4e935e47 204
d4b294bf 205 for (i = 0; i < num_counters; i++) {
41bf4989 206 if (!reserve_perfctr_nmi(x86_pmu_event_addr(i)))
4e935e47
PZ
207 goto perfctr_fail;
208 }
209
d4b294bf 210 for (i = 0; i < num_counters; i++) {
41bf4989 211 if (!reserve_evntsel_nmi(x86_pmu_config_addr(i)))
4e935e47
PZ
212 goto eventsel_fail;
213 }
214
215 return true;
216
217eventsel_fail:
218 for (i--; i >= 0; i--)
41bf4989 219 release_evntsel_nmi(x86_pmu_config_addr(i));
4e935e47 220
d4b294bf 221 i = num_counters;
4e935e47
PZ
222
223perfctr_fail:
224 for (i--; i >= 0; i--)
41bf4989 225 release_perfctr_nmi(x86_pmu_event_addr(i));
4e935e47 226
4e935e47
PZ
227 return false;
228}
229
230static void release_pmc_hardware(void)
231{
d4b294bf 232 int i, num_counters = get_possible_num_counters();
4e935e47 233
d4b294bf 234 for (i = 0; i < num_counters; i++) {
41bf4989
RR
235 release_perfctr_nmi(x86_pmu_event_addr(i));
236 release_evntsel_nmi(x86_pmu_config_addr(i));
4e935e47 237 }
4e935e47
PZ
238}
239
b27ea29c
RR
240#else
241
242static bool reserve_pmc_hardware(void) { return true; }
243static void release_pmc_hardware(void) {}
244
245#endif
246
fc4b8fca 247bool check_hw_exists(struct pmu *pmu, int num_counters, int num_counters_fixed)
33c6d6a7 248{
11d8b058
AB
249 u64 val, val_fail = -1, val_new= ~0;
250 int i, reg, reg_fail = -1, ret = 0;
a5ebe0ba 251 int bios_fail = 0;
68ab7476 252 int reg_safe = -1;
33c6d6a7 253
4407204c
PZ
254 /*
255 * Check to see if the BIOS enabled any of the counters, if so
256 * complain and bail.
257 */
fc4b8fca 258 for (i = 0; i < num_counters; i++) {
41bf4989 259 reg = x86_pmu_config_addr(i);
4407204c
PZ
260 ret = rdmsrl_safe(reg, &val);
261 if (ret)
262 goto msr_fail;
a5ebe0ba
GD
263 if (val & ARCH_PERFMON_EVENTSEL_ENABLE) {
264 bios_fail = 1;
265 val_fail = val;
266 reg_fail = reg;
68ab7476
DZ
267 } else {
268 reg_safe = i;
a5ebe0ba 269 }
4407204c
PZ
270 }
271
fc4b8fca 272 if (num_counters_fixed) {
4407204c
PZ
273 reg = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
274 ret = rdmsrl_safe(reg, &val);
275 if (ret)
276 goto msr_fail;
fc4b8fca
KL
277 for (i = 0; i < num_counters_fixed; i++) {
278 if (fixed_counter_disabled(i, pmu))
32451614 279 continue;
a5ebe0ba
GD
280 if (val & (0x03 << i*4)) {
281 bios_fail = 1;
282 val_fail = val;
283 reg_fail = reg;
284 }
4407204c
PZ
285 }
286 }
287
68ab7476
DZ
288 /*
289 * If all the counters are enabled, the below test will always
290 * fail. The tools will also become useless in this scenario.
291 * Just fail and disable the hardware counters.
292 */
293
294 if (reg_safe == -1) {
295 reg = reg_safe;
296 goto msr_fail;
297 }
298
4407204c 299 /*
bffd5fc2
AP
300 * Read the current value, change it and read it back to see if it
301 * matches, this is needed to detect certain hardware emulators
302 * (qemu/kvm) that don't trap on the MSR access and always return 0s.
4407204c 303 */
68ab7476 304 reg = x86_pmu_event_addr(reg_safe);
bffd5fc2
AP
305 if (rdmsrl_safe(reg, &val))
306 goto msr_fail;
307 val ^= 0xffffUL;
f285f92f
RR
308 ret = wrmsrl_safe(reg, val);
309 ret |= rdmsrl_safe(reg, &val_new);
33c6d6a7 310 if (ret || val != val_new)
4407204c 311 goto msr_fail;
33c6d6a7 312
45daae57
IM
313 /*
314 * We still allow the PMU driver to operate:
315 */
a5ebe0ba 316 if (bios_fail) {
1b74dde7
CY
317 pr_cont("Broken BIOS detected, complain to your hardware vendor.\n");
318 pr_err(FW_BUG "the BIOS has corrupted hw-PMU resources (MSR %x is %Lx)\n",
319 reg_fail, val_fail);
a5ebe0ba 320 }
45daae57
IM
321
322 return true;
4407204c
PZ
323
324msr_fail:
005bd007
JG
325 if (boot_cpu_has(X86_FEATURE_HYPERVISOR)) {
326 pr_cont("PMU not available due to virtualization, using software events only.\n");
327 } else {
328 pr_cont("Broken PMU hardware detected, using software events only.\n");
329 pr_err("Failed to access perfctr msr (MSR %x is %Lx)\n",
330 reg, val_new);
331 }
45daae57 332
4407204c 333 return false;
33c6d6a7
DZ
334}
335
cdd6c482 336static void hw_perf_event_destroy(struct perf_event *event)
4e935e47 337{
6b099d9b 338 x86_release_hardware();
1b7b938f 339 atomic_dec(&active_events);
4e935e47
PZ
340}
341
48070342
AS
342void hw_perf_lbr_event_destroy(struct perf_event *event)
343{
344 hw_perf_event_destroy(event);
345
346 /* undo the lbr/bts event accounting */
347 x86_del_exclusive(x86_lbr_exclusive_lbr);
348}
349
85cf9dba
RR
350static inline int x86_pmu_initialized(void)
351{
352 return x86_pmu.handle_irq != NULL;
353}
354
8326f44d 355static inline int
e994d7d2 356set_ext_hw_attr(struct hw_perf_event *hwc, struct perf_event *event)
8326f44d 357{
e994d7d2 358 struct perf_event_attr *attr = &event->attr;
8326f44d
IM
359 unsigned int cache_type, cache_op, cache_result;
360 u64 config, val;
361
362 config = attr->config;
363
ef9ee4ad 364 cache_type = (config >> 0) & 0xff;
8326f44d
IM
365 if (cache_type >= PERF_COUNT_HW_CACHE_MAX)
366 return -EINVAL;
ef9ee4ad 367 cache_type = array_index_nospec(cache_type, PERF_COUNT_HW_CACHE_MAX);
8326f44d
IM
368
369 cache_op = (config >> 8) & 0xff;
370 if (cache_op >= PERF_COUNT_HW_CACHE_OP_MAX)
371 return -EINVAL;
ef9ee4ad 372 cache_op = array_index_nospec(cache_op, PERF_COUNT_HW_CACHE_OP_MAX);
8326f44d
IM
373
374 cache_result = (config >> 16) & 0xff;
375 if (cache_result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
376 return -EINVAL;
ef9ee4ad 377 cache_result = array_index_nospec(cache_result, PERF_COUNT_HW_CACHE_RESULT_MAX);
8326f44d
IM
378
379 val = hw_cache_event_ids[cache_type][cache_op][cache_result];
380
381 if (val == 0)
382 return -ENOENT;
383
384 if (val == -1)
385 return -EINVAL;
386
387 hwc->config |= val;
e994d7d2
AK
388 attr->config1 = hw_cache_extra_regs[cache_type][cache_op][cache_result];
389 return x86_pmu_extra_regs(val, event);
8326f44d
IM
390}
391
6b099d9b
AS
392int x86_reserve_hardware(void)
393{
394 int err = 0;
395
1b7b938f 396 if (!atomic_inc_not_zero(&pmc_refcount)) {
6b099d9b 397 mutex_lock(&pmc_reserve_mutex);
1b7b938f 398 if (atomic_read(&pmc_refcount) == 0) {
6b099d9b
AS
399 if (!reserve_pmc_hardware())
400 err = -EBUSY;
401 else
402 reserve_ds_buffers();
403 }
404 if (!err)
1b7b938f 405 atomic_inc(&pmc_refcount);
6b099d9b
AS
406 mutex_unlock(&pmc_reserve_mutex);
407 }
408
409 return err;
410}
411
412void x86_release_hardware(void)
413{
1b7b938f 414 if (atomic_dec_and_mutex_lock(&pmc_refcount, &pmc_reserve_mutex)) {
6b099d9b
AS
415 release_pmc_hardware();
416 release_ds_buffers();
c085fb87 417 release_lbr_buffers();
6b099d9b
AS
418 mutex_unlock(&pmc_reserve_mutex);
419 }
420}
421
48070342
AS
422/*
423 * Check if we can create event of a certain type (that no conflicting events
424 * are present).
425 */
426int x86_add_exclusive(unsigned int what)
427{
93472aff 428 int i;
48070342 429
b0c1ef52
AK
430 /*
431 * When lbr_pt_coexist we allow PT to coexist with either LBR or BTS.
432 * LBR and BTS are still mutually exclusive.
433 */
434 if (x86_pmu.lbr_pt_coexist && what == x86_lbr_exclusive_pt)
92ca7da4 435 goto out;
ccbebba4 436
93472aff
PZ
437 if (!atomic_inc_not_zero(&x86_pmu.lbr_exclusive[what])) {
438 mutex_lock(&pmc_reserve_mutex);
439 for (i = 0; i < ARRAY_SIZE(x86_pmu.lbr_exclusive); i++) {
440 if (i != what && atomic_read(&x86_pmu.lbr_exclusive[i]))
441 goto fail_unlock;
442 }
443 atomic_inc(&x86_pmu.lbr_exclusive[what]);
444 mutex_unlock(&pmc_reserve_mutex);
6b099d9b 445 }
48070342 446
92ca7da4 447out:
93472aff
PZ
448 atomic_inc(&active_events);
449 return 0;
48070342 450
93472aff 451fail_unlock:
48070342 452 mutex_unlock(&pmc_reserve_mutex);
93472aff 453 return -EBUSY;
48070342
AS
454}
455
456void x86_del_exclusive(unsigned int what)
457{
92ca7da4
AS
458 atomic_dec(&active_events);
459
460 /*
461 * See the comment in x86_add_exclusive().
462 */
b0c1ef52 463 if (x86_pmu.lbr_pt_coexist && what == x86_lbr_exclusive_pt)
ccbebba4
AS
464 return;
465
48070342
AS
466 atomic_dec(&x86_pmu.lbr_exclusive[what]);
467}
468
de0428a7 469int x86_setup_perfctr(struct perf_event *event)
c1726f34
RR
470{
471 struct perf_event_attr *attr = &event->attr;
472 struct hw_perf_event *hwc = &event->hw;
473 u64 config;
474
6c7e550f 475 if (!is_sampling_event(event)) {
c1726f34
RR
476 hwc->sample_period = x86_pmu.max_period;
477 hwc->last_period = hwc->sample_period;
e7850595 478 local64_set(&hwc->period_left, hwc->sample_period);
c1726f34
RR
479 }
480
481 if (attr->type == PERF_TYPE_RAW)
ed13ec58 482 return x86_pmu_extra_regs(event->attr.config, event);
c1726f34
RR
483
484 if (attr->type == PERF_TYPE_HW_CACHE)
e994d7d2 485 return set_ext_hw_attr(hwc, event);
c1726f34
RR
486
487 if (attr->config >= x86_pmu.max_events)
488 return -EINVAL;
489
46b1b577
PZ
490 attr->config = array_index_nospec((unsigned long)attr->config, x86_pmu.max_events);
491
c1726f34
RR
492 /*
493 * The generic map:
494 */
495 config = x86_pmu.event_map(attr->config);
496
497 if (config == 0)
498 return -ENOENT;
499
500 if (config == -1LL)
501 return -EINVAL;
502
c1726f34
RR
503 hwc->config |= config;
504
505 return 0;
506}
4261e0e0 507
ff3fb511
SE
508/*
509 * check that branch_sample_type is compatible with
510 * settings needed for precise_ip > 1 which implies
511 * using the LBR to capture ALL taken branches at the
512 * priv levels of the measurement
513 */
514static inline int precise_br_compat(struct perf_event *event)
515{
516 u64 m = event->attr.branch_sample_type;
517 u64 b = 0;
518
519 /* must capture all branches */
520 if (!(m & PERF_SAMPLE_BRANCH_ANY))
521 return 0;
522
523 m &= PERF_SAMPLE_BRANCH_KERNEL | PERF_SAMPLE_BRANCH_USER;
524
525 if (!event->attr.exclude_user)
526 b |= PERF_SAMPLE_BRANCH_USER;
527
528 if (!event->attr.exclude_kernel)
529 b |= PERF_SAMPLE_BRANCH_KERNEL;
530
531 /*
532 * ignore PERF_SAMPLE_BRANCH_HV, not supported on x86
533 */
534
535 return m == b;
536}
537
b00233b5 538int x86_pmu_max_precise(void)
a072738e 539{
b00233b5
AK
540 int precise = 0;
541
542 /* Support for constant skid */
543 if (x86_pmu.pebs_active && !x86_pmu.pebs_broken) {
544 precise++;
ab608344 545
b00233b5
AK
546 /* Support for IP fixup */
547 if (x86_pmu.lbr_nr || x86_pmu.intel_cap.pebs_format >= 2)
ab608344
PZ
548 precise++;
549
b00233b5
AK
550 if (x86_pmu.pebs_prec_dist)
551 precise++;
552 }
553 return precise;
554}
72469764 555
b00233b5
AK
556int x86_pmu_hw_config(struct perf_event *event)
557{
558 if (event->attr.precise_ip) {
559 int precise = x86_pmu_max_precise();
ab608344
PZ
560
561 if (event->attr.precise_ip > precise)
562 return -EOPNOTSUPP;
18e7a45a
JO
563
564 /* There's no sense in having PEBS for non sampling events: */
565 if (!is_sampling_event(event))
566 return -EINVAL;
4b854900
YZ
567 }
568 /*
569 * check that PEBS LBR correction does not conflict with
570 * whatever the user is asking with attr->branch_sample_type
571 */
572 if (event->attr.precise_ip > 1 && x86_pmu.intel_cap.pebs_format < 2) {
573 u64 *br_type = &event->attr.branch_sample_type;
574
575 if (has_branch_stack(event)) {
576 if (!precise_br_compat(event))
577 return -EOPNOTSUPP;
578
579 /* branch_sample_type is compatible */
580
581 } else {
582 /*
583 * user did not specify branch_sample_type
584 *
585 * For PEBS fixups, we capture all
586 * the branches at the priv level of the
587 * event.
588 */
589 *br_type = PERF_SAMPLE_BRANCH_ANY;
590
591 if (!event->attr.exclude_user)
592 *br_type |= PERF_SAMPLE_BRANCH_USER;
593
594 if (!event->attr.exclude_kernel)
595 *br_type |= PERF_SAMPLE_BRANCH_KERNEL;
ff3fb511 596 }
ab608344
PZ
597 }
598
e18bf526
YZ
599 if (event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_CALL_STACK)
600 event->attach_state |= PERF_ATTACH_TASK_DATA;
601
a072738e
CG
602 /*
603 * Generate PMC IRQs:
604 * (keep 'enabled' bit clear for now)
605 */
b4cdc5c2 606 event->hw.config = ARCH_PERFMON_EVENTSEL_INT;
a072738e
CG
607
608 /*
609 * Count user and OS events unless requested not to
610 */
b4cdc5c2
PZ
611 if (!event->attr.exclude_user)
612 event->hw.config |= ARCH_PERFMON_EVENTSEL_USR;
613 if (!event->attr.exclude_kernel)
614 event->hw.config |= ARCH_PERFMON_EVENTSEL_OS;
a072738e 615
b4cdc5c2
PZ
616 if (event->attr.type == PERF_TYPE_RAW)
617 event->hw.config |= event->attr.config & X86_RAW_EVENT_MASK;
a072738e 618
294fe0f5
AK
619 if (event->attr.sample_period && x86_pmu.limit_period) {
620 if (x86_pmu.limit_period(event, event->attr.sample_period) >
621 event->attr.sample_period)
622 return -EINVAL;
623 }
624
878068ea 625 /* sample_regs_user never support XMM registers */
dce86ac7 626 if (unlikely(event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK))
878068ea
KL
627 return -EINVAL;
628 /*
629 * Besides the general purpose registers, XMM registers may
630 * be collected in PEBS on some platforms, e.g. Icelake
631 */
dce86ac7 632 if (unlikely(event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK)) {
cd6b984f 633 if (!(event->pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS))
878068ea
KL
634 return -EINVAL;
635
636 if (!event->attr.precise_ip)
637 return -EINVAL;
638 }
639
9d0fcba6 640 return x86_setup_perfctr(event);
a098f448
RR
641}
642
241771ef 643/*
0d48696f 644 * Setup the hardware configuration for a given attr_type
241771ef 645 */
b0a873eb 646static int __x86_pmu_event_init(struct perf_event *event)
241771ef 647{
4e935e47 648 int err;
241771ef 649
85cf9dba
RR
650 if (!x86_pmu_initialized())
651 return -ENODEV;
241771ef 652
6b099d9b 653 err = x86_reserve_hardware();
4e935e47
PZ
654 if (err)
655 return err;
656
1b7b938f 657 atomic_inc(&active_events);
cdd6c482 658 event->destroy = hw_perf_event_destroy;
a1792cda 659
4261e0e0
RR
660 event->hw.idx = -1;
661 event->hw.last_cpu = -1;
662 event->hw.last_tag = ~0ULL;
b690081d 663
efc9f05d
SE
664 /* mark unused */
665 event->hw.extra_reg.idx = EXTRA_REG_NONE;
b36817e8
SE
666 event->hw.branch_reg.idx = EXTRA_REG_NONE;
667
9d0fcba6 668 return x86_pmu.hw_config(event);
4261e0e0
RR
669}
670
de0428a7 671void x86_pmu_disable_all(void)
f87ad35d 672{
89cbc767 673 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
9e35ad38
PZ
674 int idx;
675
948b1bb8 676 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
57388912 677 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
b0f3f28e
PZ
678 u64 val;
679
43f6201a 680 if (!test_bit(idx, cpuc->active_mask))
4295ee62 681 continue;
41bf4989 682 rdmsrl(x86_pmu_config_addr(idx), val);
bb1165d6 683 if (!(val & ARCH_PERFMON_EVENTSEL_ENABLE))
4295ee62 684 continue;
bb1165d6 685 val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
41bf4989 686 wrmsrl(x86_pmu_config_addr(idx), val);
57388912
KP
687 if (is_counter_pair(hwc))
688 wrmsrl(x86_pmu_config_addr(idx + 1), 0);
f87ad35d 689 }
f87ad35d
JSR
690}
691
abd562df
LX
692struct perf_guest_switch_msr *perf_guest_get_msrs(int *nr)
693{
694 return static_call(x86_pmu_guest_get_msrs)(nr);
695}
696EXPORT_SYMBOL_GPL(perf_guest_get_msrs);
697
c3d266c8
KL
698/*
699 * There may be PMI landing after enabled=0. The PMI hitting could be before or
700 * after disable_all.
701 *
702 * If PMI hits before disable_all, the PMU will be disabled in the NMI handler.
703 * It will not be re-enabled in the NMI handler again, because enabled=0. After
704 * handling the NMI, disable_all will be called, which will not change the
705 * state either. If PMI hits after disable_all, the PMU is already disabled
706 * before entering NMI handler. The NMI handler will not change the state
707 * either.
708 *
709 * So either situation is harmless.
710 */
a4eaf7f1 711static void x86_pmu_disable(struct pmu *pmu)
b56a3802 712{
89cbc767 713 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02 714
85cf9dba 715 if (!x86_pmu_initialized())
9e35ad38 716 return;
1da53e02 717
1a6e21f7
PZ
718 if (!cpuc->enabled)
719 return;
720
721 cpuc->n_added = 0;
722 cpuc->enabled = 0;
723 barrier();
1da53e02 724
7c9903c9 725 static_call(x86_pmu_disable_all)();
b56a3802 726}
241771ef 727
de0428a7 728void x86_pmu_enable_all(int added)
f87ad35d 729{
89cbc767 730 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
f87ad35d
JSR
731 int idx;
732
948b1bb8 733 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
d45dd923 734 struct hw_perf_event *hwc = &cpuc->events[idx]->hw;
b0f3f28e 735
43f6201a 736 if (!test_bit(idx, cpuc->active_mask))
4295ee62 737 continue;
984b838c 738
d45dd923 739 __x86_pmu_enable_event(hwc, ARCH_PERFMON_EVENTSEL_ENABLE);
f87ad35d
JSR
740 }
741}
742
1da53e02
SE
743static inline int is_x86_event(struct perf_event *event)
744{
745 return event->pmu == &pmu;
746}
747
61e76d53 748struct pmu *x86_get_pmu(unsigned int cpu)
f447e4eb 749{
61e76d53
KL
750 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
751
752 /*
753 * All CPUs of the hybrid type have been offline.
754 * The x86_get_pmu() should not be invoked.
755 */
756 if (WARN_ON_ONCE(!cpuc->pmu))
757 return &pmu;
758
759 return cpuc->pmu;
f447e4eb 760}
1e2ad28f
RR
761/*
762 * Event scheduler state:
763 *
764 * Assign events iterating over all events and counters, beginning
765 * with events with least weights first. Keep the current iterator
766 * state in struct sched_state.
767 */
768struct sched_state {
769 int weight;
770 int event; /* event index */
771 int counter; /* counter index */
772 int unassigned; /* number of events to be assigned left */
cc1790cf 773 int nr_gp; /* number of GP counters used */
57388912 774 u64 used;
1e2ad28f
RR
775};
776
bc1738f6
RR
777/* Total max is X86_PMC_IDX_MAX, but we are O(n!) limited */
778#define SCHED_STATES_MAX 2
779
1e2ad28f
RR
780struct perf_sched {
781 int max_weight;
782 int max_events;
cc1790cf
PZ
783 int max_gp;
784 int saved_states;
b371b594 785 struct event_constraint **constraints;
1e2ad28f 786 struct sched_state state;
bc1738f6 787 struct sched_state saved[SCHED_STATES_MAX];
1e2ad28f
RR
788};
789
790/*
791 * Initialize interator that runs through all events and counters.
792 */
b371b594 793static void perf_sched_init(struct perf_sched *sched, struct event_constraint **constraints,
cc1790cf 794 int num, int wmin, int wmax, int gpmax)
1e2ad28f
RR
795{
796 int idx;
797
798 memset(sched, 0, sizeof(*sched));
799 sched->max_events = num;
800 sched->max_weight = wmax;
cc1790cf 801 sched->max_gp = gpmax;
b371b594 802 sched->constraints = constraints;
1e2ad28f
RR
803
804 for (idx = 0; idx < num; idx++) {
b371b594 805 if (constraints[idx]->weight == wmin)
1e2ad28f
RR
806 break;
807 }
808
809 sched->state.event = idx; /* start with min weight */
810 sched->state.weight = wmin;
811 sched->state.unassigned = num;
812}
813
bc1738f6
RR
814static void perf_sched_save_state(struct perf_sched *sched)
815{
816 if (WARN_ON_ONCE(sched->saved_states >= SCHED_STATES_MAX))
817 return;
818
819 sched->saved[sched->saved_states] = sched->state;
820 sched->saved_states++;
821}
822
823static bool perf_sched_restore_state(struct perf_sched *sched)
824{
825 if (!sched->saved_states)
826 return false;
827
828 sched->saved_states--;
829 sched->state = sched->saved[sched->saved_states];
830
57388912
KP
831 /* this assignment didn't work out */
832 /* XXX broken vs EVENT_PAIR */
833 sched->state.used &= ~BIT_ULL(sched->state.counter);
834
835 /* try the next one */
836 sched->state.counter++;
bc1738f6
RR
837
838 return true;
839}
840
1e2ad28f
RR
841/*
842 * Select a counter for the current event to schedule. Return true on
843 * success.
844 */
bc1738f6 845static bool __perf_sched_find_counter(struct perf_sched *sched)
1e2ad28f
RR
846{
847 struct event_constraint *c;
848 int idx;
849
850 if (!sched->state.unassigned)
851 return false;
852
853 if (sched->state.event >= sched->max_events)
854 return false;
855
b371b594 856 c = sched->constraints[sched->state.event];
4defea85 857 /* Prefer fixed purpose counters */
15c7ad51
RR
858 if (c->idxmsk64 & (~0ULL << INTEL_PMC_IDX_FIXED)) {
859 idx = INTEL_PMC_IDX_FIXED;
307b1cd7 860 for_each_set_bit_from(idx, c->idxmsk, X86_PMC_IDX_MAX) {
57388912
KP
861 u64 mask = BIT_ULL(idx);
862
863 if (sched->state.used & mask)
864 continue;
865
866 sched->state.used |= mask;
867 goto done;
4defea85
PZ
868 }
869 }
cc1790cf 870
1e2ad28f
RR
871 /* Grab the first unused counter starting with idx */
872 idx = sched->state.counter;
15c7ad51 873 for_each_set_bit_from(idx, c->idxmsk, INTEL_PMC_IDX_FIXED) {
57388912 874 u64 mask = BIT_ULL(idx);
cc1790cf 875
57388912
KP
876 if (c->flags & PERF_X86_EVENT_PAIR)
877 mask |= mask << 1;
878
879 if (sched->state.used & mask)
880 continue;
881
882 if (sched->state.nr_gp++ >= sched->max_gp)
883 return false;
884
885 sched->state.used |= mask;
886 goto done;
1e2ad28f 887 }
1e2ad28f 888
4defea85
PZ
889 return false;
890
891done:
892 sched->state.counter = idx;
1e2ad28f 893
bc1738f6
RR
894 if (c->overlap)
895 perf_sched_save_state(sched);
896
897 return true;
898}
899
900static bool perf_sched_find_counter(struct perf_sched *sched)
901{
902 while (!__perf_sched_find_counter(sched)) {
903 if (!perf_sched_restore_state(sched))
904 return false;
905 }
906
1e2ad28f
RR
907 return true;
908}
909
910/*
911 * Go through all unassigned events and find the next one to schedule.
912 * Take events with the least weight first. Return true on success.
913 */
914static bool perf_sched_next_event(struct perf_sched *sched)
915{
916 struct event_constraint *c;
917
918 if (!sched->state.unassigned || !--sched->state.unassigned)
919 return false;
920
921 do {
922 /* next event */
923 sched->state.event++;
924 if (sched->state.event >= sched->max_events) {
925 /* next weight */
926 sched->state.event = 0;
927 sched->state.weight++;
928 if (sched->state.weight > sched->max_weight)
929 return false;
930 }
b371b594 931 c = sched->constraints[sched->state.event];
1e2ad28f
RR
932 } while (c->weight != sched->state.weight);
933
934 sched->state.counter = 0; /* start with first counter */
935
936 return true;
937}
938
939/*
940 * Assign a counter for each event.
941 */
b371b594 942int perf_assign_events(struct event_constraint **constraints, int n,
cc1790cf 943 int wmin, int wmax, int gpmax, int *assign)
1e2ad28f
RR
944{
945 struct perf_sched sched;
946
cc1790cf 947 perf_sched_init(&sched, constraints, n, wmin, wmax, gpmax);
1e2ad28f
RR
948
949 do {
950 if (!perf_sched_find_counter(&sched))
951 break; /* failed */
952 if (assign)
953 assign[sched.state.event] = sched.state.counter;
954 } while (perf_sched_next_event(&sched));
955
956 return sched.state.unassigned;
957}
4a3dc121 958EXPORT_SYMBOL_GPL(perf_assign_events);
1e2ad28f 959
de0428a7 960int x86_schedule_events(struct cpu_hw_events *cpuc, int n, int *assign)
1da53e02 961{
d4b294bf 962 int num_counters = hybrid(cpuc->pmu, num_counters);
43b45780 963 struct event_constraint *c;
2f7f73a5 964 struct perf_event *e;
f80deefa 965 int n0, i, wmin, wmax, unsched = 0;
1da53e02 966 struct hw_perf_event *hwc;
57388912 967 u64 used_mask = 0;
1da53e02 968
f80deefa
PZ
969 /*
970 * Compute the number of events already present; see x86_pmu_add(),
971 * validate_group() and x86_pmu_commit_txn(). For the former two
972 * cpuc->n_events hasn't been updated yet, while for the latter
973 * cpuc->n_txn contains the number of events added in the current
974 * transaction.
975 */
976 n0 = cpuc->n_events;
977 if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
978 n0 -= cpuc->n_txn;
979
7c9903c9 980 static_call_cond(x86_pmu_start_scheduling)(cpuc);
c5362c0c 981
1e2ad28f 982 for (i = 0, wmin = X86_PMC_IDX_MAX, wmax = 0; i < n; i++) {
109717de
PZ
983 c = cpuc->event_constraint[i];
984
f80deefa
PZ
985 /*
986 * Previously scheduled events should have a cached constraint,
987 * while new events should not have one.
988 */
989 WARN_ON_ONCE((c && i >= n0) || (!c && i < n0));
990
109717de
PZ
991 /*
992 * Request constraints for new events; or for those events that
993 * have a dynamic constraint -- for those the constraint can
994 * change due to external factors (sibling state, allow_tfa).
995 */
996 if (!c || (c->flags & PERF_X86_EVENT_DYNAMIC)) {
7c9903c9 997 c = static_call(x86_pmu_get_event_constraints)(cpuc, i, cpuc->event_list[i]);
109717de
PZ
998 cpuc->event_constraint[i] = c;
999 }
43b45780 1000
1e2ad28f
RR
1001 wmin = min(wmin, c->weight);
1002 wmax = max(wmax, c->weight);
1da53e02
SE
1003 }
1004
8113070d
SE
1005 /*
1006 * fastpath, try to reuse previous register
1007 */
c933c1a6 1008 for (i = 0; i < n; i++) {
57388912
KP
1009 u64 mask;
1010
8113070d 1011 hwc = &cpuc->event_list[i]->hw;
b371b594 1012 c = cpuc->event_constraint[i];
8113070d
SE
1013
1014 /* never assigned */
1015 if (hwc->idx == -1)
1016 break;
1017
1018 /* constraint still honored */
63b14649 1019 if (!test_bit(hwc->idx, c->idxmsk))
8113070d
SE
1020 break;
1021
57388912
KP
1022 mask = BIT_ULL(hwc->idx);
1023 if (is_counter_pair(hwc))
1024 mask |= mask << 1;
1025
8113070d 1026 /* not already used */
57388912 1027 if (used_mask & mask)
8113070d
SE
1028 break;
1029
57388912
KP
1030 used_mask |= mask;
1031
8113070d
SE
1032 if (assign)
1033 assign[i] = hwc->idx;
1034 }
8113070d 1035
1e2ad28f 1036 /* slow path */
b371b594 1037 if (i != n) {
d4b294bf 1038 int gpmax = num_counters;
cc1790cf
PZ
1039
1040 /*
1041 * Do not allow scheduling of more than half the available
1042 * generic counters.
1043 *
1044 * This helps avoid counter starvation of sibling thread by
1045 * ensuring at most half the counters cannot be in exclusive
1046 * mode. There is no designated counters for the limits. Any
1047 * N/2 counters can be used. This helps with events with
1048 * specific counter constraints.
1049 */
1050 if (is_ht_workaround_enabled() && !cpuc->is_fake &&
1051 READ_ONCE(cpuc->excl_cntrs->exclusive_present))
1052 gpmax /= 2;
1053
57388912
KP
1054 /*
1055 * Reduce the amount of available counters to allow fitting
1056 * the extra Merge events needed by large increment events.
1057 */
1058 if (x86_pmu.flags & PMU_FL_PAIR) {
d4b294bf 1059 gpmax = num_counters - cpuc->n_pair;
57388912
KP
1060 WARN_ON(gpmax <= 0);
1061 }
1062
b371b594 1063 unsched = perf_assign_events(cpuc->event_constraint, n, wmin,
cc1790cf 1064 wmax, gpmax, assign);
b371b594 1065 }
8113070d 1066
2f7f73a5 1067 /*
e979121b
MD
1068 * In case of success (unsched = 0), mark events as committed,
1069 * so we do not put_constraint() in case new events are added
1070 * and fail to be scheduled
1071 *
1072 * We invoke the lower level commit callback to lock the resource
1073 *
1074 * We do not need to do all of this in case we are called to
1075 * validate an event group (assign == NULL)
2f7f73a5 1076 */
e979121b 1077 if (!unsched && assign) {
2f7f73a5
SE
1078 for (i = 0; i < n; i++) {
1079 e = cpuc->event_list[i];
7c9903c9 1080 static_call_cond(x86_pmu_commit_scheduling)(cpuc, i, assign[i]);
2f7f73a5 1081 }
8736e548 1082 } else {
f80deefa 1083 for (i = n0; i < n; i++) {
2f7f73a5 1084 e = cpuc->event_list[i];
2f7f73a5 1085
e979121b
MD
1086 /*
1087 * release events that failed scheduling
1088 */
7c9903c9 1089 static_call_cond(x86_pmu_put_event_constraints)(cpuc, e);
2c9651c3
PZ
1090
1091 cpuc->event_constraint[i] = NULL;
1da53e02
SE
1092 }
1093 }
c5362c0c 1094
7c9903c9 1095 static_call_cond(x86_pmu_stop_scheduling)(cpuc);
c5362c0c 1096
e979121b 1097 return unsched ? -EINVAL : 0;
1da53e02
SE
1098}
1099
7b2c05a1
KL
1100static int add_nr_metric_event(struct cpu_hw_events *cpuc,
1101 struct perf_event *event)
1102{
1103 if (is_metric_event(event)) {
1104 if (cpuc->n_metric == INTEL_TD_METRIC_NUM)
1105 return -EINVAL;
1106 cpuc->n_metric++;
3dbde695 1107 cpuc->n_txn_metric++;
7b2c05a1
KL
1108 }
1109
1110 return 0;
1111}
1112
1113static void del_nr_metric_event(struct cpu_hw_events *cpuc,
1114 struct perf_event *event)
1115{
1116 if (is_metric_event(event))
1117 cpuc->n_metric--;
1118}
1119
1120static int collect_event(struct cpu_hw_events *cpuc, struct perf_event *event,
1121 int max_count, int n)
1122{
d0946a88 1123 union perf_capabilities intel_cap = hybrid(cpuc->pmu, intel_cap);
7b2c05a1 1124
d0946a88 1125 if (intel_cap.perf_metrics && add_nr_metric_event(cpuc, event))
7b2c05a1
KL
1126 return -EINVAL;
1127
1128 if (n >= max_count + cpuc->n_metric)
1129 return -EINVAL;
1130
1131 cpuc->event_list[n] = event;
871a93b0 1132 if (is_counter_pair(&event->hw)) {
7b2c05a1 1133 cpuc->n_pair++;
871a93b0
PZ
1134 cpuc->n_txn_pair++;
1135 }
7b2c05a1
KL
1136
1137 return 0;
1138}
1139
1da53e02
SE
1140/*
1141 * dogrp: true if must collect siblings events (group)
1142 * returns total number of events and error code
1143 */
1144static int collect_events(struct cpu_hw_events *cpuc, struct perf_event *leader, bool dogrp)
1145{
d4b294bf
KL
1146 int num_counters = hybrid(cpuc->pmu, num_counters);
1147 int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed);
1da53e02
SE
1148 struct perf_event *event;
1149 int n, max_count;
1150
d4b294bf 1151 max_count = num_counters + num_counters_fixed;
1da53e02
SE
1152
1153 /* current number of events already accepted */
1154 n = cpuc->n_events;
42880f72
AS
1155 if (!cpuc->n_events)
1156 cpuc->pebs_output = 0;
1157
1158 if (!cpuc->is_fake && leader->attr.precise_ip) {
1159 /*
1160 * For PEBS->PT, if !aux_event, the group leader (PT) went
1161 * away, the group was broken down and this singleton event
1162 * can't schedule any more.
1163 */
1164 if (is_pebs_pt(leader) && !leader->aux_event)
1165 return -EINVAL;
1166
1167 /*
1168 * pebs_output: 0: no PEBS so far, 1: PT, 2: DS
1169 */
1170 if (cpuc->pebs_output &&
1171 cpuc->pebs_output != is_pebs_pt(leader) + 1)
1172 return -EINVAL;
1173
1174 cpuc->pebs_output = is_pebs_pt(leader) + 1;
1175 }
1da53e02
SE
1176
1177 if (is_x86_event(leader)) {
7b2c05a1 1178 if (collect_event(cpuc, leader, max_count, n))
aa2bc1ad 1179 return -EINVAL;
1da53e02
SE
1180 n++;
1181 }
7b2c05a1 1182
1da53e02
SE
1183 if (!dogrp)
1184 return n;
1185
edb39592 1186 for_each_sibling_event(event, leader) {
7b2c05a1 1187 if (!is_x86_event(event) || event->state <= PERF_EVENT_STATE_OFF)
1da53e02
SE
1188 continue;
1189
7b2c05a1 1190 if (collect_event(cpuc, event, max_count, n))
aa2bc1ad 1191 return -EINVAL;
1da53e02 1192
1da53e02
SE
1193 n++;
1194 }
1195 return n;
1196}
1197
1da53e02 1198static inline void x86_assign_hw_event(struct perf_event *event,
447a194b 1199 struct cpu_hw_events *cpuc, int i)
1da53e02 1200{
447a194b 1201 struct hw_perf_event *hwc = &event->hw;
027440b5 1202 int idx;
447a194b 1203
027440b5 1204 idx = hwc->idx = cpuc->assign[i];
447a194b
SE
1205 hwc->last_cpu = smp_processor_id();
1206 hwc->last_tag = ++cpuc->tags[i];
1da53e02 1207
027440b5
LX
1208 switch (hwc->idx) {
1209 case INTEL_PMC_IDX_FIXED_BTS:
097e4311 1210 case INTEL_PMC_IDX_FIXED_VLBR:
1da53e02
SE
1211 hwc->config_base = 0;
1212 hwc->event_base = 0;
027440b5
LX
1213 break;
1214
7b2c05a1
KL
1215 case INTEL_PMC_IDX_METRIC_BASE ... INTEL_PMC_IDX_METRIC_END:
1216 /* All the metric events are mapped onto the fixed counter 3. */
1217 idx = INTEL_PMC_IDX_FIXED_SLOTS;
b6459575 1218 fallthrough;
027440b5 1219 case INTEL_PMC_IDX_FIXED ... INTEL_PMC_IDX_FIXED_BTS-1:
1da53e02 1220 hwc->config_base = MSR_ARCH_PERFMON_FIXED_CTR_CTRL;
027440b5
LX
1221 hwc->event_base = MSR_ARCH_PERFMON_FIXED_CTR0 +
1222 (idx - INTEL_PMC_IDX_FIXED);
0e2e45e2
KL
1223 hwc->event_base_rdpmc = (idx - INTEL_PMC_IDX_FIXED) |
1224 INTEL_PMC_FIXED_RDPMC_BASE;
027440b5
LX
1225 break;
1226
1227 default:
73d6e522
RR
1228 hwc->config_base = x86_pmu_config_addr(hwc->idx);
1229 hwc->event_base = x86_pmu_event_addr(hwc->idx);
0fbdad07 1230 hwc->event_base_rdpmc = x86_pmu_rdpmc_index(hwc->idx);
027440b5 1231 break;
1da53e02
SE
1232 }
1233}
1234
1182a495
RC
1235/**
1236 * x86_perf_rdpmc_index - Return PMC counter used for event
1237 * @event: the perf_event to which the PMC counter was assigned
1238 *
1239 * The counter assigned to this performance event may change if interrupts
1240 * are enabled. This counter should thus never be used while interrupts are
1241 * enabled. Before this function is used to obtain the assigned counter the
1242 * event should be checked for validity using, for example,
1243 * perf_event_read_local(), within the same interrupt disabled section in
1244 * which this counter is planned to be used.
1245 *
1246 * Return: The index of the performance monitoring counter assigned to
1247 * @perf_event.
1248 */
1249int x86_perf_rdpmc_index(struct perf_event *event)
1250{
1251 lockdep_assert_irqs_disabled();
1252
1253 return event->hw.event_base_rdpmc;
1254}
1255
447a194b
SE
1256static inline int match_prev_assignment(struct hw_perf_event *hwc,
1257 struct cpu_hw_events *cpuc,
1258 int i)
1259{
1260 return hwc->idx == cpuc->assign[i] &&
1261 hwc->last_cpu == smp_processor_id() &&
1262 hwc->last_tag == cpuc->tags[i];
1263}
1264
a4eaf7f1 1265static void x86_pmu_start(struct perf_event *event, int flags);
2e841873 1266
a4eaf7f1 1267static void x86_pmu_enable(struct pmu *pmu)
ee06094f 1268{
89cbc767 1269 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02
SE
1270 struct perf_event *event;
1271 struct hw_perf_event *hwc;
11164cd4 1272 int i, added = cpuc->n_added;
1da53e02 1273
85cf9dba 1274 if (!x86_pmu_initialized())
2b9ff0db 1275 return;
1a6e21f7
PZ
1276
1277 if (cpuc->enabled)
1278 return;
1279
1da53e02 1280 if (cpuc->n_added) {
19925ce7 1281 int n_running = cpuc->n_events - cpuc->n_added;
1da53e02
SE
1282 /*
1283 * apply assignment obtained either from
1284 * hw_perf_group_sched_in() or x86_pmu_enable()
1285 *
1286 * step1: save events moving to new counters
1da53e02 1287 */
19925ce7 1288 for (i = 0; i < n_running; i++) {
1da53e02
SE
1289 event = cpuc->event_list[i];
1290 hwc = &event->hw;
1291
447a194b
SE
1292 /*
1293 * we can avoid reprogramming counter if:
1294 * - assigned same counter as last time
1295 * - running on same CPU as last time
1296 * - no other event has used the counter since
1297 */
1298 if (hwc->idx == -1 ||
1299 match_prev_assignment(hwc, cpuc, i))
1da53e02
SE
1300 continue;
1301
a4eaf7f1
PZ
1302 /*
1303 * Ensure we don't accidentally enable a stopped
1304 * counter simply because we rescheduled.
1305 */
1306 if (hwc->state & PERF_HES_STOPPED)
1307 hwc->state |= PERF_HES_ARCH;
1308
1309 x86_pmu_stop(event, PERF_EF_UPDATE);
1da53e02
SE
1310 }
1311
c347a2f1
PZ
1312 /*
1313 * step2: reprogram moved events into new counters
1314 */
1da53e02 1315 for (i = 0; i < cpuc->n_events; i++) {
1da53e02
SE
1316 event = cpuc->event_list[i];
1317 hwc = &event->hw;
1318
45e16a68 1319 if (!match_prev_assignment(hwc, cpuc, i))
447a194b 1320 x86_assign_hw_event(event, cpuc, i);
45e16a68
PZ
1321 else if (i < n_running)
1322 continue;
1da53e02 1323
a4eaf7f1
PZ
1324 if (hwc->state & PERF_HES_ARCH)
1325 continue;
1326
1327 x86_pmu_start(event, PERF_EF_RELOAD);
1da53e02
SE
1328 }
1329 cpuc->n_added = 0;
1330 perf_events_lapic_init();
1331 }
1a6e21f7
PZ
1332
1333 cpuc->enabled = 1;
1334 barrier();
1335
7c9903c9 1336 static_call(x86_pmu_enable_all)(added);
ee06094f 1337}
ee06094f 1338
245b2e70 1339static DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
241771ef 1340
ee06094f
IM
1341/*
1342 * Set the next IRQ period, based on the hwc->period_left value.
cdd6c482 1343 * To be called with the event disabled in hw:
ee06094f 1344 */
de0428a7 1345int x86_perf_event_set_period(struct perf_event *event)
241771ef 1346{
07088edb 1347 struct hw_perf_event *hwc = &event->hw;
e7850595 1348 s64 left = local64_read(&hwc->period_left);
e4abb5d4 1349 s64 period = hwc->sample_period;
7645a24c 1350 int ret = 0, idx = hwc->idx;
ee06094f 1351
027440b5 1352 if (unlikely(!hwc->event_base))
30dd568c
MM
1353 return 0;
1354
7b2c05a1
KL
1355 if (unlikely(is_topdown_count(event)) &&
1356 x86_pmu.set_topdown_event_period)
1357 return x86_pmu.set_topdown_event_period(event);
1358
ee06094f 1359 /*
af901ca1 1360 * If we are way outside a reasonable range then just skip forward:
ee06094f
IM
1361 */
1362 if (unlikely(left <= -period)) {
1363 left = period;
e7850595 1364 local64_set(&hwc->period_left, left);
9e350de3 1365 hwc->last_period = period;
e4abb5d4 1366 ret = 1;
ee06094f
IM
1367 }
1368
1369 if (unlikely(left <= 0)) {
1370 left += period;
e7850595 1371 local64_set(&hwc->period_left, left);
9e350de3 1372 hwc->last_period = period;
e4abb5d4 1373 ret = 1;
ee06094f 1374 }
1c80f4b5 1375 /*
dfc65094 1376 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1c80f4b5
IM
1377 */
1378 if (unlikely(left < 2))
1379 left = 2;
241771ef 1380
e4abb5d4
PZ
1381 if (left > x86_pmu.max_period)
1382 left = x86_pmu.max_period;
1383
294fe0f5
AK
1384 if (x86_pmu.limit_period)
1385 left = x86_pmu.limit_period(event, left);
1386
245b2e70 1387 per_cpu(pmc_prev_left[idx], smp_processor_id()) = left;
ee06094f 1388
d31fc13f
KL
1389 /*
1390 * The hw event starts counting from this event offset,
1391 * mark it to be able to extra future deltas:
1392 */
1393 local64_set(&hwc->prev_count, (u64)-left);
ee06094f 1394
d31fc13f 1395 wrmsrl(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
68aa00ac 1396
57388912 1397 /*
26e52558 1398 * Sign extend the Merge event counter's upper 16 bits since
57388912
KP
1399 * we currently declare a 48-bit counter width
1400 */
1401 if (is_counter_pair(hwc))
26e52558 1402 wrmsrl(x86_pmu_event_addr(idx + 1), 0xffff);
57388912 1403
68aa00ac
CG
1404 /*
1405 * Due to erratum on certan cpu we need
1406 * a second write to be sure the register
1407 * is updated properly
1408 */
1409 if (x86_pmu.perfctr_second_write) {
73d6e522 1410 wrmsrl(hwc->event_base,
948b1bb8 1411 (u64)(-left) & x86_pmu.cntval_mask);
68aa00ac 1412 }
e4abb5d4 1413
cdd6c482 1414 perf_event_update_userpage(event);
194002b2 1415
e4abb5d4 1416 return ret;
2f18d1e8
IM
1417}
1418
de0428a7 1419void x86_pmu_enable_event(struct perf_event *event)
7c90cc45 1420{
0a3aee0d 1421 if (__this_cpu_read(cpu_hw_events.enabled))
31fa58af
RR
1422 __x86_pmu_enable_event(&event->hw,
1423 ARCH_PERFMON_EVENTSEL_ENABLE);
241771ef
IM
1424}
1425
b690081d 1426/*
a4eaf7f1 1427 * Add a single event to the PMU.
1da53e02
SE
1428 *
1429 * The event is added to the group of enabled events
77d76032 1430 * but only if it can be scheduled with existing events.
fe9081cc 1431 */
a4eaf7f1 1432static int x86_pmu_add(struct perf_event *event, int flags)
fe9081cc 1433{
89cbc767 1434 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1da53e02
SE
1435 struct hw_perf_event *hwc;
1436 int assign[X86_PMC_IDX_MAX];
1437 int n, n0, ret;
fe9081cc 1438
1da53e02 1439 hwc = &event->hw;
fe9081cc 1440
1da53e02 1441 n0 = cpuc->n_events;
24cd7f54
PZ
1442 ret = n = collect_events(cpuc, event, false);
1443 if (ret < 0)
1444 goto out;
53b441a5 1445
a4eaf7f1
PZ
1446 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1447 if (!(flags & PERF_EF_START))
1448 hwc->state |= PERF_HES_ARCH;
1449
4d1c52b0
LM
1450 /*
1451 * If group events scheduling transaction was started,
0d2eb44f 1452 * skip the schedulability test here, it will be performed
c347a2f1 1453 * at commit time (->commit_txn) as a whole.
68f7082f
PZ
1454 *
1455 * If commit fails, we'll call ->del() on all events
1456 * for which ->add() was called.
4d1c52b0 1457 */
8f3e5684 1458 if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
24cd7f54 1459 goto done_collect;
4d1c52b0 1460
7c9903c9 1461 ret = static_call(x86_pmu_schedule_events)(cpuc, n, assign);
1da53e02 1462 if (ret)
24cd7f54 1463 goto out;
1da53e02
SE
1464 /*
1465 * copy new assignment, now we know it is possible
1466 * will be used by hw_perf_enable()
1467 */
1468 memcpy(cpuc->assign, assign, n*sizeof(int));
7e2ae347 1469
24cd7f54 1470done_collect:
c347a2f1
PZ
1471 /*
1472 * Commit the collect_events() state. See x86_pmu_del() and
1473 * x86_pmu_*_txn().
1474 */
1da53e02 1475 cpuc->n_events = n;
356e1f2e 1476 cpuc->n_added += n - n0;
90151c35 1477 cpuc->n_txn += n - n0;
95cdd2e7 1478
7c9903c9
PZ
1479 /*
1480 * This is before x86_pmu_enable() will call x86_pmu_start(),
1481 * so we enable LBRs before an event needs them etc..
1482 */
1483 static_call_cond(x86_pmu_add)(event);
68f7082f 1484
24cd7f54
PZ
1485 ret = 0;
1486out:
24cd7f54 1487 return ret;
241771ef
IM
1488}
1489
a4eaf7f1 1490static void x86_pmu_start(struct perf_event *event, int flags)
d76a0812 1491{
89cbc767 1492 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
c08053e6
PZ
1493 int idx = event->hw.idx;
1494
a4eaf7f1
PZ
1495 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1496 return;
1497
1498 if (WARN_ON_ONCE(idx == -1))
1499 return;
1500
1501 if (flags & PERF_EF_RELOAD) {
1502 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1503 x86_perf_event_set_period(event);
1504 }
1505
1506 event->hw.state = 0;
d76a0812 1507
c08053e6
PZ
1508 cpuc->events[idx] = event;
1509 __set_bit(idx, cpuc->active_mask);
7c9903c9 1510 static_call(x86_pmu_enable)(event);
c08053e6 1511 perf_event_update_userpage(event);
a78ac325
PZ
1512}
1513
cdd6c482 1514void perf_event_print_debug(void)
241771ef 1515{
2f18d1e8 1516 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
da3e606d 1517 u64 pebs, debugctl;
d4b294bf
KL
1518 int cpu = smp_processor_id();
1519 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1520 int num_counters = hybrid(cpuc->pmu, num_counters);
1521 int num_counters_fixed = hybrid(cpuc->pmu, num_counters_fixed);
5bb9efe3 1522 unsigned long flags;
d4b294bf 1523 int idx;
1e125676 1524
d4b294bf 1525 if (!num_counters)
1e125676 1526 return;
241771ef 1527
5bb9efe3 1528 local_irq_save(flags);
241771ef 1529
faa28ae0 1530 if (x86_pmu.version >= 2) {
a1ef58f4
JSR
1531 rdmsrl(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1532 rdmsrl(MSR_CORE_PERF_GLOBAL_STATUS, status);
1533 rdmsrl(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1534 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1535
1536 pr_info("\n");
1537 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1538 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1539 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1540 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
15fde110
AK
1541 if (x86_pmu.pebs_constraints) {
1542 rdmsrl(MSR_IA32_PEBS_ENABLE, pebs);
1543 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1544 }
da3e606d
AK
1545 if (x86_pmu.lbr_nr) {
1546 rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctl);
1547 pr_info("CPU#%d: debugctl: %016llx\n", cpu, debugctl);
1548 }
f87ad35d 1549 }
7645a24c 1550 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
241771ef 1551
d4b294bf 1552 for (idx = 0; idx < num_counters; idx++) {
41bf4989
RR
1553 rdmsrl(x86_pmu_config_addr(idx), pmc_ctrl);
1554 rdmsrl(x86_pmu_event_addr(idx), pmc_count);
241771ef 1555
245b2e70 1556 prev_left = per_cpu(pmc_prev_left[idx], cpu);
241771ef 1557
a1ef58f4 1558 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
241771ef 1559 cpu, idx, pmc_ctrl);
a1ef58f4 1560 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
241771ef 1561 cpu, idx, pmc_count);
a1ef58f4 1562 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
ee06094f 1563 cpu, idx, prev_left);
241771ef 1564 }
d4b294bf 1565 for (idx = 0; idx < num_counters_fixed; idx++) {
fc4b8fca 1566 if (fixed_counter_disabled(idx, cpuc->pmu))
32451614 1567 continue;
2f18d1e8
IM
1568 rdmsrl(MSR_ARCH_PERFMON_FIXED_CTR0 + idx, pmc_count);
1569
a1ef58f4 1570 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
2f18d1e8
IM
1571 cpu, idx, pmc_count);
1572 }
5bb9efe3 1573 local_irq_restore(flags);
241771ef
IM
1574}
1575
de0428a7 1576void x86_pmu_stop(struct perf_event *event, int flags)
241771ef 1577{
89cbc767 1578 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
cdd6c482 1579 struct hw_perf_event *hwc = &event->hw;
241771ef 1580
3966c3fe 1581 if (test_bit(hwc->idx, cpuc->active_mask)) {
7c9903c9 1582 static_call(x86_pmu_disable)(event);
3966c3fe 1583 __clear_bit(hwc->idx, cpuc->active_mask);
a4eaf7f1
PZ
1584 cpuc->events[hwc->idx] = NULL;
1585 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1586 hwc->state |= PERF_HES_STOPPED;
1587 }
30dd568c 1588
a4eaf7f1
PZ
1589 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1590 /*
1591 * Drain the remaining delta count out of a event
1592 * that we are disabling:
1593 */
1594 x86_perf_event_update(event);
1595 hwc->state |= PERF_HES_UPTODATE;
1596 }
2e841873
PZ
1597}
1598
a4eaf7f1 1599static void x86_pmu_del(struct perf_event *event, int flags)
2e841873 1600{
89cbc767 1601 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
d0946a88 1602 union perf_capabilities intel_cap = hybrid(cpuc->pmu, intel_cap);
2e841873
PZ
1603 int i;
1604
90151c35 1605 /*
68f7082f 1606 * If we're called during a txn, we only need to undo x86_pmu.add.
90151c35
SE
1607 * The events never got scheduled and ->cancel_txn will truncate
1608 * the event_list.
c347a2f1
PZ
1609 *
1610 * XXX assumes any ->del() called during a TXN will only be on
1611 * an event added during that same TXN.
90151c35 1612 */
8f3e5684 1613 if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
68f7082f 1614 goto do_del;
90151c35 1615
c347a2f1
PZ
1616 /*
1617 * Not a TXN, therefore cleanup properly.
1618 */
a4eaf7f1 1619 x86_pmu_stop(event, PERF_EF_UPDATE);
194002b2 1620
1da53e02 1621 for (i = 0; i < cpuc->n_events; i++) {
c347a2f1
PZ
1622 if (event == cpuc->event_list[i])
1623 break;
1624 }
1da53e02 1625
c347a2f1
PZ
1626 if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1627 return;
26e61e89 1628
c347a2f1
PZ
1629 /* If we have a newly added event; make sure to decrease n_added. */
1630 if (i >= cpuc->n_events - cpuc->n_added)
1631 --cpuc->n_added;
1da53e02 1632
7c9903c9 1633 static_call_cond(x86_pmu_put_event_constraints)(cpuc, event);
c347a2f1
PZ
1634
1635 /* Delete the array entry. */
b371b594 1636 while (++i < cpuc->n_events) {
c347a2f1 1637 cpuc->event_list[i-1] = cpuc->event_list[i];
b371b594
PZ
1638 cpuc->event_constraint[i-1] = cpuc->event_constraint[i];
1639 }
2c9651c3 1640 cpuc->event_constraint[i-1] = NULL;
c347a2f1 1641 --cpuc->n_events;
d0946a88 1642 if (intel_cap.perf_metrics)
7b2c05a1 1643 del_nr_metric_event(cpuc, event);
1da53e02 1644
cdd6c482 1645 perf_event_update_userpage(event);
68f7082f
PZ
1646
1647do_del:
7c9903c9
PZ
1648
1649 /*
1650 * This is after x86_pmu_stop(); so we disable LBRs after any
1651 * event can need them etc..
1652 */
1653 static_call_cond(x86_pmu_del)(event);
241771ef
IM
1654}
1655
de0428a7 1656int x86_pmu_handle_irq(struct pt_regs *regs)
a29aa8a7 1657{
df1a132b 1658 struct perf_sample_data data;
cdd6c482
IM
1659 struct cpu_hw_events *cpuc;
1660 struct perf_event *event;
11d1578f 1661 int idx, handled = 0;
9029a5e3
IM
1662 u64 val;
1663
89cbc767 1664 cpuc = this_cpu_ptr(&cpu_hw_events);
962bf7a6 1665
2bce5dac
DZ
1666 /*
1667 * Some chipsets need to unmask the LVTPC in a particular spot
1668 * inside the nmi handler. As a result, the unmasking was pushed
1669 * into all the nmi handlers.
1670 *
1671 * This generic handler doesn't seem to have any issues where the
1672 * unmasking occurs so it was left at the top.
1673 */
1674 apic_write(APIC_LVTPC, APIC_DM_NMI);
1675
948b1bb8 1676 for (idx = 0; idx < x86_pmu.num_counters; idx++) {
3966c3fe 1677 if (!test_bit(idx, cpuc->active_mask))
a29aa8a7 1678 continue;
962bf7a6 1679
cdd6c482 1680 event = cpuc->events[idx];
a4016a79 1681
cc2ad4ba 1682 val = x86_perf_event_update(event);
948b1bb8 1683 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
48e22d56 1684 continue;
962bf7a6 1685
9e350de3 1686 /*
cdd6c482 1687 * event overflow
9e350de3 1688 */
4177c42a 1689 handled++;
fd0d000b 1690 perf_sample_data_init(&data, 0, event->hw.last_period);
9e350de3 1691
07088edb 1692 if (!x86_perf_event_set_period(event))
e4abb5d4
PZ
1693 continue;
1694
a8b0ca17 1695 if (perf_event_overflow(event, &data, regs))
a4eaf7f1 1696 x86_pmu_stop(event, 0);
a29aa8a7 1697 }
962bf7a6 1698
9e350de3
PZ
1699 if (handled)
1700 inc_irq_stat(apic_perf_irqs);
1701
a29aa8a7
RR
1702 return handled;
1703}
39d81eab 1704
cdd6c482 1705void perf_events_lapic_init(void)
241771ef 1706{
04da8a43 1707 if (!x86_pmu.apic || !x86_pmu_initialized())
241771ef 1708 return;
85cf9dba 1709
241771ef 1710 /*
c323d95f 1711 * Always use NMI for PMU
241771ef 1712 */
c323d95f 1713 apic_write(APIC_LVTPC, APIC_DM_NMI);
241771ef
IM
1714}
1715
9326638c 1716static int
9c48f1c6 1717perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
241771ef 1718{
14c63f17
DH
1719 u64 start_clock;
1720 u64 finish_clock;
e8a923cc 1721 int ret;
14c63f17 1722
1b7b938f
AS
1723 /*
1724 * All PMUs/events that share this PMI handler should make sure to
1725 * increment active_events for their events.
1726 */
cdd6c482 1727 if (!atomic_read(&active_events))
9c48f1c6 1728 return NMI_DONE;
4177c42a 1729
e8a923cc 1730 start_clock = sched_clock();
7c9903c9 1731 ret = static_call(x86_pmu_handle_irq)(regs);
e8a923cc 1732 finish_clock = sched_clock();
14c63f17
DH
1733
1734 perf_sample_event_took(finish_clock - start_clock);
1735
1736 return ret;
241771ef 1737}
9326638c 1738NOKPROBE_SYMBOL(perf_event_nmi_handler);
241771ef 1739
de0428a7
KW
1740struct event_constraint emptyconstraint;
1741struct event_constraint unconstrained;
f87ad35d 1742
95ca792c 1743static int x86_pmu_prepare_cpu(unsigned int cpu)
3f6da390 1744{
7fdba1ca 1745 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
95ca792c 1746 int i;
3f6da390 1747
95ca792c
TG
1748 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++)
1749 cpuc->kfree_on_online[i] = NULL;
1750 if (x86_pmu.cpu_prepare)
1751 return x86_pmu.cpu_prepare(cpu);
1752 return 0;
1753}
7fdba1ca 1754
95ca792c
TG
1755static int x86_pmu_dead_cpu(unsigned int cpu)
1756{
1757 if (x86_pmu.cpu_dead)
1758 x86_pmu.cpu_dead(cpu);
1759 return 0;
1760}
3f6da390 1761
95ca792c
TG
1762static int x86_pmu_online_cpu(unsigned int cpu)
1763{
1764 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1765 int i;
3f6da390 1766
95ca792c
TG
1767 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++) {
1768 kfree(cpuc->kfree_on_online[i]);
1769 cpuc->kfree_on_online[i] = NULL;
3f6da390 1770 }
95ca792c
TG
1771 return 0;
1772}
3f6da390 1773
95ca792c
TG
1774static int x86_pmu_starting_cpu(unsigned int cpu)
1775{
1776 if (x86_pmu.cpu_starting)
1777 x86_pmu.cpu_starting(cpu);
1778 return 0;
1779}
1780
1781static int x86_pmu_dying_cpu(unsigned int cpu)
1782{
1783 if (x86_pmu.cpu_dying)
1784 x86_pmu.cpu_dying(cpu);
1785 return 0;
3f6da390
PZ
1786}
1787
12558038
CG
1788static void __init pmu_check_apic(void)
1789{
93984fbd 1790 if (boot_cpu_has(X86_FEATURE_APIC))
12558038
CG
1791 return;
1792
1793 x86_pmu.apic = 0;
1794 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1795 pr_info("no hardware sampling interrupt available.\n");
c184c980
VW
1796
1797 /*
1798 * If we have a PMU initialized but no APIC
1799 * interrupts, we cannot sample hardware
1800 * events (user-space has to fall back and
1801 * sample via a hrtimer based software event):
1802 */
1803 pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1804
12558038
CG
1805}
1806
2766d2ee 1807static struct attribute_group x86_pmu_format_group __ro_after_init = {
641cc938
JO
1808 .name = "format",
1809 .attrs = NULL,
1810};
1811
c7ab62bf 1812ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr, char *page)
a4747393 1813{
1e69a0ef 1814 struct perf_pmu_events_attr *pmu_attr =
a4747393 1815 container_of(attr, struct perf_pmu_events_attr, attr);
1e69a0ef
PZ
1816 u64 config = 0;
1817
1818 if (pmu_attr->id < x86_pmu.max_events)
1819 config = x86_pmu.event_map(pmu_attr->id);
a4747393 1820
3a54aaa0
SE
1821 /* string trumps id */
1822 if (pmu_attr->event_str)
1823 return sprintf(page, "%s", pmu_attr->event_str);
a4747393 1824
3a54aaa0
SE
1825 return x86_pmu.events_sysfs_show(page, config);
1826}
c7ab62bf 1827EXPORT_SYMBOL_GPL(events_sysfs_show);
a4747393 1828
fc07e9f9
AK
1829ssize_t events_ht_sysfs_show(struct device *dev, struct device_attribute *attr,
1830 char *page)
1831{
1832 struct perf_pmu_events_ht_attr *pmu_attr =
1833 container_of(attr, struct perf_pmu_events_ht_attr, attr);
1834
1835 /*
1836 * Report conditional events depending on Hyper-Threading.
1837 *
1838 * This is overly conservative as usually the HT special
1839 * handling is not needed if the other CPU thread is idle.
1840 *
1841 * Note this does not (and cannot) handle the case when thread
1842 * siblings are invisible, for example with virtualization
1843 * if they are owned by some other guest. The user tool
1844 * has to re-read when a thread sibling gets onlined later.
1845 */
1846 return sprintf(page, "%s",
1847 topology_max_smt_threads() > 1 ?
1848 pmu_attr->event_str_ht :
1849 pmu_attr->event_str_noht);
1850}
1851
a4747393
JO
1852EVENT_ATTR(cpu-cycles, CPU_CYCLES );
1853EVENT_ATTR(instructions, INSTRUCTIONS );
1854EVENT_ATTR(cache-references, CACHE_REFERENCES );
1855EVENT_ATTR(cache-misses, CACHE_MISSES );
1856EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
1857EVENT_ATTR(branch-misses, BRANCH_MISSES );
1858EVENT_ATTR(bus-cycles, BUS_CYCLES );
1859EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
1860EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
1861EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
1862
1863static struct attribute *empty_attrs;
1864
95d18aa2 1865static struct attribute *events_attr[] = {
a4747393
JO
1866 EVENT_PTR(CPU_CYCLES),
1867 EVENT_PTR(INSTRUCTIONS),
1868 EVENT_PTR(CACHE_REFERENCES),
1869 EVENT_PTR(CACHE_MISSES),
1870 EVENT_PTR(BRANCH_INSTRUCTIONS),
1871 EVENT_PTR(BRANCH_MISSES),
1872 EVENT_PTR(BUS_CYCLES),
1873 EVENT_PTR(STALLED_CYCLES_FRONTEND),
1874 EVENT_PTR(STALLED_CYCLES_BACKEND),
1875 EVENT_PTR(REF_CPU_CYCLES),
1876 NULL,
1877};
1878
3d567273
JO
1879/*
1880 * Remove all undefined events (x86_pmu.event_map(id) == 0)
1881 * out of events_attr attributes.
1882 */
1883static umode_t
1884is_visible(struct kobject *kobj, struct attribute *attr, int idx)
1885{
1886 struct perf_pmu_events_attr *pmu_attr;
1887
1e69a0ef
PZ
1888 if (idx >= x86_pmu.max_events)
1889 return 0;
1890
3d567273
JO
1891 pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr.attr);
1892 /* str trumps id */
1893 return pmu_attr->event_str || x86_pmu.event_map(idx) ? attr->mode : 0;
1894}
1895
2766d2ee 1896static struct attribute_group x86_pmu_events_group __ro_after_init = {
a4747393
JO
1897 .name = "events",
1898 .attrs = events_attr,
3d567273 1899 .is_visible = is_visible,
a4747393
JO
1900};
1901
0bf79d44 1902ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
43c032fe 1903{
43c032fe
JO
1904 u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
1905 u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
1906 bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
1907 bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
1908 bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
1909 bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
1910 ssize_t ret;
1911
1912 /*
1913 * We have whole page size to spend and just little data
1914 * to write, so we can safely use sprintf.
1915 */
1916 ret = sprintf(page, "event=0x%02llx", event);
1917
1918 if (umask)
1919 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
1920
1921 if (edge)
1922 ret += sprintf(page + ret, ",edge");
1923
1924 if (pc)
1925 ret += sprintf(page + ret, ",pc");
1926
1927 if (any)
1928 ret += sprintf(page + ret, ",any");
1929
1930 if (inv)
1931 ret += sprintf(page + ret, ",inv");
1932
1933 if (cmask)
1934 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
1935
1936 ret += sprintf(page + ret, "\n");
1937
1938 return ret;
1939}
1940
6089327f 1941static struct attribute_group x86_pmu_attr_group;
5da382eb 1942static struct attribute_group x86_pmu_caps_group;
6089327f 1943
7c9903c9
PZ
1944static void x86_pmu_static_call_update(void)
1945{
1946 static_call_update(x86_pmu_handle_irq, x86_pmu.handle_irq);
1947 static_call_update(x86_pmu_disable_all, x86_pmu.disable_all);
1948 static_call_update(x86_pmu_enable_all, x86_pmu.enable_all);
1949 static_call_update(x86_pmu_enable, x86_pmu.enable);
1950 static_call_update(x86_pmu_disable, x86_pmu.disable);
1951
1952 static_call_update(x86_pmu_add, x86_pmu.add);
1953 static_call_update(x86_pmu_del, x86_pmu.del);
1954 static_call_update(x86_pmu_read, x86_pmu.read);
1955
1956 static_call_update(x86_pmu_schedule_events, x86_pmu.schedule_events);
1957 static_call_update(x86_pmu_get_event_constraints, x86_pmu.get_event_constraints);
1958 static_call_update(x86_pmu_put_event_constraints, x86_pmu.put_event_constraints);
1959
1960 static_call_update(x86_pmu_start_scheduling, x86_pmu.start_scheduling);
1961 static_call_update(x86_pmu_commit_scheduling, x86_pmu.commit_scheduling);
1962 static_call_update(x86_pmu_stop_scheduling, x86_pmu.stop_scheduling);
1963
1964 static_call_update(x86_pmu_sched_task, x86_pmu.sched_task);
1965 static_call_update(x86_pmu_swap_task_ctx, x86_pmu.swap_task_ctx);
1966
1967 static_call_update(x86_pmu_drain_pebs, x86_pmu.drain_pebs);
1968 static_call_update(x86_pmu_pebs_aliases, x86_pmu.pebs_aliases);
abd562df
LX
1969
1970 static_call_update(x86_pmu_guest_get_msrs, x86_pmu.guest_get_msrs);
7c9903c9
PZ
1971}
1972
1973static void _x86_pmu_read(struct perf_event *event)
1974{
1975 x86_perf_event_update(event);
1976}
1977
dda99116 1978static int __init init_hw_perf_events(void)
b56a3802 1979{
c1d6f42f 1980 struct x86_pmu_quirk *quirk;
72eae04d
RR
1981 int err;
1982
cdd6c482 1983 pr_info("Performance Events: ");
1123e3ad 1984
b56a3802
JSR
1985 switch (boot_cpu_data.x86_vendor) {
1986 case X86_VENDOR_INTEL:
72eae04d 1987 err = intel_pmu_init();
b56a3802 1988 break;
f87ad35d 1989 case X86_VENDOR_AMD:
72eae04d 1990 err = amd_pmu_init();
f87ad35d 1991 break;
6d0ef316
PW
1992 case X86_VENDOR_HYGON:
1993 err = amd_pmu_init();
1994 x86_pmu.name = "HYGON";
1995 break;
3a4ac121
C
1996 case X86_VENDOR_ZHAOXIN:
1997 case X86_VENDOR_CENTAUR:
1998 err = zhaoxin_pmu_init();
1999 break;
4138960a 2000 default:
8a3da6c7 2001 err = -ENOTSUPP;
b56a3802 2002 }
1123e3ad 2003 if (err != 0) {
cdd6c482 2004 pr_cont("no PMU driver, software events only.\n");
004417a6 2005 return 0;
1123e3ad 2006 }
b56a3802 2007
12558038
CG
2008 pmu_check_apic();
2009
33c6d6a7 2010 /* sanity check that the hardware exists or is emulated */
fc4b8fca 2011 if (!check_hw_exists(&pmu, x86_pmu.num_counters, x86_pmu.num_counters_fixed))
004417a6 2012 return 0;
33c6d6a7 2013
1123e3ad 2014 pr_cont("%s PMU driver.\n", x86_pmu.name);
faa28ae0 2015
e97df763
PZ
2016 x86_pmu.attr_rdpmc = 1; /* enable userspace RDPMC usage by default */
2017
c1d6f42f
PZ
2018 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
2019 quirk->func();
3c44780b 2020
a1eac7ac
RR
2021 if (!x86_pmu.intel_ctrl)
2022 x86_pmu.intel_ctrl = (1 << x86_pmu.num_counters) - 1;
241771ef 2023
cdd6c482 2024 perf_events_lapic_init();
9c48f1c6 2025 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
1123e3ad 2026
63b14649 2027 unconstrained = (struct event_constraint)
948b1bb8 2028 __EVENT_CONSTRAINT(0, (1ULL << x86_pmu.num_counters) - 1,
9fac2cf3 2029 0, x86_pmu.num_counters, 0, 0);
63b14649 2030
641cc938 2031 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
0c9d42ed 2032
a4747393
JO
2033 if (!x86_pmu.events_sysfs_show)
2034 x86_pmu_events_group.attrs = &empty_attrs;
1a6461b1 2035
baa0c833 2036 pmu.attr_update = x86_pmu.attr_update;
6089327f 2037
57c0c15b 2038 pr_info("... version: %d\n", x86_pmu.version);
948b1bb8
RR
2039 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
2040 pr_info("... generic registers: %d\n", x86_pmu.num_counters);
2041 pr_info("... value mask: %016Lx\n", x86_pmu.cntval_mask);
57c0c15b 2042 pr_info("... max period: %016Lx\n", x86_pmu.max_period);
32451614
KL
2043 pr_info("... fixed-purpose events: %lu\n",
2044 hweight64((((1ULL << x86_pmu.num_counters_fixed) - 1)
2045 << INTEL_PMC_IDX_FIXED) & x86_pmu.intel_ctrl));
d6dc0b4e 2046 pr_info("... event mask: %016Lx\n", x86_pmu.intel_ctrl);
3f6da390 2047
7c9903c9
PZ
2048 if (!x86_pmu.read)
2049 x86_pmu.read = _x86_pmu_read;
2050
abd562df 2051 if (!x86_pmu.guest_get_msrs)
c8e2fe13 2052 x86_pmu.guest_get_msrs = (void *)&__static_call_return0;
abd562df 2053
7c9903c9
PZ
2054 x86_pmu_static_call_update();
2055
95ca792c
TG
2056 /*
2057 * Install callbacks. Core will call them for each online
2058 * cpu.
2059 */
73c1b41e 2060 err = cpuhp_setup_state(CPUHP_PERF_X86_PREPARE, "perf/x86:prepare",
95ca792c
TG
2061 x86_pmu_prepare_cpu, x86_pmu_dead_cpu);
2062 if (err)
2063 return err;
2064
2065 err = cpuhp_setup_state(CPUHP_AP_PERF_X86_STARTING,
73c1b41e 2066 "perf/x86:starting", x86_pmu_starting_cpu,
95ca792c
TG
2067 x86_pmu_dying_cpu);
2068 if (err)
2069 goto out;
2070
73c1b41e 2071 err = cpuhp_setup_state(CPUHP_AP_PERF_X86_ONLINE, "perf/x86:online",
95ca792c
TG
2072 x86_pmu_online_cpu, NULL);
2073 if (err)
2074 goto out1;
2075
2076 err = perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
2077 if (err)
2078 goto out2;
004417a6
PZ
2079
2080 return 0;
95ca792c
TG
2081
2082out2:
2083 cpuhp_remove_state(CPUHP_AP_PERF_X86_ONLINE);
2084out1:
2085 cpuhp_remove_state(CPUHP_AP_PERF_X86_STARTING);
2086out:
2087 cpuhp_remove_state(CPUHP_PERF_X86_PREPARE);
2088 return err;
241771ef 2089}
004417a6 2090early_initcall(init_hw_perf_events);
621a01ea 2091
7c9903c9 2092static void x86_pmu_read(struct perf_event *event)
ee06094f 2093{
7c9903c9 2094 static_call(x86_pmu_read)(event);
ee06094f
IM
2095}
2096
4d1c52b0
LM
2097/*
2098 * Start group events scheduling transaction
2099 * Set the flag to make pmu::enable() not perform the
2100 * schedulability test, it will be performed at commit time
fbbe0701
SB
2101 *
2102 * We only support PERF_PMU_TXN_ADD transactions. Save the
2103 * transaction flags but otherwise ignore non-PERF_PMU_TXN_ADD
2104 * transactions.
4d1c52b0 2105 */
fbbe0701 2106static void x86_pmu_start_txn(struct pmu *pmu, unsigned int txn_flags)
4d1c52b0 2107{
fbbe0701
SB
2108 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2109
2110 WARN_ON_ONCE(cpuc->txn_flags); /* txn already in flight */
2111
2112 cpuc->txn_flags = txn_flags;
2113 if (txn_flags & ~PERF_PMU_TXN_ADD)
2114 return;
2115
33696fc0 2116 perf_pmu_disable(pmu);
0a3aee0d 2117 __this_cpu_write(cpu_hw_events.n_txn, 0);
871a93b0 2118 __this_cpu_write(cpu_hw_events.n_txn_pair, 0);
3dbde695 2119 __this_cpu_write(cpu_hw_events.n_txn_metric, 0);
4d1c52b0
LM
2120}
2121
2122/*
2123 * Stop group events scheduling transaction
2124 * Clear the flag and pmu::enable() will perform the
2125 * schedulability test.
2126 */
51b0fe39 2127static void x86_pmu_cancel_txn(struct pmu *pmu)
4d1c52b0 2128{
fbbe0701
SB
2129 unsigned int txn_flags;
2130 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2131
2132 WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
2133
2134 txn_flags = cpuc->txn_flags;
2135 cpuc->txn_flags = 0;
2136 if (txn_flags & ~PERF_PMU_TXN_ADD)
2137 return;
2138
90151c35 2139 /*
c347a2f1
PZ
2140 * Truncate collected array by the number of events added in this
2141 * transaction. See x86_pmu_add() and x86_pmu_*_txn().
90151c35 2142 */
0a3aee0d
TH
2143 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
2144 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
871a93b0 2145 __this_cpu_sub(cpu_hw_events.n_pair, __this_cpu_read(cpu_hw_events.n_txn_pair));
3dbde695 2146 __this_cpu_sub(cpu_hw_events.n_metric, __this_cpu_read(cpu_hw_events.n_txn_metric));
33696fc0 2147 perf_pmu_enable(pmu);
4d1c52b0
LM
2148}
2149
2150/*
2151 * Commit group events scheduling transaction
2152 * Perform the group schedulability test as a whole
2153 * Return 0 if success
c347a2f1
PZ
2154 *
2155 * Does not cancel the transaction on failure; expects the caller to do this.
4d1c52b0 2156 */
51b0fe39 2157static int x86_pmu_commit_txn(struct pmu *pmu)
4d1c52b0 2158{
89cbc767 2159 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
4d1c52b0
LM
2160 int assign[X86_PMC_IDX_MAX];
2161 int n, ret;
2162
fbbe0701
SB
2163 WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
2164
2165 if (cpuc->txn_flags & ~PERF_PMU_TXN_ADD) {
2166 cpuc->txn_flags = 0;
2167 return 0;
2168 }
2169
4d1c52b0
LM
2170 n = cpuc->n_events;
2171
2172 if (!x86_pmu_initialized())
2173 return -EAGAIN;
2174
7c9903c9 2175 ret = static_call(x86_pmu_schedule_events)(cpuc, n, assign);
4d1c52b0
LM
2176 if (ret)
2177 return ret;
2178
2179 /*
2180 * copy new assignment, now we know it is possible
2181 * will be used by hw_perf_enable()
2182 */
2183 memcpy(cpuc->assign, assign, n*sizeof(int));
2184
fbbe0701 2185 cpuc->txn_flags = 0;
33696fc0 2186 perf_pmu_enable(pmu);
4d1c52b0
LM
2187 return 0;
2188}
cd8a38d3
SE
2189/*
2190 * a fake_cpuc is used to validate event groups. Due to
2191 * the extra reg logic, we need to also allocate a fake
2192 * per_core and per_cpu structure. Otherwise, group events
2193 * using extra reg may conflict without the kernel being
2194 * able to catch this when the last event gets added to
2195 * the group.
2196 */
2197static void free_fake_cpuc(struct cpu_hw_events *cpuc)
2198{
d01b1f96 2199 intel_cpuc_finish(cpuc);
cd8a38d3
SE
2200 kfree(cpuc);
2201}
2202
2203static struct cpu_hw_events *allocate_fake_cpuc(void)
2204{
2205 struct cpu_hw_events *cpuc;
2206 int cpu = raw_smp_processor_id();
2207
2208 cpuc = kzalloc(sizeof(*cpuc), GFP_KERNEL);
2209 if (!cpuc)
2210 return ERR_PTR(-ENOMEM);
b430f7c4 2211 cpuc->is_fake = 1;
d01b1f96
PZI
2212
2213 if (intel_cpuc_prepare(cpuc, cpu))
2214 goto error;
2215
cd8a38d3
SE
2216 return cpuc;
2217error:
2218 free_fake_cpuc(cpuc);
2219 return ERR_PTR(-ENOMEM);
2220}
4d1c52b0 2221
ca037701
PZ
2222/*
2223 * validate that we can schedule this event
2224 */
2225static int validate_event(struct perf_event *event)
2226{
2227 struct cpu_hw_events *fake_cpuc;
2228 struct event_constraint *c;
2229 int ret = 0;
2230
cd8a38d3
SE
2231 fake_cpuc = allocate_fake_cpuc();
2232 if (IS_ERR(fake_cpuc))
2233 return PTR_ERR(fake_cpuc);
ca037701 2234
21d65555 2235 c = x86_pmu.get_event_constraints(fake_cpuc, 0, event);
ca037701
PZ
2236
2237 if (!c || !c->weight)
aa2bc1ad 2238 ret = -EINVAL;
ca037701
PZ
2239
2240 if (x86_pmu.put_event_constraints)
2241 x86_pmu.put_event_constraints(fake_cpuc, event);
2242
cd8a38d3 2243 free_fake_cpuc(fake_cpuc);
ca037701
PZ
2244
2245 return ret;
2246}
2247
1da53e02
SE
2248/*
2249 * validate a single event group
2250 *
2251 * validation include:
184f412c
IM
2252 * - check events are compatible which each other
2253 * - events do not compete for the same counter
2254 * - number of events <= number of counters
1da53e02
SE
2255 *
2256 * validation ensures the group can be loaded onto the
2257 * PMU if it was the only group available.
2258 */
fe9081cc
PZ
2259static int validate_group(struct perf_event *event)
2260{
1da53e02 2261 struct perf_event *leader = event->group_leader;
502568d5 2262 struct cpu_hw_events *fake_cpuc;
aa2bc1ad 2263 int ret = -EINVAL, n;
fe9081cc 2264
cd8a38d3
SE
2265 fake_cpuc = allocate_fake_cpuc();
2266 if (IS_ERR(fake_cpuc))
2267 return PTR_ERR(fake_cpuc);
1da53e02
SE
2268 /*
2269 * the event is not yet connected with its
2270 * siblings therefore we must first collect
2271 * existing siblings, then add the new event
2272 * before we can simulate the scheduling
2273 */
502568d5 2274 n = collect_events(fake_cpuc, leader, true);
1da53e02 2275 if (n < 0)
cd8a38d3 2276 goto out;
fe9081cc 2277
502568d5
PZ
2278 fake_cpuc->n_events = n;
2279 n = collect_events(fake_cpuc, event, false);
1da53e02 2280 if (n < 0)
cd8a38d3 2281 goto out;
fe9081cc 2282
1f6a1e2d 2283 fake_cpuc->n_events = 0;
a072738e 2284 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
502568d5 2285
502568d5 2286out:
cd8a38d3 2287 free_fake_cpuc(fake_cpuc);
502568d5 2288 return ret;
fe9081cc
PZ
2289}
2290
dda99116 2291static int x86_pmu_event_init(struct perf_event *event)
621a01ea 2292{
51b0fe39 2293 struct pmu *tmp;
621a01ea
IM
2294 int err;
2295
b0a873eb
PZ
2296 switch (event->attr.type) {
2297 case PERF_TYPE_RAW:
2298 case PERF_TYPE_HARDWARE:
2299 case PERF_TYPE_HW_CACHE:
2300 break;
2301
2302 default:
2303 return -ENOENT;
2304 }
2305
2306 err = __x86_pmu_event_init(event);
fe9081cc 2307 if (!err) {
8113070d
SE
2308 /*
2309 * we temporarily connect event to its pmu
2310 * such that validate_group() can classify
2311 * it as an x86 event using is_x86_event()
2312 */
2313 tmp = event->pmu;
2314 event->pmu = &pmu;
2315
fe9081cc
PZ
2316 if (event->group_leader != event)
2317 err = validate_group(event);
ca037701
PZ
2318 else
2319 err = validate_event(event);
8113070d
SE
2320
2321 event->pmu = tmp;
fe9081cc 2322 }
a1792cda 2323 if (err) {
cdd6c482
IM
2324 if (event->destroy)
2325 event->destroy(event);
a1792cda 2326 }
621a01ea 2327
1af22eba 2328 if (READ_ONCE(x86_pmu.attr_rdpmc) &&
174afc3e 2329 !(event->hw.flags & PERF_X86_EVENT_LARGE_PEBS))
7911d3f7
AL
2330 event->hw.flags |= PERF_X86_EVENT_RDPMC_ALLOWED;
2331
b0a873eb 2332 return err;
621a01ea 2333}
d7d59fb3 2334
bfe33492 2335static void x86_pmu_event_mapped(struct perf_event *event, struct mm_struct *mm)
7911d3f7
AL
2336{
2337 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
2338 return;
2339
4b07372a
AL
2340 /*
2341 * This function relies on not being called concurrently in two
2342 * tasks in the same mm. Otherwise one task could observe
2343 * perf_rdpmc_allowed > 1 and return all the way back to
2344 * userspace with CR4.PCE clear while another task is still
2345 * doing on_each_cpu_mask() to propagate CR4.PCE.
2346 *
c1e8d7c6 2347 * For now, this can't happen because all callers hold mmap_lock
4b07372a
AL
2348 * for write. If this changes, we'll need a different solution.
2349 */
42fc5414 2350 mmap_assert_write_locked(mm);
4b07372a 2351
bfe33492 2352 if (atomic_inc_return(&mm->context.perf_rdpmc_allowed) == 1)
cb2a0235 2353 on_each_cpu_mask(mm_cpumask(mm), cr4_update_pce, NULL, 1);
7911d3f7
AL
2354}
2355
bfe33492 2356static void x86_pmu_event_unmapped(struct perf_event *event, struct mm_struct *mm)
7911d3f7 2357{
7911d3f7
AL
2358
2359 if (!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED))
2360 return;
2361
bfe33492 2362 if (atomic_dec_and_test(&mm->context.perf_rdpmc_allowed))
cb2a0235 2363 on_each_cpu_mask(mm_cpumask(mm), cr4_update_pce, NULL, 1);
7911d3f7
AL
2364}
2365
fe4a3308
PZ
2366static int x86_pmu_event_idx(struct perf_event *event)
2367{
75608cb0 2368 struct hw_perf_event *hwc = &event->hw;
fe4a3308 2369
75608cb0 2370 if (!(hwc->flags & PERF_X86_EVENT_RDPMC_ALLOWED))
c7206205
PZ
2371 return 0;
2372
2cb5383b
KL
2373 if (is_metric_idx(hwc->idx))
2374 return INTEL_PMC_FIXED_RDPMC_METRICS + 1;
2375 else
2376 return hwc->event_base_rdpmc + 1;
fe4a3308
PZ
2377}
2378
0c9d42ed
PZ
2379static ssize_t get_attr_rdpmc(struct device *cdev,
2380 struct device_attribute *attr,
2381 char *buf)
2382{
2383 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
2384}
2385
0c9d42ed
PZ
2386static ssize_t set_attr_rdpmc(struct device *cdev,
2387 struct device_attribute *attr,
2388 const char *buf, size_t count)
2389{
e2b297fc
SK
2390 unsigned long val;
2391 ssize_t ret;
2392
2393 ret = kstrtoul(buf, 0, &val);
2394 if (ret)
2395 return ret;
e97df763 2396
a6673429
AL
2397 if (val > 2)
2398 return -EINVAL;
2399
e97df763
PZ
2400 if (x86_pmu.attr_rdpmc_broken)
2401 return -ENOTSUPP;
0c9d42ed 2402
405b4537 2403 if (val != x86_pmu.attr_rdpmc) {
a6673429 2404 /*
405b4537
AS
2405 * Changing into or out of never available or always available,
2406 * aka perf-event-bypassing mode. This path is extremely slow,
a6673429
AL
2407 * but only root can trigger it, so it's okay.
2408 */
405b4537
AS
2409 if (val == 0)
2410 static_branch_inc(&rdpmc_never_available_key);
2411 else if (x86_pmu.attr_rdpmc == 0)
2412 static_branch_dec(&rdpmc_never_available_key);
2413
a6673429 2414 if (val == 2)
631fe154 2415 static_branch_inc(&rdpmc_always_available_key);
405b4537 2416 else if (x86_pmu.attr_rdpmc == 2)
631fe154 2417 static_branch_dec(&rdpmc_always_available_key);
405b4537 2418
cb2a0235 2419 on_each_cpu(cr4_update_pce, NULL, 1);
405b4537 2420 x86_pmu.attr_rdpmc = val;
a6673429
AL
2421 }
2422
0c9d42ed
PZ
2423 return count;
2424}
2425
2426static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
2427
2428static struct attribute *x86_pmu_attrs[] = {
2429 &dev_attr_rdpmc.attr,
2430 NULL,
2431};
2432
2766d2ee 2433static struct attribute_group x86_pmu_attr_group __ro_after_init = {
0c9d42ed
PZ
2434 .attrs = x86_pmu_attrs,
2435};
2436
5da382eb
PZ
2437static ssize_t max_precise_show(struct device *cdev,
2438 struct device_attribute *attr,
2439 char *buf)
2440{
2441 return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu_max_precise());
2442}
2443
2444static DEVICE_ATTR_RO(max_precise);
2445
2446static struct attribute *x86_pmu_caps_attrs[] = {
2447 &dev_attr_max_precise.attr,
2448 NULL
2449};
2450
2766d2ee 2451static struct attribute_group x86_pmu_caps_group __ro_after_init = {
5da382eb
PZ
2452 .name = "caps",
2453 .attrs = x86_pmu_caps_attrs,
2454};
2455
0c9d42ed
PZ
2456static const struct attribute_group *x86_pmu_attr_groups[] = {
2457 &x86_pmu_attr_group,
641cc938 2458 &x86_pmu_format_group,
a4747393 2459 &x86_pmu_events_group,
b00233b5 2460 &x86_pmu_caps_group,
0c9d42ed
PZ
2461 NULL,
2462};
2463
ba532500 2464static void x86_pmu_sched_task(struct perf_event_context *ctx, bool sched_in)
d010b332 2465{
7c9903c9 2466 static_call_cond(x86_pmu_sched_task)(ctx, sched_in);
d010b332
SE
2467}
2468
a4439970
AB
2469static void x86_pmu_swap_task_ctx(struct perf_event_context *prev,
2470 struct perf_event_context *next)
2471{
7c9903c9 2472 static_call_cond(x86_pmu_swap_task_ctx)(prev, next);
a4439970
AB
2473}
2474
c93dc84c
PZ
2475void perf_check_microcode(void)
2476{
2477 if (x86_pmu.check_microcode)
2478 x86_pmu.check_microcode();
2479}
c93dc84c 2480
81ec3f3c
JO
2481static int x86_pmu_check_period(struct perf_event *event, u64 value)
2482{
2483 if (x86_pmu.check_period && x86_pmu.check_period(event, value))
2484 return -EINVAL;
2485
2486 if (value && x86_pmu.limit_period) {
2487 if (x86_pmu.limit_period(event, value) > value)
2488 return -EINVAL;
2489 }
2490
2491 return 0;
2492}
2493
42880f72
AS
2494static int x86_pmu_aux_output_match(struct perf_event *event)
2495{
2496 if (!(pmu.capabilities & PERF_PMU_CAP_AUX_OUTPUT))
2497 return 0;
2498
2499 if (x86_pmu.aux_output_match)
2500 return x86_pmu.aux_output_match(event);
2501
2502 return 0;
2503}
2504
b0a873eb 2505static struct pmu pmu = {
d010b332
SE
2506 .pmu_enable = x86_pmu_enable,
2507 .pmu_disable = x86_pmu_disable,
a4eaf7f1 2508
c93dc84c 2509 .attr_groups = x86_pmu_attr_groups,
0c9d42ed 2510
c93dc84c 2511 .event_init = x86_pmu_event_init,
a4eaf7f1 2512
7911d3f7
AL
2513 .event_mapped = x86_pmu_event_mapped,
2514 .event_unmapped = x86_pmu_event_unmapped,
2515
d010b332
SE
2516 .add = x86_pmu_add,
2517 .del = x86_pmu_del,
2518 .start = x86_pmu_start,
2519 .stop = x86_pmu_stop,
2520 .read = x86_pmu_read,
a4eaf7f1 2521
c93dc84c
PZ
2522 .start_txn = x86_pmu_start_txn,
2523 .cancel_txn = x86_pmu_cancel_txn,
2524 .commit_txn = x86_pmu_commit_txn,
fe4a3308 2525
c93dc84c 2526 .event_idx = x86_pmu_event_idx,
ba532500 2527 .sched_task = x86_pmu_sched_task,
a4439970 2528 .swap_task_ctx = x86_pmu_swap_task_ctx,
81ec3f3c 2529 .check_period = x86_pmu_check_period,
42880f72
AS
2530
2531 .aux_output_match = x86_pmu_aux_output_match,
b0a873eb
PZ
2532};
2533
c1317ec2
AL
2534void arch_perf_update_userpage(struct perf_event *event,
2535 struct perf_event_mmap_page *userpg, u64 now)
e3f3541c 2536{
59eaef78 2537 struct cyc2ns_data data;
698eff63 2538 u64 offset;
20d1c86a 2539
fa731587
PZ
2540 userpg->cap_user_time = 0;
2541 userpg->cap_user_time_zero = 0;
7911d3f7
AL
2542 userpg->cap_user_rdpmc =
2543 !!(event->hw.flags & PERF_X86_EVENT_RDPMC_ALLOWED);
c7206205
PZ
2544 userpg->pmc_width = x86_pmu.cntval_bits;
2545
698eff63 2546 if (!using_native_sched_clock() || !sched_clock_stable())
e3f3541c
PZ
2547 return;
2548
59eaef78 2549 cyc2ns_read_begin(&data);
20d1c86a 2550
59eaef78 2551 offset = data.cyc2ns_offset + __sched_clock_offset;
698eff63 2552
34f43927
PZ
2553 /*
2554 * Internal timekeeping for enabled/running/stopped times
2555 * is always in the local_clock domain.
2556 */
fa731587 2557 userpg->cap_user_time = 1;
59eaef78
PZ
2558 userpg->time_mult = data.cyc2ns_mul;
2559 userpg->time_shift = data.cyc2ns_shift;
698eff63 2560 userpg->time_offset = offset - now;
c73deb6a 2561
34f43927
PZ
2562 /*
2563 * cap_user_time_zero doesn't make sense when we're using a different
2564 * time base for the records.
2565 */
f454bfdd 2566 if (!event->attr.use_clockid) {
34f43927 2567 userpg->cap_user_time_zero = 1;
698eff63 2568 userpg->time_zero = offset;
34f43927 2569 }
20d1c86a 2570
59eaef78 2571 cyc2ns_read_end();
e3f3541c
PZ
2572}
2573
d15d3568
KS
2574/*
2575 * Determine whether the regs were taken from an irq/exception handler rather
2576 * than from perf_arch_fetch_caller_regs().
2577 */
2578static bool perf_hw_regs(struct pt_regs *regs)
2579{
2580 return regs->flags & X86_EFLAGS_FIXED;
2581}
2582
56962b44 2583void
cfbcf468 2584perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs)
d7d59fb3 2585{
35f4d9b3
JP
2586 struct unwind_state state;
2587 unsigned long addr;
2588
927c7a9e
FW
2589 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2590 /* TODO: We don't support guest os callchain now */
ed805261 2591 return;
927c7a9e
FW
2592 }
2593
83f44ae0
SL
2594 if (perf_callchain_store(entry, regs->ip))
2595 return;
2596
2597 if (perf_hw_regs(regs))
d15d3568 2598 unwind_start(&state, current, regs, NULL);
83f44ae0 2599 else
d15d3568 2600 unwind_start(&state, current, NULL, (void *)regs->sp);
d7d59fb3 2601
d15d3568 2602 for (; !unwind_done(&state); unwind_next_frame(&state)) {
35f4d9b3
JP
2603 addr = unwind_get_return_address(&state);
2604 if (!addr || perf_callchain_store(entry, addr))
2605 return;
2606 }
d7d59fb3
PZ
2607}
2608
bc6ca7b3
AS
2609static inline int
2610valid_user_frame(const void __user *fp, unsigned long size)
2611{
2612 return (__range_not_ok(fp, size, TASK_SIZE) == 0);
2613}
2614
d07bdfd3
PZ
2615static unsigned long get_segment_base(unsigned int segment)
2616{
2617 struct desc_struct *desc;
990e9dc3 2618 unsigned int idx = segment >> 3;
d07bdfd3
PZ
2619
2620 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
a5b9e5a2 2621#ifdef CONFIG_MODIFY_LDT_SYSCALL
37868fe1
AL
2622 struct ldt_struct *ldt;
2623
37868fe1 2624 /* IRQs are off, so this synchronizes with smp_store_release */
506458ef 2625 ldt = READ_ONCE(current->active_mm->context.ldt);
eaa2f87c 2626 if (!ldt || idx >= ldt->nr_entries)
d07bdfd3
PZ
2627 return 0;
2628
37868fe1 2629 desc = &ldt->entries[idx];
a5b9e5a2
AL
2630#else
2631 return 0;
2632#endif
d07bdfd3 2633 } else {
eaa2f87c 2634 if (idx >= GDT_ENTRIES)
d07bdfd3
PZ
2635 return 0;
2636
37868fe1 2637 desc = raw_cpu_ptr(gdt_page.gdt) + idx;
d07bdfd3
PZ
2638 }
2639
37868fe1 2640 return get_desc_base(desc);
d07bdfd3
PZ
2641}
2642
10ed3493 2643#ifdef CONFIG_IA32_EMULATION
d1a797f3 2644
0d55303c 2645#include <linux/compat.h>
d1a797f3 2646
257ef9d2 2647static inline int
cfbcf468 2648perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry_ctx *entry)
74193ef0 2649{
257ef9d2 2650 /* 32-bit process in 64-bit kernel. */
d07bdfd3 2651 unsigned long ss_base, cs_base;
257ef9d2 2652 struct stack_frame_ia32 frame;
c8e3dd86 2653 const struct stack_frame_ia32 __user *fp;
74193ef0 2654
375d4bfd 2655 if (user_64bit_mode(regs))
257ef9d2
TE
2656 return 0;
2657
d07bdfd3
PZ
2658 cs_base = get_segment_base(regs->cs);
2659 ss_base = get_segment_base(regs->ss);
2660
2661 fp = compat_ptr(ss_base + regs->bp);
75925e1a 2662 pagefault_disable();
3b1fff08 2663 while (entry->nr < entry->max_stack) {
ae31fe51 2664 if (!valid_user_frame(fp, sizeof(frame)))
75925e1a
AK
2665 break;
2666
c8e3dd86 2667 if (__get_user(frame.next_frame, &fp->next_frame))
75925e1a 2668 break;
c8e3dd86 2669 if (__get_user(frame.return_address, &fp->return_address))
257ef9d2 2670 break;
74193ef0 2671
d07bdfd3
PZ
2672 perf_callchain_store(entry, cs_base + frame.return_address);
2673 fp = compat_ptr(ss_base + frame.next_frame);
257ef9d2 2674 }
75925e1a 2675 pagefault_enable();
257ef9d2 2676 return 1;
d7d59fb3 2677}
257ef9d2
TE
2678#else
2679static inline int
cfbcf468 2680perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry_ctx *entry)
257ef9d2
TE
2681{
2682 return 0;
2683}
2684#endif
d7d59fb3 2685
56962b44 2686void
cfbcf468 2687perf_callchain_user(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs)
d7d59fb3
PZ
2688{
2689 struct stack_frame frame;
c8e3dd86 2690 const struct stack_frame __user *fp;
d7d59fb3 2691
927c7a9e
FW
2692 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
2693 /* TODO: We don't support guest os callchain now */
ed805261 2694 return;
927c7a9e 2695 }
5a6cec3a 2696
d07bdfd3
PZ
2697 /*
2698 * We don't know what to do with VM86 stacks.. ignore them for now.
2699 */
2700 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2701 return;
2702
c8e3dd86 2703 fp = (void __user *)regs->bp;
d7d59fb3 2704
70791ce9 2705 perf_callchain_store(entry, regs->ip);
d7d59fb3 2706
4012e77a 2707 if (!nmi_uaccess_okay())
20afc60f
AV
2708 return;
2709
257ef9d2
TE
2710 if (perf_callchain_user32(regs, entry))
2711 return;
2712
75925e1a 2713 pagefault_disable();
3b1fff08 2714 while (entry->nr < entry->max_stack) {
ae31fe51 2715 if (!valid_user_frame(fp, sizeof(frame)))
75925e1a
AK
2716 break;
2717
c8e3dd86 2718 if (__get_user(frame.next_frame, &fp->next_frame))
75925e1a 2719 break;
c8e3dd86 2720 if (__get_user(frame.return_address, &fp->return_address))
d7d59fb3
PZ
2721 break;
2722
70791ce9 2723 perf_callchain_store(entry, frame.return_address);
75925e1a 2724 fp = (void __user *)frame.next_frame;
d7d59fb3 2725 }
75925e1a 2726 pagefault_enable();
d7d59fb3
PZ
2727}
2728
d07bdfd3
PZ
2729/*
2730 * Deal with code segment offsets for the various execution modes:
2731 *
2732 * VM86 - the good olde 16 bit days, where the linear address is
2733 * 20 bits and we use regs->ip + 0x10 * regs->cs.
2734 *
2735 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
2736 * to figure out what the 32bit base address is.
2737 *
2738 * X32 - has TIF_X32 set, but is running in x86_64
2739 *
2740 * X86_64 - CS,DS,SS,ES are all zero based.
2741 */
2742static unsigned long code_segment_base(struct pt_regs *regs)
39447b38 2743{
383f3af3
AL
2744 /*
2745 * For IA32 we look at the GDT/LDT segment base to convert the
2746 * effective IP to a linear address.
2747 */
2748
2749#ifdef CONFIG_X86_32
d07bdfd3
PZ
2750 /*
2751 * If we are in VM86 mode, add the segment offset to convert to a
2752 * linear address.
2753 */
2754 if (regs->flags & X86_VM_MASK)
2755 return 0x10 * regs->cs;
2756
55474c48 2757 if (user_mode(regs) && regs->cs != __USER_CS)
d07bdfd3
PZ
2758 return get_segment_base(regs->cs);
2759#else
c56716af
AL
2760 if (user_mode(regs) && !user_64bit_mode(regs) &&
2761 regs->cs != __USER32_CS)
2762 return get_segment_base(regs->cs);
d07bdfd3
PZ
2763#endif
2764 return 0;
2765}
dcf46b94 2766
d07bdfd3
PZ
2767unsigned long perf_instruction_pointer(struct pt_regs *regs)
2768{
39447b38 2769 if (perf_guest_cbs && perf_guest_cbs->is_in_guest())
d07bdfd3 2770 return perf_guest_cbs->get_guest_ip();
dcf46b94 2771
d07bdfd3 2772 return regs->ip + code_segment_base(regs);
39447b38
ZY
2773}
2774
2775unsigned long perf_misc_flags(struct pt_regs *regs)
2776{
2777 int misc = 0;
dcf46b94 2778
39447b38 2779 if (perf_guest_cbs && perf_guest_cbs->is_in_guest()) {
dcf46b94
ZY
2780 if (perf_guest_cbs->is_user_mode())
2781 misc |= PERF_RECORD_MISC_GUEST_USER;
2782 else
2783 misc |= PERF_RECORD_MISC_GUEST_KERNEL;
2784 } else {
d07bdfd3 2785 if (user_mode(regs))
dcf46b94
ZY
2786 misc |= PERF_RECORD_MISC_USER;
2787 else
2788 misc |= PERF_RECORD_MISC_KERNEL;
2789 }
2790
39447b38 2791 if (regs->flags & PERF_EFLAGS_EXACT)
ab608344 2792 misc |= PERF_RECORD_MISC_EXACT_IP;
39447b38
ZY
2793
2794 return misc;
2795}
b3d9468a
GN
2796
2797void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
2798{
2799 cap->version = x86_pmu.version;
d4b294bf
KL
2800 /*
2801 * KVM doesn't support the hybrid PMU yet.
2802 * Return the common value in global x86_pmu,
2803 * which available for all cores.
2804 */
b3d9468a
GN
2805 cap->num_counters_gp = x86_pmu.num_counters;
2806 cap->num_counters_fixed = x86_pmu.num_counters_fixed;
2807 cap->bit_width_gp = x86_pmu.cntval_bits;
2808 cap->bit_width_fixed = x86_pmu.cntval_bits;
2809 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
2810 cap->events_mask_len = x86_pmu.events_mask_len;
2811}
2812EXPORT_SYMBOL_GPL(perf_get_x86_pmu_capability);