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