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