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