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