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 perf_event * event,struct cpu_hw_events * cpuc,int i)1297 static inline int match_prev_assignment(struct perf_event *event,
1298 struct cpu_hw_events *cpuc,
1299 int i)
1300 {
1301 struct hw_perf_event *hwc = &event->hw;
1302
1303 return hwc->idx == cpuc->assign[i] &&
1304 hwc->last_cpu == smp_processor_id() &&
1305 hwc->last_tag == cpuc->tags[i] &&
1306 !is_acr_event_group(event);
1307 }
1308
1309 static void x86_pmu_start(struct perf_event *event, int flags);
1310
x86_pmu_enable(struct pmu * pmu)1311 static void x86_pmu_enable(struct pmu *pmu)
1312 {
1313 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1314 struct perf_event *event;
1315 struct hw_perf_event *hwc;
1316 int i, added = cpuc->n_added;
1317
1318 if (!x86_pmu_initialized())
1319 return;
1320
1321 if (cpuc->enabled)
1322 return;
1323
1324 if (cpuc->n_added) {
1325 int n_running = cpuc->n_events - cpuc->n_added;
1326
1327 /*
1328 * The late setup (after counters are scheduled)
1329 * is required for some cases, e.g., PEBS counters
1330 * snapshotting. Because an accurate counter index
1331 * is needed.
1332 */
1333 static_call_cond(x86_pmu_late_setup)();
1334
1335 /*
1336 * apply assignment obtained either from
1337 * hw_perf_group_sched_in() or x86_pmu_enable()
1338 *
1339 * step1: save events moving to new counters
1340 */
1341 for (i = 0; i < n_running; i++) {
1342 event = cpuc->event_list[i];
1343 hwc = &event->hw;
1344
1345 /*
1346 * we can avoid reprogramming counter if:
1347 * - assigned same counter as last time
1348 * - running on same CPU as last time
1349 * - no other event has used the counter since
1350 */
1351 if (hwc->idx == -1 ||
1352 match_prev_assignment(event, cpuc, i))
1353 continue;
1354
1355 /*
1356 * Ensure we don't accidentally enable a stopped
1357 * counter simply because we rescheduled.
1358 */
1359 if (hwc->state & PERF_HES_STOPPED)
1360 hwc->state |= PERF_HES_ARCH;
1361
1362 x86_pmu_stop(event, PERF_EF_UPDATE);
1363 cpuc->events[hwc->idx] = NULL;
1364 }
1365
1366 /*
1367 * step2: reprogram moved events into new counters
1368 */
1369 for (i = 0; i < cpuc->n_events; i++) {
1370 event = cpuc->event_list[i];
1371 hwc = &event->hw;
1372
1373 if (!match_prev_assignment(event, cpuc, i))
1374 x86_assign_hw_event(event, cpuc, i);
1375 else if (i < n_running)
1376 continue;
1377
1378 cpuc->events[hwc->idx] = event;
1379
1380 if (hwc->state & PERF_HES_ARCH) {
1381 static_call(x86_pmu_set_period)(event);
1382 continue;
1383 }
1384
1385 /*
1386 * if cpuc->enabled = 0, then no wrmsr as
1387 * per x86_pmu_enable_event()
1388 */
1389 x86_pmu_start(event, PERF_EF_RELOAD);
1390 }
1391 cpuc->n_added = 0;
1392 perf_events_lapic_init();
1393 }
1394
1395 cpuc->enabled = 1;
1396 barrier();
1397
1398 static_call(x86_pmu_enable_all)(added);
1399 }
1400
1401 DEFINE_PER_CPU(u64 [X86_PMC_IDX_MAX], pmc_prev_left);
1402
1403 /*
1404 * Set the next IRQ period, based on the hwc->period_left value.
1405 * To be called with the event disabled in hw:
1406 */
x86_perf_event_set_period(struct perf_event * event)1407 int x86_perf_event_set_period(struct perf_event *event)
1408 {
1409 struct hw_perf_event *hwc = &event->hw;
1410 s64 left = local64_read(&hwc->period_left);
1411 s64 period = hwc->sample_period;
1412 int ret = 0, idx = hwc->idx;
1413
1414 if (unlikely(!hwc->event_base))
1415 return 0;
1416
1417 /*
1418 * If we are way outside a reasonable range then just skip forward:
1419 */
1420 if (unlikely(left <= -period)) {
1421 left = period;
1422 local64_set(&hwc->period_left, left);
1423 hwc->last_period = period;
1424 ret = 1;
1425 }
1426
1427 if (unlikely(left <= 0)) {
1428 left += period;
1429 local64_set(&hwc->period_left, left);
1430 hwc->last_period = period;
1431 ret = 1;
1432 }
1433 /*
1434 * Quirk: certain CPUs dont like it if just 1 hw_event is left:
1435 */
1436 if (unlikely(left < 2))
1437 left = 2;
1438
1439 if (left > x86_pmu.max_period)
1440 left = x86_pmu.max_period;
1441
1442 static_call_cond(x86_pmu_limit_period)(event, &left);
1443
1444 this_cpu_write(pmc_prev_left[idx], left);
1445
1446 /*
1447 * The hw event starts counting from this event offset,
1448 * mark it to be able to extra future deltas:
1449 */
1450 local64_set(&hwc->prev_count, (u64)-left);
1451
1452 wrmsrq(hwc->event_base, (u64)(-left) & x86_pmu.cntval_mask);
1453
1454 /*
1455 * Sign extend the Merge event counter's upper 16 bits since
1456 * we currently declare a 48-bit counter width
1457 */
1458 if (is_counter_pair(hwc))
1459 wrmsrq(x86_pmu_event_addr(idx + 1), 0xffff);
1460
1461 perf_event_update_userpage(event);
1462
1463 return ret;
1464 }
1465
x86_pmu_enable_event(struct perf_event * event)1466 void x86_pmu_enable_event(struct perf_event *event)
1467 {
1468 if (__this_cpu_read(cpu_hw_events.enabled))
1469 __x86_pmu_enable_event(&event->hw,
1470 ARCH_PERFMON_EVENTSEL_ENABLE);
1471 }
1472
1473 /*
1474 * Add a single event to the PMU.
1475 *
1476 * The event is added to the group of enabled events
1477 * but only if it can be scheduled with existing events.
1478 */
x86_pmu_add(struct perf_event * event,int flags)1479 static int x86_pmu_add(struct perf_event *event, int flags)
1480 {
1481 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1482 struct hw_perf_event *hwc;
1483 int assign[X86_PMC_IDX_MAX];
1484 int n, n0, ret;
1485
1486 hwc = &event->hw;
1487
1488 n0 = cpuc->n_events;
1489 ret = n = collect_events(cpuc, event, false);
1490 if (ret < 0)
1491 goto out;
1492
1493 hwc->state = PERF_HES_UPTODATE | PERF_HES_STOPPED;
1494 if (!(flags & PERF_EF_START))
1495 hwc->state |= PERF_HES_ARCH;
1496
1497 /*
1498 * If group events scheduling transaction was started,
1499 * skip the schedulability test here, it will be performed
1500 * at commit time (->commit_txn) as a whole.
1501 *
1502 * If commit fails, we'll call ->del() on all events
1503 * for which ->add() was called.
1504 */
1505 if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
1506 goto done_collect;
1507
1508 ret = static_call(x86_pmu_schedule_events)(cpuc, n, assign);
1509 if (ret)
1510 goto out;
1511 /*
1512 * copy new assignment, now we know it is possible
1513 * will be used by hw_perf_enable()
1514 */
1515 memcpy(cpuc->assign, assign, n*sizeof(int));
1516
1517 done_collect:
1518 /*
1519 * Commit the collect_events() state. See x86_pmu_del() and
1520 * x86_pmu_*_txn().
1521 */
1522 cpuc->n_events = n;
1523 cpuc->n_added += n - n0;
1524 cpuc->n_txn += n - n0;
1525
1526 /*
1527 * This is before x86_pmu_enable() will call x86_pmu_start(),
1528 * so we enable LBRs before an event needs them etc..
1529 */
1530 static_call_cond(x86_pmu_add)(event);
1531
1532 ret = 0;
1533 out:
1534 return ret;
1535 }
1536
x86_pmu_start(struct perf_event * event,int flags)1537 static void x86_pmu_start(struct perf_event *event, int flags)
1538 {
1539 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1540 int idx = event->hw.idx;
1541
1542 if (WARN_ON_ONCE(!(event->hw.state & PERF_HES_STOPPED)))
1543 return;
1544
1545 if (WARN_ON_ONCE(idx == -1))
1546 return;
1547
1548 if (flags & PERF_EF_RELOAD) {
1549 WARN_ON_ONCE(!(event->hw.state & PERF_HES_UPTODATE));
1550 static_call(x86_pmu_set_period)(event);
1551 }
1552
1553 event->hw.state = 0;
1554
1555 __set_bit(idx, cpuc->active_mask);
1556 static_call(x86_pmu_enable)(event);
1557 perf_event_update_userpage(event);
1558 }
1559
perf_event_print_debug(void)1560 void perf_event_print_debug(void)
1561 {
1562 u64 ctrl, status, overflow, pmc_ctrl, pmc_count, prev_left, fixed;
1563 unsigned long *cntr_mask, *fixed_cntr_mask;
1564 struct event_constraint *pebs_constraints;
1565 struct cpu_hw_events *cpuc;
1566 u64 pebs, debugctl;
1567 int cpu, idx;
1568
1569 guard(irqsave)();
1570
1571 cpu = smp_processor_id();
1572 cpuc = &per_cpu(cpu_hw_events, cpu);
1573 cntr_mask = hybrid(cpuc->pmu, cntr_mask);
1574 fixed_cntr_mask = hybrid(cpuc->pmu, fixed_cntr_mask);
1575 pebs_constraints = hybrid(cpuc->pmu, pebs_constraints);
1576
1577 if (!*(u64 *)cntr_mask)
1578 return;
1579
1580 if (x86_pmu.version >= 2) {
1581 rdmsrq(MSR_CORE_PERF_GLOBAL_CTRL, ctrl);
1582 rdmsrq(MSR_CORE_PERF_GLOBAL_STATUS, status);
1583 rdmsrq(MSR_CORE_PERF_GLOBAL_OVF_CTRL, overflow);
1584 rdmsrq(MSR_ARCH_PERFMON_FIXED_CTR_CTRL, fixed);
1585
1586 pr_info("\n");
1587 pr_info("CPU#%d: ctrl: %016llx\n", cpu, ctrl);
1588 pr_info("CPU#%d: status: %016llx\n", cpu, status);
1589 pr_info("CPU#%d: overflow: %016llx\n", cpu, overflow);
1590 pr_info("CPU#%d: fixed: %016llx\n", cpu, fixed);
1591 if (pebs_constraints) {
1592 rdmsrq(MSR_IA32_PEBS_ENABLE, pebs);
1593 pr_info("CPU#%d: pebs: %016llx\n", cpu, pebs);
1594 }
1595 if (x86_pmu.lbr_nr) {
1596 rdmsrq(MSR_IA32_DEBUGCTLMSR, debugctl);
1597 pr_info("CPU#%d: debugctl: %016llx\n", cpu, debugctl);
1598 }
1599 }
1600 pr_info("CPU#%d: active: %016llx\n", cpu, *(u64 *)cpuc->active_mask);
1601
1602 for_each_set_bit(idx, cntr_mask, X86_PMC_IDX_MAX) {
1603 rdmsrq(x86_pmu_config_addr(idx), pmc_ctrl);
1604 rdmsrq(x86_pmu_event_addr(idx), pmc_count);
1605
1606 prev_left = per_cpu(pmc_prev_left[idx], cpu);
1607
1608 pr_info("CPU#%d: gen-PMC%d ctrl: %016llx\n",
1609 cpu, idx, pmc_ctrl);
1610 pr_info("CPU#%d: gen-PMC%d count: %016llx\n",
1611 cpu, idx, pmc_count);
1612 pr_info("CPU#%d: gen-PMC%d left: %016llx\n",
1613 cpu, idx, prev_left);
1614 }
1615 for_each_set_bit(idx, fixed_cntr_mask, X86_PMC_IDX_MAX) {
1616 if (fixed_counter_disabled(idx, cpuc->pmu))
1617 continue;
1618 rdmsrq(x86_pmu_fixed_ctr_addr(idx), pmc_count);
1619
1620 pr_info("CPU#%d: fixed-PMC%d count: %016llx\n",
1621 cpu, idx, pmc_count);
1622 }
1623 }
1624
x86_pmu_stop(struct perf_event * event,int flags)1625 void x86_pmu_stop(struct perf_event *event, int flags)
1626 {
1627 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1628 struct hw_perf_event *hwc = &event->hw;
1629
1630 if (test_bit(hwc->idx, cpuc->active_mask)) {
1631 static_call(x86_pmu_disable)(event);
1632 __clear_bit(hwc->idx, cpuc->active_mask);
1633 WARN_ON_ONCE(hwc->state & PERF_HES_STOPPED);
1634 hwc->state |= PERF_HES_STOPPED;
1635 }
1636
1637 if ((flags & PERF_EF_UPDATE) && !(hwc->state & PERF_HES_UPTODATE)) {
1638 /*
1639 * Drain the remaining delta count out of a event
1640 * that we are disabling:
1641 */
1642 static_call(x86_pmu_update)(event);
1643 hwc->state |= PERF_HES_UPTODATE;
1644 }
1645 }
1646
x86_pmu_del(struct perf_event * event,int flags)1647 static void x86_pmu_del(struct perf_event *event, int flags)
1648 {
1649 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
1650 union perf_capabilities intel_cap = hybrid(cpuc->pmu, intel_cap);
1651 int i;
1652
1653 /*
1654 * If we're called during a txn, we only need to undo x86_pmu.add.
1655 * The events never got scheduled and ->cancel_txn will truncate
1656 * the event_list.
1657 *
1658 * XXX assumes any ->del() called during a TXN will only be on
1659 * an event added during that same TXN.
1660 */
1661 if (cpuc->txn_flags & PERF_PMU_TXN_ADD)
1662 goto do_del;
1663
1664 __set_bit(event->hw.idx, cpuc->dirty);
1665
1666 /*
1667 * Not a TXN, therefore cleanup properly.
1668 */
1669 x86_pmu_stop(event, PERF_EF_UPDATE);
1670 cpuc->events[event->hw.idx] = NULL;
1671
1672 for (i = 0; i < cpuc->n_events; i++) {
1673 if (event == cpuc->event_list[i])
1674 break;
1675 }
1676
1677 if (WARN_ON_ONCE(i == cpuc->n_events)) /* called ->del() without ->add() ? */
1678 return;
1679
1680 /* If we have a newly added event; make sure to decrease n_added. */
1681 if (i >= cpuc->n_events - cpuc->n_added)
1682 --cpuc->n_added;
1683
1684 static_call_cond(x86_pmu_put_event_constraints)(cpuc, event);
1685
1686 /* Delete the array entry. */
1687 while (++i < cpuc->n_events) {
1688 cpuc->event_list[i-1] = cpuc->event_list[i];
1689 cpuc->event_constraint[i-1] = cpuc->event_constraint[i];
1690 cpuc->assign[i-1] = cpuc->assign[i];
1691 }
1692 cpuc->event_constraint[i-1] = NULL;
1693 --cpuc->n_events;
1694 if (intel_cap.perf_metrics)
1695 del_nr_metric_event(cpuc, event);
1696
1697 perf_event_update_userpage(event);
1698
1699 do_del:
1700
1701 /*
1702 * This is after x86_pmu_stop(); so we disable LBRs after any
1703 * event can need them etc..
1704 */
1705 static_call_cond(x86_pmu_del)(event);
1706 }
1707
x86_pmu_handle_irq(struct pt_regs * regs)1708 int x86_pmu_handle_irq(struct pt_regs *regs)
1709 {
1710 struct perf_sample_data data;
1711 struct cpu_hw_events *cpuc;
1712 struct perf_event *event;
1713 int idx, handled = 0;
1714 u64 last_period;
1715 u64 val;
1716
1717 cpuc = this_cpu_ptr(&cpu_hw_events);
1718
1719 /*
1720 * Some chipsets need to unmask the LVTPC in a particular spot
1721 * inside the nmi handler. As a result, the unmasking was pushed
1722 * into all the nmi handlers.
1723 *
1724 * This generic handler doesn't seem to have any issues where the
1725 * unmasking occurs so it was left at the top.
1726 */
1727 apic_write(APIC_LVTPC, APIC_DM_NMI);
1728
1729 for_each_set_bit(idx, x86_pmu.cntr_mask, X86_PMC_IDX_MAX) {
1730 if (!test_bit(idx, cpuc->active_mask))
1731 continue;
1732
1733 event = cpuc->events[idx];
1734 last_period = event->hw.last_period;
1735
1736 val = static_call(x86_pmu_update)(event);
1737 if (val & (1ULL << (x86_pmu.cntval_bits - 1)))
1738 continue;
1739
1740 /*
1741 * event overflow
1742 */
1743 handled++;
1744
1745 if (!static_call(x86_pmu_set_period)(event))
1746 continue;
1747
1748 perf_sample_data_init(&data, 0, last_period);
1749
1750 perf_sample_save_brstack(&data, event, &cpuc->lbr_stack, NULL);
1751
1752 perf_event_overflow(event, &data, regs);
1753 }
1754
1755 if (handled)
1756 inc_irq_stat(apic_perf_irqs);
1757
1758 return handled;
1759 }
1760
perf_events_lapic_init(void)1761 void perf_events_lapic_init(void)
1762 {
1763 if (!x86_pmu.apic || !x86_pmu_initialized())
1764 return;
1765
1766 /*
1767 * Always use NMI for PMU
1768 */
1769 apic_write(APIC_LVTPC, APIC_DM_NMI);
1770 }
1771
1772 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU
perf_load_guest_lvtpc(u32 guest_lvtpc)1773 void perf_load_guest_lvtpc(u32 guest_lvtpc)
1774 {
1775 u32 masked = guest_lvtpc & APIC_LVT_MASKED;
1776
1777 apic_write(APIC_LVTPC,
1778 APIC_DM_FIXED | PERF_GUEST_MEDIATED_PMI_VECTOR | masked);
1779 this_cpu_write(guest_lvtpc_loaded, true);
1780 }
1781 EXPORT_SYMBOL_FOR_KVM(perf_load_guest_lvtpc);
1782
perf_put_guest_lvtpc(void)1783 void perf_put_guest_lvtpc(void)
1784 {
1785 this_cpu_write(guest_lvtpc_loaded, false);
1786 apic_write(APIC_LVTPC, APIC_DM_NMI);
1787 }
1788 EXPORT_SYMBOL_FOR_KVM(perf_put_guest_lvtpc);
1789 #endif /* CONFIG_PERF_GUEST_MEDIATED_PMU */
1790
1791 static int
perf_event_nmi_handler(unsigned int cmd,struct pt_regs * regs)1792 perf_event_nmi_handler(unsigned int cmd, struct pt_regs *regs)
1793 {
1794 u64 start_clock;
1795 u64 finish_clock;
1796 int ret;
1797
1798 /*
1799 * Ignore all NMIs when the CPU's LVTPC is configured to route PMIs to
1800 * PERF_GUEST_MEDIATED_PMI_VECTOR, i.e. when an NMI time can't be due
1801 * to a PMI. Attempting to handle a PMI while the guest's context is
1802 * loaded will generate false positives and clobber guest state. Note,
1803 * the LVTPC is switched to/from the dedicated mediated PMI IRQ vector
1804 * while host events are quiesced.
1805 */
1806 if (this_cpu_read(guest_lvtpc_loaded))
1807 return NMI_DONE;
1808
1809 /*
1810 * All PMUs/events that share this PMI handler should make sure to
1811 * increment active_events for their events.
1812 */
1813 if (!atomic_read(&active_events))
1814 return NMI_DONE;
1815
1816 start_clock = sched_clock();
1817 ret = static_call(x86_pmu_handle_irq)(regs);
1818 finish_clock = sched_clock();
1819
1820 perf_sample_event_took(finish_clock - start_clock);
1821
1822 return ret;
1823 }
1824 NOKPROBE_SYMBOL(perf_event_nmi_handler);
1825
1826 struct event_constraint emptyconstraint;
1827 struct event_constraint unconstrained;
1828
x86_pmu_prepare_cpu(unsigned int cpu)1829 static int x86_pmu_prepare_cpu(unsigned int cpu)
1830 {
1831 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1832 int i;
1833
1834 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++)
1835 cpuc->kfree_on_online[i] = NULL;
1836 if (x86_pmu.cpu_prepare)
1837 return x86_pmu.cpu_prepare(cpu);
1838 return 0;
1839 }
1840
x86_pmu_dead_cpu(unsigned int cpu)1841 static int x86_pmu_dead_cpu(unsigned int cpu)
1842 {
1843 if (x86_pmu.cpu_dead)
1844 x86_pmu.cpu_dead(cpu);
1845 return 0;
1846 }
1847
x86_pmu_online_cpu(unsigned int cpu)1848 static int x86_pmu_online_cpu(unsigned int cpu)
1849 {
1850 struct cpu_hw_events *cpuc = &per_cpu(cpu_hw_events, cpu);
1851 int i;
1852
1853 for (i = 0 ; i < X86_PERF_KFREE_MAX; i++) {
1854 kfree(cpuc->kfree_on_online[i]);
1855 cpuc->kfree_on_online[i] = NULL;
1856 }
1857 return 0;
1858 }
1859
x86_pmu_starting_cpu(unsigned int cpu)1860 static int x86_pmu_starting_cpu(unsigned int cpu)
1861 {
1862 if (x86_pmu.cpu_starting)
1863 x86_pmu.cpu_starting(cpu);
1864 return 0;
1865 }
1866
x86_pmu_dying_cpu(unsigned int cpu)1867 static int x86_pmu_dying_cpu(unsigned int cpu)
1868 {
1869 if (x86_pmu.cpu_dying)
1870 x86_pmu.cpu_dying(cpu);
1871 return 0;
1872 }
1873
pmu_check_apic(void)1874 static void __init pmu_check_apic(void)
1875 {
1876 if (boot_cpu_has(X86_FEATURE_APIC))
1877 return;
1878
1879 x86_pmu.apic = 0;
1880 pr_info("no APIC, boot with the \"lapic\" boot parameter to force-enable it.\n");
1881 pr_info("no hardware sampling interrupt available.\n");
1882
1883 /*
1884 * If we have a PMU initialized but no APIC
1885 * interrupts, we cannot sample hardware
1886 * events (user-space has to fall back and
1887 * sample via a hrtimer based software event):
1888 */
1889 pmu.capabilities |= PERF_PMU_CAP_NO_INTERRUPT;
1890
1891 }
1892
1893 static struct attribute_group x86_pmu_format_group __ro_after_init = {
1894 .name = "format",
1895 .attrs = NULL,
1896 };
1897
events_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)1898 ssize_t events_sysfs_show(struct device *dev, struct device_attribute *attr, char *page)
1899 {
1900 struct perf_pmu_events_attr *pmu_attr =
1901 container_of(attr, struct perf_pmu_events_attr, attr);
1902 u64 config = 0;
1903
1904 if (pmu_attr->id < x86_pmu.max_events)
1905 config = x86_pmu.event_map(pmu_attr->id);
1906
1907 /* string trumps id */
1908 if (pmu_attr->event_str)
1909 return sprintf(page, "%s\n", pmu_attr->event_str);
1910
1911 return x86_pmu.events_sysfs_show(page, config);
1912 }
1913 EXPORT_SYMBOL_GPL(events_sysfs_show);
1914
events_ht_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)1915 ssize_t events_ht_sysfs_show(struct device *dev, struct device_attribute *attr,
1916 char *page)
1917 {
1918 struct perf_pmu_events_ht_attr *pmu_attr =
1919 container_of(attr, struct perf_pmu_events_ht_attr, attr);
1920
1921 /*
1922 * Report conditional events depending on Hyper-Threading.
1923 *
1924 * This is overly conservative as usually the HT special
1925 * handling is not needed if the other CPU thread is idle.
1926 *
1927 * Note this does not (and cannot) handle the case when thread
1928 * siblings are invisible, for example with virtualization
1929 * if they are owned by some other guest. The user tool
1930 * has to re-read when a thread sibling gets onlined later.
1931 */
1932 return sprintf(page, "%s",
1933 topology_max_smt_threads() > 1 ?
1934 pmu_attr->event_str_ht :
1935 pmu_attr->event_str_noht);
1936 }
1937
events_hybrid_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)1938 ssize_t events_hybrid_sysfs_show(struct device *dev,
1939 struct device_attribute *attr,
1940 char *page)
1941 {
1942 struct perf_pmu_events_hybrid_attr *pmu_attr =
1943 container_of(attr, struct perf_pmu_events_hybrid_attr, attr);
1944 struct x86_hybrid_pmu *pmu;
1945 const char *str, *next_str;
1946 int i;
1947
1948 if (hweight64(pmu_attr->pmu_type) == 1)
1949 return sprintf(page, "%s", pmu_attr->event_str);
1950
1951 /*
1952 * Hybrid PMUs may support the same event name, but with different
1953 * event encoding, e.g., the mem-loads event on an Atom PMU has
1954 * different event encoding from a Core PMU.
1955 *
1956 * The event_str includes all event encodings. Each event encoding
1957 * is divided by ";". The order of the event encodings must follow
1958 * the order of the hybrid PMU index.
1959 */
1960 pmu = container_of(dev_get_drvdata(dev), struct x86_hybrid_pmu, pmu);
1961
1962 str = pmu_attr->event_str;
1963 for (i = 0; i < x86_pmu.num_hybrid_pmus; i++) {
1964 if (!(x86_pmu.hybrid_pmu[i].pmu_type & pmu_attr->pmu_type))
1965 continue;
1966 if (x86_pmu.hybrid_pmu[i].pmu_type & pmu->pmu_type) {
1967 next_str = strchr(str, ';');
1968 if (next_str)
1969 return snprintf(page, next_str - str + 1, "%s", str);
1970 else
1971 return sprintf(page, "%s", str);
1972 }
1973 str = strchr(str, ';');
1974 str++;
1975 }
1976
1977 return 0;
1978 }
1979 EXPORT_SYMBOL_GPL(events_hybrid_sysfs_show);
1980
1981 EVENT_ATTR(cpu-cycles, CPU_CYCLES );
1982 EVENT_ATTR(instructions, INSTRUCTIONS );
1983 EVENT_ATTR(cache-references, CACHE_REFERENCES );
1984 EVENT_ATTR(cache-misses, CACHE_MISSES );
1985 EVENT_ATTR(branch-instructions, BRANCH_INSTRUCTIONS );
1986 EVENT_ATTR(branch-misses, BRANCH_MISSES );
1987 EVENT_ATTR(bus-cycles, BUS_CYCLES );
1988 EVENT_ATTR(stalled-cycles-frontend, STALLED_CYCLES_FRONTEND );
1989 EVENT_ATTR(stalled-cycles-backend, STALLED_CYCLES_BACKEND );
1990 EVENT_ATTR(ref-cycles, REF_CPU_CYCLES );
1991
1992 static struct attribute *empty_attrs;
1993
1994 static struct attribute *events_attr[] = {
1995 EVENT_PTR(CPU_CYCLES),
1996 EVENT_PTR(INSTRUCTIONS),
1997 EVENT_PTR(CACHE_REFERENCES),
1998 EVENT_PTR(CACHE_MISSES),
1999 EVENT_PTR(BRANCH_INSTRUCTIONS),
2000 EVENT_PTR(BRANCH_MISSES),
2001 EVENT_PTR(BUS_CYCLES),
2002 EVENT_PTR(STALLED_CYCLES_FRONTEND),
2003 EVENT_PTR(STALLED_CYCLES_BACKEND),
2004 EVENT_PTR(REF_CPU_CYCLES),
2005 NULL,
2006 };
2007
2008 /*
2009 * Remove all undefined events (x86_pmu.event_map(id) == 0)
2010 * out of events_attr attributes.
2011 */
2012 static umode_t
is_visible(struct kobject * kobj,struct attribute * attr,int idx)2013 is_visible(struct kobject *kobj, struct attribute *attr, int idx)
2014 {
2015 struct perf_pmu_events_attr *pmu_attr;
2016
2017 if (idx >= x86_pmu.max_events)
2018 return 0;
2019
2020 pmu_attr = container_of(attr, struct perf_pmu_events_attr, attr.attr);
2021 /* str trumps id */
2022 return pmu_attr->event_str || x86_pmu.event_map(idx) ? attr->mode : 0;
2023 }
2024
2025 static struct attribute_group x86_pmu_events_group __ro_after_init = {
2026 .name = "events",
2027 .attrs = events_attr,
2028 .is_visible = is_visible,
2029 };
2030
x86_event_sysfs_show(char * page,u64 config,u64 event)2031 ssize_t x86_event_sysfs_show(char *page, u64 config, u64 event)
2032 {
2033 u64 umask = (config & ARCH_PERFMON_EVENTSEL_UMASK) >> 8;
2034 u64 cmask = (config & ARCH_PERFMON_EVENTSEL_CMASK) >> 24;
2035 bool edge = (config & ARCH_PERFMON_EVENTSEL_EDGE);
2036 bool pc = (config & ARCH_PERFMON_EVENTSEL_PIN_CONTROL);
2037 bool any = (config & ARCH_PERFMON_EVENTSEL_ANY);
2038 bool inv = (config & ARCH_PERFMON_EVENTSEL_INV);
2039 ssize_t ret;
2040
2041 /*
2042 * We have whole page size to spend and just little data
2043 * to write, so we can safely use sprintf.
2044 */
2045 ret = sprintf(page, "event=0x%02llx", event);
2046
2047 if (umask)
2048 ret += sprintf(page + ret, ",umask=0x%02llx", umask);
2049
2050 if (edge)
2051 ret += sprintf(page + ret, ",edge");
2052
2053 if (pc)
2054 ret += sprintf(page + ret, ",pc");
2055
2056 if (any)
2057 ret += sprintf(page + ret, ",any");
2058
2059 if (inv)
2060 ret += sprintf(page + ret, ",inv");
2061
2062 if (cmask)
2063 ret += sprintf(page + ret, ",cmask=0x%02llx", cmask);
2064
2065 ret += sprintf(page + ret, "\n");
2066
2067 return ret;
2068 }
2069
2070 static struct attribute_group x86_pmu_attr_group;
2071 static struct attribute_group x86_pmu_caps_group;
2072
x86_pmu_static_call_update(void)2073 static void x86_pmu_static_call_update(void)
2074 {
2075 static_call_update(x86_pmu_handle_irq, x86_pmu.handle_irq);
2076 static_call_update(x86_pmu_disable_all, x86_pmu.disable_all);
2077 static_call_update(x86_pmu_enable_all, x86_pmu.enable_all);
2078 static_call_update(x86_pmu_enable, x86_pmu.enable);
2079 static_call_update(x86_pmu_disable, x86_pmu.disable);
2080
2081 static_call_update(x86_pmu_assign, x86_pmu.assign);
2082
2083 static_call_update(x86_pmu_add, x86_pmu.add);
2084 static_call_update(x86_pmu_del, x86_pmu.del);
2085 static_call_update(x86_pmu_read, x86_pmu.read);
2086
2087 static_call_update(x86_pmu_set_period, x86_pmu.set_period);
2088 static_call_update(x86_pmu_update, x86_pmu.update);
2089 static_call_update(x86_pmu_limit_period, x86_pmu.limit_period);
2090
2091 static_call_update(x86_pmu_schedule_events, x86_pmu.schedule_events);
2092 static_call_update(x86_pmu_get_event_constraints, x86_pmu.get_event_constraints);
2093 static_call_update(x86_pmu_put_event_constraints, x86_pmu.put_event_constraints);
2094
2095 static_call_update(x86_pmu_start_scheduling, x86_pmu.start_scheduling);
2096 static_call_update(x86_pmu_commit_scheduling, x86_pmu.commit_scheduling);
2097 static_call_update(x86_pmu_stop_scheduling, x86_pmu.stop_scheduling);
2098
2099 static_call_update(x86_pmu_sched_task, x86_pmu.sched_task);
2100
2101 static_call_update(x86_pmu_drain_pebs, x86_pmu.drain_pebs);
2102 static_call_update(x86_pmu_pebs_aliases, x86_pmu.pebs_aliases);
2103
2104 static_call_update(x86_pmu_guest_get_msrs, x86_pmu.guest_get_msrs);
2105 static_call_update(x86_pmu_filter, x86_pmu.filter);
2106
2107 static_call_update(x86_pmu_late_setup, x86_pmu.late_setup);
2108
2109 static_call_update(x86_pmu_pebs_enable, x86_pmu.pebs_enable);
2110 static_call_update(x86_pmu_pebs_disable, x86_pmu.pebs_disable);
2111 static_call_update(x86_pmu_pebs_enable_all, x86_pmu.pebs_enable_all);
2112 static_call_update(x86_pmu_pebs_disable_all, x86_pmu.pebs_disable_all);
2113 }
2114
_x86_pmu_read(struct perf_event * event)2115 static void _x86_pmu_read(struct perf_event *event)
2116 {
2117 static_call(x86_pmu_update)(event);
2118 }
2119
x86_pmu_show_pmu_cap(struct pmu * pmu)2120 void x86_pmu_show_pmu_cap(struct pmu *pmu)
2121 {
2122 pr_info("... version: %d\n", x86_pmu.version);
2123 pr_info("... bit width: %d\n", x86_pmu.cntval_bits);
2124 pr_info("... generic counters: %d\n", x86_pmu_num_counters(pmu));
2125 pr_info("... generic bitmap: %016llx\n", hybrid(pmu, cntr_mask64));
2126 pr_info("... fixed-purpose counters: %d\n", x86_pmu_num_counters_fixed(pmu));
2127 pr_info("... fixed-purpose bitmap: %016llx\n", hybrid(pmu, fixed_cntr_mask64));
2128 pr_info("... value mask: %016llx\n", x86_pmu.cntval_mask);
2129 pr_info("... max period: %016llx\n", x86_pmu.max_period);
2130 pr_info("... global_ctrl mask: %016llx\n", hybrid(pmu, intel_ctrl));
2131 }
2132
init_hw_perf_events(void)2133 static int __init init_hw_perf_events(void)
2134 {
2135 struct x86_pmu_quirk *quirk;
2136 int err;
2137
2138 pr_info("Performance Events: ");
2139
2140 switch (boot_cpu_data.x86_vendor) {
2141 case X86_VENDOR_INTEL:
2142 err = intel_pmu_init();
2143 break;
2144 case X86_VENDOR_AMD:
2145 err = amd_pmu_init();
2146 break;
2147 case X86_VENDOR_HYGON:
2148 err = amd_pmu_init();
2149 x86_pmu.name = "HYGON";
2150 break;
2151 case X86_VENDOR_ZHAOXIN:
2152 case X86_VENDOR_CENTAUR:
2153 err = zhaoxin_pmu_init();
2154 break;
2155 default:
2156 err = -ENOTSUPP;
2157 }
2158 if (err != 0) {
2159 pr_cont("no PMU driver, software events only.\n");
2160 err = 0;
2161 goto out_bad_pmu;
2162 }
2163
2164 pmu_check_apic();
2165
2166 /* sanity check that the hardware exists or is emulated */
2167 if (!check_hw_exists(&pmu, x86_pmu.cntr_mask, x86_pmu.fixed_cntr_mask))
2168 goto out_bad_pmu;
2169
2170 pr_cont("%s PMU driver.\n", x86_pmu.name);
2171
2172 /* enable userspace RDPMC usage by default */
2173 x86_pmu.attr_rdpmc = X86_USER_RDPMC_CONDITIONAL_ENABLE;
2174
2175 for (quirk = x86_pmu.quirks; quirk; quirk = quirk->next)
2176 quirk->func();
2177
2178 if (!x86_pmu.intel_ctrl)
2179 x86_pmu.intel_ctrl = x86_pmu.cntr_mask64;
2180
2181 if (!x86_pmu.config_mask)
2182 x86_pmu.config_mask = X86_RAW_EVENT_MASK;
2183
2184 perf_events_lapic_init();
2185 register_nmi_handler(NMI_LOCAL, perf_event_nmi_handler, 0, "PMI");
2186
2187 unconstrained = (struct event_constraint)
2188 __EVENT_CONSTRAINT(0, x86_pmu.cntr_mask64,
2189 0, x86_pmu_num_counters(NULL), 0, 0);
2190
2191 x86_pmu_format_group.attrs = x86_pmu.format_attrs;
2192
2193 if (!x86_pmu.events_sysfs_show)
2194 x86_pmu_events_group.attrs = &empty_attrs;
2195
2196 pmu.attr_update = x86_pmu.attr_update;
2197
2198 if (!is_hybrid())
2199 x86_pmu_show_pmu_cap(NULL);
2200
2201 if (!x86_pmu.read)
2202 x86_pmu.read = _x86_pmu_read;
2203
2204 if (!x86_pmu.guest_get_msrs)
2205 x86_pmu.guest_get_msrs = (void *)&__static_call_return0;
2206
2207 if (!x86_pmu.set_period)
2208 x86_pmu.set_period = x86_perf_event_set_period;
2209
2210 if (!x86_pmu.update)
2211 x86_pmu.update = x86_perf_event_update;
2212
2213 x86_pmu_static_call_update();
2214
2215 /*
2216 * Install callbacks. Core will call them for each online
2217 * cpu.
2218 */
2219 err = cpuhp_setup_state(CPUHP_PERF_X86_PREPARE, "perf/x86:prepare",
2220 x86_pmu_prepare_cpu, x86_pmu_dead_cpu);
2221 if (err)
2222 return err;
2223
2224 err = cpuhp_setup_state(CPUHP_AP_PERF_X86_STARTING,
2225 "perf/x86:starting", x86_pmu_starting_cpu,
2226 x86_pmu_dying_cpu);
2227 if (err)
2228 goto out;
2229
2230 err = cpuhp_setup_state(CPUHP_AP_PERF_X86_ONLINE, "perf/x86:online",
2231 x86_pmu_online_cpu, NULL);
2232 if (err)
2233 goto out1;
2234
2235 if (!is_hybrid()) {
2236 err = perf_pmu_register(&pmu, "cpu", PERF_TYPE_RAW);
2237 if (err)
2238 goto out2;
2239 } else {
2240 struct x86_hybrid_pmu *hybrid_pmu;
2241 int i, j;
2242
2243 for (i = 0; i < x86_pmu.num_hybrid_pmus; i++) {
2244 hybrid_pmu = &x86_pmu.hybrid_pmu[i];
2245
2246 hybrid_pmu->pmu = pmu;
2247 hybrid_pmu->pmu.type = -1;
2248 hybrid_pmu->pmu.attr_update = x86_pmu.attr_update;
2249 hybrid_pmu->pmu.capabilities |= PERF_PMU_CAP_EXTENDED_HW_TYPE;
2250
2251 err = perf_pmu_register(&hybrid_pmu->pmu, hybrid_pmu->name,
2252 (hybrid_pmu->pmu_type == hybrid_big) ? PERF_TYPE_RAW : -1);
2253 if (err)
2254 break;
2255 }
2256
2257 if (i < x86_pmu.num_hybrid_pmus) {
2258 for (j = 0; j < i; j++)
2259 perf_pmu_unregister(&x86_pmu.hybrid_pmu[j].pmu);
2260 pr_warn("Failed to register hybrid PMUs\n");
2261 kfree(x86_pmu.hybrid_pmu);
2262 x86_pmu.hybrid_pmu = NULL;
2263 x86_pmu.num_hybrid_pmus = 0;
2264 goto out2;
2265 }
2266 }
2267
2268 return 0;
2269
2270 out2:
2271 cpuhp_remove_state(CPUHP_AP_PERF_X86_ONLINE);
2272 out1:
2273 cpuhp_remove_state(CPUHP_AP_PERF_X86_STARTING);
2274 out:
2275 cpuhp_remove_state(CPUHP_PERF_X86_PREPARE);
2276 out_bad_pmu:
2277 memset(&x86_pmu, 0, sizeof(x86_pmu));
2278 return err;
2279 }
2280 early_initcall(init_hw_perf_events);
2281
x86_pmu_read(struct perf_event * event)2282 static void x86_pmu_read(struct perf_event *event)
2283 {
2284 static_call(x86_pmu_read)(event);
2285 }
2286
2287 /*
2288 * Start group events scheduling transaction
2289 * Set the flag to make pmu::enable() not perform the
2290 * schedulability test, it will be performed at commit time
2291 *
2292 * We only support PERF_PMU_TXN_ADD transactions. Save the
2293 * transaction flags but otherwise ignore non-PERF_PMU_TXN_ADD
2294 * transactions.
2295 */
x86_pmu_start_txn(struct pmu * pmu,unsigned int txn_flags)2296 static void x86_pmu_start_txn(struct pmu *pmu, unsigned int txn_flags)
2297 {
2298 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2299
2300 WARN_ON_ONCE(cpuc->txn_flags); /* txn already in flight */
2301
2302 cpuc->txn_flags = txn_flags;
2303 if (txn_flags & ~PERF_PMU_TXN_ADD)
2304 return;
2305
2306 perf_pmu_disable(pmu);
2307 __this_cpu_write(cpu_hw_events.n_txn, 0);
2308 __this_cpu_write(cpu_hw_events.n_txn_pair, 0);
2309 __this_cpu_write(cpu_hw_events.n_txn_metric, 0);
2310 }
2311
2312 /*
2313 * Stop group events scheduling transaction
2314 * Clear the flag and pmu::enable() will perform the
2315 * schedulability test.
2316 */
x86_pmu_cancel_txn(struct pmu * pmu)2317 static void x86_pmu_cancel_txn(struct pmu *pmu)
2318 {
2319 unsigned int txn_flags;
2320 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2321
2322 WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
2323
2324 txn_flags = cpuc->txn_flags;
2325 cpuc->txn_flags = 0;
2326 if (txn_flags & ~PERF_PMU_TXN_ADD)
2327 return;
2328
2329 /*
2330 * Truncate collected array by the number of events added in this
2331 * transaction. See x86_pmu_add() and x86_pmu_*_txn().
2332 */
2333 __this_cpu_sub(cpu_hw_events.n_added, __this_cpu_read(cpu_hw_events.n_txn));
2334 __this_cpu_sub(cpu_hw_events.n_events, __this_cpu_read(cpu_hw_events.n_txn));
2335 __this_cpu_sub(cpu_hw_events.n_pair, __this_cpu_read(cpu_hw_events.n_txn_pair));
2336 __this_cpu_sub(cpu_hw_events.n_metric, __this_cpu_read(cpu_hw_events.n_txn_metric));
2337 perf_pmu_enable(pmu);
2338 }
2339
2340 /*
2341 * Commit group events scheduling transaction
2342 * Perform the group schedulability test as a whole
2343 * Return 0 if success
2344 *
2345 * Does not cancel the transaction on failure; expects the caller to do this.
2346 */
x86_pmu_commit_txn(struct pmu * pmu)2347 static int x86_pmu_commit_txn(struct pmu *pmu)
2348 {
2349 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2350 int assign[X86_PMC_IDX_MAX];
2351 int n, ret;
2352
2353 WARN_ON_ONCE(!cpuc->txn_flags); /* no txn in flight */
2354
2355 if (cpuc->txn_flags & ~PERF_PMU_TXN_ADD) {
2356 cpuc->txn_flags = 0;
2357 return 0;
2358 }
2359
2360 n = cpuc->n_events;
2361
2362 if (!x86_pmu_initialized())
2363 return -EAGAIN;
2364
2365 ret = static_call(x86_pmu_schedule_events)(cpuc, n, assign);
2366 if (ret)
2367 return ret;
2368
2369 /*
2370 * copy new assignment, now we know it is possible
2371 * will be used by hw_perf_enable()
2372 */
2373 memcpy(cpuc->assign, assign, n*sizeof(int));
2374
2375 cpuc->txn_flags = 0;
2376 perf_pmu_enable(pmu);
2377 return 0;
2378 }
2379 /*
2380 * a fake_cpuc is used to validate event groups. Due to
2381 * the extra reg logic, we need to also allocate a fake
2382 * per_core and per_cpu structure. Otherwise, group events
2383 * using extra reg may conflict without the kernel being
2384 * able to catch this when the last event gets added to
2385 * the group.
2386 */
free_fake_cpuc(struct cpu_hw_events * cpuc)2387 static void free_fake_cpuc(struct cpu_hw_events *cpuc)
2388 {
2389 intel_cpuc_finish(cpuc);
2390 kfree(cpuc);
2391 }
2392
allocate_fake_cpuc(struct pmu * event_pmu)2393 static struct cpu_hw_events *allocate_fake_cpuc(struct pmu *event_pmu)
2394 {
2395 struct cpu_hw_events *cpuc;
2396 int cpu;
2397
2398 cpuc = kzalloc_obj(*cpuc);
2399 if (!cpuc)
2400 return ERR_PTR(-ENOMEM);
2401 cpuc->is_fake = 1;
2402
2403 if (is_hybrid()) {
2404 struct x86_hybrid_pmu *h_pmu;
2405
2406 h_pmu = hybrid_pmu(event_pmu);
2407 if (cpumask_empty(&h_pmu->supported_cpus))
2408 goto error;
2409 cpu = cpumask_first(&h_pmu->supported_cpus);
2410 } else
2411 cpu = raw_smp_processor_id();
2412 cpuc->pmu = event_pmu;
2413
2414 if (intel_cpuc_prepare(cpuc, cpu))
2415 goto error;
2416
2417 return cpuc;
2418 error:
2419 free_fake_cpuc(cpuc);
2420 return ERR_PTR(-ENOMEM);
2421 }
2422
2423 /*
2424 * validate that we can schedule this event
2425 */
validate_event(struct perf_event * event)2426 static int validate_event(struct perf_event *event)
2427 {
2428 struct cpu_hw_events *fake_cpuc;
2429 struct event_constraint *c;
2430 int ret = 0;
2431
2432 fake_cpuc = allocate_fake_cpuc(event->pmu);
2433 if (IS_ERR(fake_cpuc))
2434 return PTR_ERR(fake_cpuc);
2435
2436 c = x86_pmu.get_event_constraints(fake_cpuc, 0, event);
2437
2438 if (!c || !c->weight)
2439 ret = -EINVAL;
2440
2441 if (x86_pmu.put_event_constraints)
2442 x86_pmu.put_event_constraints(fake_cpuc, event);
2443
2444 free_fake_cpuc(fake_cpuc);
2445
2446 return ret;
2447 }
2448
2449 /*
2450 * validate a single event group
2451 *
2452 * validation include:
2453 * - check events are compatible which each other
2454 * - events do not compete for the same counter
2455 * - number of events <= number of counters
2456 *
2457 * validation ensures the group can be loaded onto the
2458 * PMU if it was the only group available.
2459 */
validate_group(struct perf_event * event)2460 static int validate_group(struct perf_event *event)
2461 {
2462 struct perf_event *leader = event->group_leader;
2463 struct cpu_hw_events *fake_cpuc;
2464 int ret = -EINVAL, n;
2465
2466 /*
2467 * Reject events from different hybrid PMUs.
2468 */
2469 if (is_hybrid()) {
2470 struct perf_event *sibling;
2471 struct pmu *pmu = NULL;
2472
2473 if (is_x86_event(leader))
2474 pmu = leader->pmu;
2475
2476 for_each_sibling_event(sibling, leader) {
2477 if (!is_x86_event(sibling))
2478 continue;
2479 if (!pmu)
2480 pmu = sibling->pmu;
2481 else if (pmu != sibling->pmu)
2482 return ret;
2483 }
2484 }
2485
2486 fake_cpuc = allocate_fake_cpuc(event->pmu);
2487 if (IS_ERR(fake_cpuc))
2488 return PTR_ERR(fake_cpuc);
2489 /*
2490 * the event is not yet connected with its
2491 * siblings therefore we must first collect
2492 * existing siblings, then add the new event
2493 * before we can simulate the scheduling
2494 */
2495 n = collect_events(fake_cpuc, leader, true);
2496 if (n < 0)
2497 goto out;
2498
2499 fake_cpuc->n_events = n;
2500 n = collect_events(fake_cpuc, event, false);
2501 if (n < 0)
2502 goto out;
2503
2504 fake_cpuc->n_events = 0;
2505 ret = x86_pmu.schedule_events(fake_cpuc, n, NULL);
2506
2507 out:
2508 free_fake_cpuc(fake_cpuc);
2509 return ret;
2510 }
2511
x86_pmu_event_init(struct perf_event * event)2512 static int x86_pmu_event_init(struct perf_event *event)
2513 {
2514 struct x86_hybrid_pmu *pmu = NULL;
2515 int err;
2516
2517 if ((event->attr.type != event->pmu->type) &&
2518 (event->attr.type != PERF_TYPE_HARDWARE) &&
2519 (event->attr.type != PERF_TYPE_HW_CACHE))
2520 return -ENOENT;
2521
2522 if (is_hybrid() && (event->cpu != -1)) {
2523 pmu = hybrid_pmu(event->pmu);
2524 if (!cpumask_test_cpu(event->cpu, &pmu->supported_cpus))
2525 return -ENOENT;
2526 }
2527
2528 err = __x86_pmu_event_init(event);
2529 if (!err) {
2530 if (event->group_leader != event)
2531 err = validate_group(event);
2532 else
2533 err = validate_event(event);
2534 }
2535 if (err) {
2536 if (event->destroy)
2537 event->destroy(event);
2538 event->destroy = NULL;
2539 }
2540
2541 if (READ_ONCE(x86_pmu.attr_rdpmc) &&
2542 !(event->hw.flags & PERF_X86_EVENT_LARGE_PEBS))
2543 event->hw.flags |= PERF_EVENT_FLAG_USER_READ_CNT;
2544
2545 return err;
2546 }
2547
perf_clear_dirty_counters(void)2548 void perf_clear_dirty_counters(void)
2549 {
2550 struct cpu_hw_events *cpuc = this_cpu_ptr(&cpu_hw_events);
2551 int i;
2552
2553 /* Don't need to clear the assigned counter. */
2554 for (i = 0; i < cpuc->n_events; i++)
2555 __clear_bit(cpuc->assign[i], cpuc->dirty);
2556
2557 if (bitmap_empty(cpuc->dirty, X86_PMC_IDX_MAX))
2558 return;
2559
2560 for_each_set_bit(i, cpuc->dirty, X86_PMC_IDX_MAX) {
2561 if (i >= INTEL_PMC_IDX_FIXED) {
2562 /* Metrics and fake events don't have corresponding HW counters. */
2563 if (!test_bit(i - INTEL_PMC_IDX_FIXED, hybrid(cpuc->pmu, fixed_cntr_mask)))
2564 continue;
2565
2566 wrmsrq(x86_pmu_fixed_ctr_addr(i - INTEL_PMC_IDX_FIXED), 0);
2567 } else {
2568 wrmsrq(x86_pmu_event_addr(i), 0);
2569 }
2570 }
2571
2572 bitmap_zero(cpuc->dirty, X86_PMC_IDX_MAX);
2573 }
2574
x86_pmu_event_mapped(struct perf_event * event,struct mm_struct * mm)2575 static void x86_pmu_event_mapped(struct perf_event *event, struct mm_struct *mm)
2576 {
2577 if (!(event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT))
2578 return;
2579
2580 /*
2581 * This function relies on not being called concurrently in two
2582 * tasks in the same mm. Otherwise one task could observe
2583 * perf_rdpmc_allowed > 1 and return all the way back to
2584 * userspace with CR4.PCE clear while another task is still
2585 * doing on_each_cpu_mask() to propagate CR4.PCE.
2586 *
2587 * For now, this can't happen because all callers hold mmap_lock
2588 * for write. If this changes, we'll need a different solution.
2589 */
2590 mmap_assert_write_locked(mm);
2591
2592 if (atomic_inc_return(&mm->context.perf_rdpmc_allowed) == 1)
2593 on_each_cpu_mask(mm_cpumask(mm), cr4_update_pce, NULL, 1);
2594 }
2595
x86_pmu_event_unmapped(struct perf_event * event,struct mm_struct * mm)2596 static void x86_pmu_event_unmapped(struct perf_event *event, struct mm_struct *mm)
2597 {
2598 if (!(event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT))
2599 return;
2600
2601 if (atomic_dec_and_test(&mm->context.perf_rdpmc_allowed))
2602 on_each_cpu_mask(mm_cpumask(mm), cr4_update_pce, NULL, 1);
2603 }
2604
x86_pmu_event_idx(struct perf_event * event)2605 static int x86_pmu_event_idx(struct perf_event *event)
2606 {
2607 struct hw_perf_event *hwc = &event->hw;
2608
2609 if (!(hwc->flags & PERF_EVENT_FLAG_USER_READ_CNT))
2610 return 0;
2611
2612 if (is_metric_idx(hwc->idx))
2613 return INTEL_PMC_FIXED_RDPMC_METRICS + 1;
2614 else
2615 return hwc->event_base_rdpmc + 1;
2616 }
2617
get_attr_rdpmc(struct device * cdev,struct device_attribute * attr,char * buf)2618 static ssize_t get_attr_rdpmc(struct device *cdev,
2619 struct device_attribute *attr,
2620 char *buf)
2621 {
2622 return snprintf(buf, 40, "%d\n", x86_pmu.attr_rdpmc);
2623 }
2624
2625 /*
2626 * Behaviors of rdpmc value:
2627 * - rdpmc = 0
2628 * global user space rdpmc and counter level's user space rdpmc of all
2629 * counters are both disabled.
2630 * - rdpmc = 1
2631 * global user space rdpmc is enabled in mmap enabled time window and
2632 * counter level's user space rdpmc is enabled for only non system-wide
2633 * events. Counter level's user space rdpmc of system-wide events is
2634 * still disabled by default. This won't introduce counter data leak for
2635 * non system-wide events since their count data would be cleared when
2636 * context switches.
2637 * - rdpmc = 2
2638 * global user space rdpmc and counter level's user space rdpmc of all
2639 * counters are enabled unconditionally.
2640 *
2641 * Suppose the rdpmc value won't be changed frequently, don't dynamically
2642 * reschedule events to make the new rpdmc value take effect on active perf
2643 * events immediately, the new rdpmc value would only impact the new
2644 * activated perf events. This makes code simpler and cleaner.
2645 */
set_attr_rdpmc(struct device * cdev,struct device_attribute * attr,const char * buf,size_t count)2646 static ssize_t set_attr_rdpmc(struct device *cdev,
2647 struct device_attribute *attr,
2648 const char *buf, size_t count)
2649 {
2650 static DEFINE_MUTEX(rdpmc_mutex);
2651 unsigned long val;
2652 ssize_t ret;
2653
2654 ret = kstrtoul(buf, 0, &val);
2655 if (ret)
2656 return ret;
2657
2658 if (val > 2)
2659 return -EINVAL;
2660
2661 if (x86_pmu.attr_rdpmc_broken)
2662 return -ENOTSUPP;
2663
2664 guard(mutex)(&rdpmc_mutex);
2665
2666 if (val != x86_pmu.attr_rdpmc) {
2667 /*
2668 * Changing into or out of never available or always available,
2669 * aka perf-event-bypassing mode. This path is extremely slow,
2670 * but only root can trigger it, so it's okay.
2671 */
2672 if (val == 0)
2673 static_branch_inc(&rdpmc_never_available_key);
2674 else if (x86_pmu.attr_rdpmc == X86_USER_RDPMC_NEVER_ENABLE)
2675 static_branch_dec(&rdpmc_never_available_key);
2676
2677 if (val == 2)
2678 static_branch_inc(&rdpmc_always_available_key);
2679 else if (x86_pmu.attr_rdpmc == X86_USER_RDPMC_ALWAYS_ENABLE)
2680 static_branch_dec(&rdpmc_always_available_key);
2681
2682 on_each_cpu(cr4_update_pce, NULL, 1);
2683 x86_pmu.attr_rdpmc = val;
2684 }
2685
2686 return count;
2687 }
2688
2689 static DEVICE_ATTR(rdpmc, S_IRUSR | S_IWUSR, get_attr_rdpmc, set_attr_rdpmc);
2690
2691 static struct attribute *x86_pmu_attrs[] = {
2692 &dev_attr_rdpmc.attr,
2693 NULL,
2694 };
2695
2696 static struct attribute_group x86_pmu_attr_group __ro_after_init = {
2697 .attrs = x86_pmu_attrs,
2698 };
2699
max_precise_show(struct device * cdev,struct device_attribute * attr,char * buf)2700 static ssize_t max_precise_show(struct device *cdev,
2701 struct device_attribute *attr,
2702 char *buf)
2703 {
2704 struct pmu *pmu = dev_get_drvdata(cdev);
2705
2706 return snprintf(buf, PAGE_SIZE, "%d\n", x86_pmu_max_precise(pmu));
2707 }
2708
2709 static DEVICE_ATTR_RO(max_precise);
2710
2711 static struct attribute *x86_pmu_caps_attrs[] = {
2712 &dev_attr_max_precise.attr,
2713 NULL
2714 };
2715
2716 static struct attribute_group x86_pmu_caps_group __ro_after_init = {
2717 .name = "caps",
2718 .attrs = x86_pmu_caps_attrs,
2719 };
2720
2721 static const struct attribute_group *x86_pmu_attr_groups[] = {
2722 &x86_pmu_attr_group,
2723 &x86_pmu_format_group,
2724 &x86_pmu_events_group,
2725 &x86_pmu_caps_group,
2726 NULL,
2727 };
2728
x86_pmu_sched_task(struct perf_event_pmu_context * pmu_ctx,struct task_struct * task,bool sched_in)2729 static void x86_pmu_sched_task(struct perf_event_pmu_context *pmu_ctx,
2730 struct task_struct *task, bool sched_in)
2731 {
2732 static_call_cond(x86_pmu_sched_task)(pmu_ctx, task, sched_in);
2733 }
2734
perf_check_microcode(void)2735 void perf_check_microcode(void)
2736 {
2737 if (x86_pmu.check_microcode)
2738 x86_pmu.check_microcode();
2739 }
2740
x86_pmu_check_period(struct perf_event * event,u64 value)2741 static int x86_pmu_check_period(struct perf_event *event, u64 value)
2742 {
2743 if (x86_pmu.check_period && x86_pmu.check_period(event, value))
2744 return -EINVAL;
2745
2746 if (value && x86_pmu.limit_period) {
2747 s64 left = value;
2748 x86_pmu.limit_period(event, &left);
2749 if (left > value)
2750 return -EINVAL;
2751 }
2752
2753 return 0;
2754 }
2755
x86_pmu_aux_output_match(struct perf_event * event)2756 static int x86_pmu_aux_output_match(struct perf_event *event)
2757 {
2758 if (!(pmu.capabilities & PERF_PMU_CAP_AUX_OUTPUT))
2759 return 0;
2760
2761 if (x86_pmu.aux_output_match)
2762 return x86_pmu.aux_output_match(event);
2763
2764 return 0;
2765 }
2766
x86_pmu_filter(struct pmu * pmu,int cpu)2767 static bool x86_pmu_filter(struct pmu *pmu, int cpu)
2768 {
2769 bool ret = false;
2770
2771 static_call_cond(x86_pmu_filter)(pmu, cpu, &ret);
2772
2773 return ret;
2774 }
2775
2776 static struct pmu pmu = {
2777 .pmu_enable = x86_pmu_enable,
2778 .pmu_disable = x86_pmu_disable,
2779
2780 .attr_groups = x86_pmu_attr_groups,
2781
2782 .event_init = x86_pmu_event_init,
2783
2784 .event_mapped = x86_pmu_event_mapped,
2785 .event_unmapped = x86_pmu_event_unmapped,
2786
2787 .add = x86_pmu_add,
2788 .del = x86_pmu_del,
2789 .start = x86_pmu_start,
2790 .stop = x86_pmu_stop,
2791 .read = x86_pmu_read,
2792
2793 .start_txn = x86_pmu_start_txn,
2794 .cancel_txn = x86_pmu_cancel_txn,
2795 .commit_txn = x86_pmu_commit_txn,
2796
2797 .event_idx = x86_pmu_event_idx,
2798 .sched_task = x86_pmu_sched_task,
2799 .check_period = x86_pmu_check_period,
2800
2801 .aux_output_match = x86_pmu_aux_output_match,
2802
2803 .filter = x86_pmu_filter,
2804 };
2805
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)2806 void arch_perf_update_userpage(struct perf_event *event,
2807 struct perf_event_mmap_page *userpg, u64 now)
2808 {
2809 struct cyc2ns_data data;
2810 u64 offset;
2811
2812 userpg->cap_user_time = 0;
2813 userpg->cap_user_time_zero = 0;
2814 userpg->cap_user_rdpmc =
2815 !!(event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT);
2816 userpg->pmc_width = x86_pmu.cntval_bits;
2817
2818 if (!using_native_sched_clock() || !sched_clock_stable())
2819 return;
2820
2821 cyc2ns_read_begin(&data);
2822
2823 offset = data.cyc2ns_offset + __sched_clock_offset;
2824
2825 /*
2826 * Internal timekeeping for enabled/running/stopped times
2827 * is always in the local_clock domain.
2828 */
2829 userpg->cap_user_time = 1;
2830 userpg->time_mult = data.cyc2ns_mul;
2831 userpg->time_shift = data.cyc2ns_shift;
2832 userpg->time_offset = offset - now;
2833
2834 /*
2835 * cap_user_time_zero doesn't make sense when we're using a different
2836 * time base for the records.
2837 */
2838 if (!event->attr.use_clockid) {
2839 userpg->cap_user_time_zero = 1;
2840 userpg->time_zero = offset;
2841 }
2842
2843 cyc2ns_read_end();
2844 }
2845
2846 /*
2847 * Determine whether the regs were taken from an irq/exception handler rather
2848 * than from perf_arch_fetch_caller_regs().
2849 */
perf_hw_regs(struct pt_regs * regs)2850 static bool perf_hw_regs(struct pt_regs *regs)
2851 {
2852 return regs->flags & X86_EFLAGS_FIXED;
2853 }
2854
2855 void
perf_callchain_kernel(struct perf_callchain_entry_ctx * entry,struct pt_regs * regs)2856 perf_callchain_kernel(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs)
2857 {
2858 struct unwind_state state;
2859 unsigned long addr;
2860
2861 if (perf_guest_state()) {
2862 /* TODO: We don't support guest os callchain now */
2863 return;
2864 }
2865
2866 if (perf_hw_regs(regs)) {
2867 if (perf_callchain_store(entry, regs->ip))
2868 return;
2869 unwind_start(&state, current, regs, NULL);
2870 } else {
2871 unwind_start(&state, current, NULL, (void *)regs->sp);
2872 }
2873
2874 for (; !unwind_done(&state); unwind_next_frame(&state)) {
2875 addr = unwind_get_return_address(&state);
2876 if (!addr || perf_callchain_store(entry, addr))
2877 return;
2878 }
2879 }
2880
2881 static inline int
valid_user_frame(const void __user * fp,unsigned long size)2882 valid_user_frame(const void __user *fp, unsigned long size)
2883 {
2884 return __access_ok(fp, size);
2885 }
2886
get_segment_base(unsigned int segment)2887 static unsigned long get_segment_base(unsigned int segment)
2888 {
2889 struct desc_struct *desc;
2890 unsigned int idx = segment >> 3;
2891
2892 if ((segment & SEGMENT_TI_MASK) == SEGMENT_LDT) {
2893 #ifdef CONFIG_MODIFY_LDT_SYSCALL
2894 struct ldt_struct *ldt;
2895
2896 /*
2897 * If we're not in a valid context with a real (not just lazy)
2898 * user mm, then don't even try.
2899 */
2900 if (!nmi_uaccess_okay())
2901 return 0;
2902
2903 /* IRQs are off, so this synchronizes with smp_store_release */
2904 ldt = smp_load_acquire(¤t->mm->context.ldt);
2905 if (!ldt || idx >= ldt->nr_entries)
2906 return 0;
2907
2908 desc = &ldt->entries[idx];
2909 #else
2910 return 0;
2911 #endif
2912 } else {
2913 if (idx >= GDT_ENTRIES)
2914 return 0;
2915
2916 desc = raw_cpu_ptr(gdt_page.gdt) + idx;
2917 }
2918
2919 return get_desc_base(desc);
2920 }
2921
2922 #ifdef CONFIG_IA32_EMULATION
2923
2924 #include <linux/compat.h>
2925
2926 static inline int
perf_callchain_user32(struct pt_regs * regs,struct perf_callchain_entry_ctx * entry)2927 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry_ctx *entry)
2928 {
2929 /* 32-bit process in 64-bit kernel. */
2930 unsigned long ss_base, cs_base;
2931 struct stack_frame_ia32 frame;
2932 const struct stack_frame_ia32 __user *fp;
2933 u32 ret_addr;
2934
2935 if (user_64bit_mode(regs))
2936 return 0;
2937
2938 cs_base = get_segment_base(regs->cs);
2939 ss_base = get_segment_base(regs->ss);
2940
2941 fp = compat_ptr(ss_base + regs->bp);
2942 pagefault_disable();
2943
2944 /* see perf_callchain_user() below for why we do this */
2945 if (is_uprobe_at_func_entry(regs) &&
2946 !get_user(ret_addr, (const u32 __user *)regs->sp))
2947 perf_callchain_store(entry, ret_addr);
2948
2949 while (entry->nr < entry->max_stack) {
2950 if (!valid_user_frame(fp, sizeof(frame)))
2951 break;
2952
2953 if (__get_user(frame.next_frame, &fp->next_frame))
2954 break;
2955 if (__get_user(frame.return_address, &fp->return_address))
2956 break;
2957
2958 perf_callchain_store(entry, cs_base + frame.return_address);
2959 fp = compat_ptr(ss_base + frame.next_frame);
2960 }
2961 pagefault_enable();
2962 return 1;
2963 }
2964 #else
2965 static inline int
perf_callchain_user32(struct pt_regs * regs,struct perf_callchain_entry_ctx * entry)2966 perf_callchain_user32(struct pt_regs *regs, struct perf_callchain_entry_ctx *entry)
2967 {
2968 return 0;
2969 }
2970 #endif
2971
2972 void
perf_callchain_user(struct perf_callchain_entry_ctx * entry,struct pt_regs * regs)2973 perf_callchain_user(struct perf_callchain_entry_ctx *entry, struct pt_regs *regs)
2974 {
2975 struct stack_frame frame;
2976 const struct stack_frame __user *fp;
2977 unsigned long ret_addr;
2978
2979 if (perf_guest_state()) {
2980 /* TODO: We don't support guest os callchain now */
2981 return;
2982 }
2983
2984 /*
2985 * We don't know what to do with VM86 stacks.. ignore them for now.
2986 */
2987 if (regs->flags & (X86_VM_MASK | PERF_EFLAGS_VM))
2988 return;
2989
2990 fp = (void __user *)regs->bp;
2991
2992 perf_callchain_store(entry, regs->ip);
2993
2994 if (!nmi_uaccess_okay())
2995 return;
2996
2997 if (perf_callchain_user32(regs, entry))
2998 return;
2999
3000 pagefault_disable();
3001
3002 /*
3003 * If we are called from uprobe handler, and we are indeed at the very
3004 * entry to user function (which is normally a `push %rbp` instruction,
3005 * under assumption of application being compiled with frame pointers),
3006 * we should read return address from *regs->sp before proceeding
3007 * to follow frame pointers, otherwise we'll skip immediate caller
3008 * as %rbp is not yet setup.
3009 */
3010 if (is_uprobe_at_func_entry(regs) &&
3011 !get_user(ret_addr, (const unsigned long __user *)regs->sp))
3012 perf_callchain_store(entry, ret_addr);
3013
3014 while (entry->nr < entry->max_stack) {
3015 if (!valid_user_frame(fp, sizeof(frame)))
3016 break;
3017
3018 if (__get_user(frame.next_frame, &fp->next_frame))
3019 break;
3020 if (__get_user(frame.return_address, &fp->return_address))
3021 break;
3022
3023 perf_callchain_store(entry, frame.return_address);
3024 fp = (void __user *)frame.next_frame;
3025 }
3026 pagefault_enable();
3027 }
3028
3029 /*
3030 * Deal with code segment offsets for the various execution modes:
3031 *
3032 * VM86 - the good olde 16 bit days, where the linear address is
3033 * 20 bits and we use regs->ip + 0x10 * regs->cs.
3034 *
3035 * IA32 - Where we need to look at GDT/LDT segment descriptor tables
3036 * to figure out what the 32bit base address is.
3037 *
3038 * X32 - has TIF_X32 set, but is running in x86_64
3039 *
3040 * X86_64 - CS,DS,SS,ES are all zero based.
3041 */
code_segment_base(struct pt_regs * regs)3042 static unsigned long code_segment_base(struct pt_regs *regs)
3043 {
3044 /*
3045 * For IA32 we look at the GDT/LDT segment base to convert the
3046 * effective IP to a linear address.
3047 */
3048
3049 #ifdef CONFIG_X86_32
3050 /*
3051 * If we are in VM86 mode, add the segment offset to convert to a
3052 * linear address.
3053 */
3054 if (regs->flags & X86_VM_MASK)
3055 return 0x10 * regs->cs;
3056
3057 if (user_mode(regs) && regs->cs != __USER_CS)
3058 return get_segment_base(regs->cs);
3059 #else
3060 if (user_mode(regs) && !user_64bit_mode(regs) &&
3061 regs->cs != __USER32_CS)
3062 return get_segment_base(regs->cs);
3063 #endif
3064 return 0;
3065 }
3066
perf_arch_instruction_pointer(struct pt_regs * regs)3067 unsigned long perf_arch_instruction_pointer(struct pt_regs *regs)
3068 {
3069 return regs->ip + code_segment_base(regs);
3070 }
3071
common_misc_flags(struct pt_regs * regs)3072 static unsigned long common_misc_flags(struct pt_regs *regs)
3073 {
3074 if (regs->flags & PERF_EFLAGS_EXACT)
3075 return PERF_RECORD_MISC_EXACT_IP;
3076
3077 return 0;
3078 }
3079
guest_misc_flags(struct pt_regs * regs)3080 static unsigned long guest_misc_flags(struct pt_regs *regs)
3081 {
3082 unsigned long guest_state = perf_guest_state();
3083
3084 if (!(guest_state & PERF_GUEST_ACTIVE))
3085 return 0;
3086
3087 if (guest_state & PERF_GUEST_USER)
3088 return PERF_RECORD_MISC_GUEST_USER;
3089 else
3090 return PERF_RECORD_MISC_GUEST_KERNEL;
3091
3092 }
3093
host_misc_flags(struct pt_regs * regs)3094 static unsigned long host_misc_flags(struct pt_regs *regs)
3095 {
3096 if (user_mode(regs))
3097 return PERF_RECORD_MISC_USER;
3098 else
3099 return PERF_RECORD_MISC_KERNEL;
3100 }
3101
perf_arch_guest_misc_flags(struct pt_regs * regs)3102 unsigned long perf_arch_guest_misc_flags(struct pt_regs *regs)
3103 {
3104 unsigned long flags = common_misc_flags(regs);
3105
3106 flags |= guest_misc_flags(regs);
3107
3108 return flags;
3109 }
3110
perf_arch_misc_flags(struct pt_regs * regs)3111 unsigned long perf_arch_misc_flags(struct pt_regs *regs)
3112 {
3113 unsigned long flags = common_misc_flags(regs);
3114
3115 flags |= host_misc_flags(regs);
3116
3117 return flags;
3118 }
3119
perf_get_x86_pmu_capability(struct x86_pmu_capability * cap)3120 void perf_get_x86_pmu_capability(struct x86_pmu_capability *cap)
3121 {
3122 /* This API doesn't currently support enumerating hybrid PMUs. */
3123 if (WARN_ON_ONCE(cpu_feature_enabled(X86_FEATURE_HYBRID_CPU)) ||
3124 !x86_pmu_initialized()) {
3125 memset(cap, 0, sizeof(*cap));
3126 return;
3127 }
3128
3129 /*
3130 * Note, hybrid CPU models get tracked as having hybrid PMUs even when
3131 * all E-cores are disabled via BIOS. When E-cores are disabled, the
3132 * base PMU holds the correct number of counters for P-cores.
3133 */
3134 cap->version = x86_pmu.version;
3135 cap->num_counters_gp = x86_pmu_num_counters(NULL);
3136 cap->num_counters_fixed = x86_pmu_num_counters_fixed(NULL);
3137 cap->bit_width_gp = cap->num_counters_gp ? x86_pmu.cntval_bits : 0;
3138 cap->bit_width_fixed = cap->num_counters_fixed ? x86_pmu.cntval_bits : 0;
3139 cap->events_mask = (unsigned int)x86_pmu.events_maskl;
3140 cap->events_mask_len = x86_pmu.events_mask_len;
3141 cap->pebs_ept = x86_pmu.pebs_ept;
3142 cap->mediated = !!(pmu.capabilities & PERF_PMU_CAP_MEDIATED_VPMU);
3143 }
3144 EXPORT_SYMBOL_FOR_KVM(perf_get_x86_pmu_capability);
3145
perf_get_hw_event_config(int hw_event)3146 u64 perf_get_hw_event_config(int hw_event)
3147 {
3148 int max = x86_pmu.max_events;
3149
3150 if (hw_event < max)
3151 return x86_pmu.event_map(array_index_nospec(hw_event, max));
3152
3153 return 0;
3154 }
3155 EXPORT_SYMBOL_FOR_KVM(perf_get_hw_event_config);
3156