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