xref: /linux/arch/arm64/kvm/pmu-emul.c (revision 751d041a13bdc9d72bf7efdc86224da1174ff31d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2015 Linaro Ltd.
4  * Author: Shannon Zhao <shannon.zhao@linaro.org>
5  */
6 
7 #include <linux/cpu.h>
8 #include <linux/kvm.h>
9 #include <linux/kvm_host.h>
10 #include <linux/list.h>
11 #include <linux/perf_event.h>
12 #include <linux/perf/arm_pmu.h>
13 #include <linux/uaccess.h>
14 #include <asm/kvm_emulate.h>
15 #include <kvm/arm_pmu.h>
16 #include <kvm/arm_vgic.h>
17 
18 #define PERF_ATTR_CFG1_COUNTER_64BIT	BIT(0)
19 
20 static LIST_HEAD(arm_pmus);
21 static DEFINE_MUTEX(arm_pmus_lock);
22 
23 static void kvm_pmu_create_perf_event(struct kvm_pmc *pmc);
24 static void kvm_pmu_release_perf_event(struct kvm_pmc *pmc);
25 static bool kvm_pmu_counter_is_enabled(struct kvm_pmc *pmc);
26 
27 bool kvm_supports_guest_pmuv3(void)
28 {
29 	guard(mutex)(&arm_pmus_lock);
30 	return !list_empty(&arm_pmus);
31 }
32 
33 static struct kvm_vcpu *kvm_pmc_to_vcpu(const struct kvm_pmc *pmc)
34 {
35 	return container_of(pmc, struct kvm_vcpu, arch.pmu.pmc[pmc->idx]);
36 }
37 
38 static struct kvm_pmc *kvm_vcpu_idx_to_pmc(struct kvm_vcpu *vcpu, int cnt_idx)
39 {
40 	return &vcpu->arch.pmu.pmc[cnt_idx];
41 }
42 
43 static u32 __kvm_pmu_event_mask(unsigned int pmuver)
44 {
45 	switch (pmuver) {
46 	case ID_AA64DFR0_EL1_PMUVer_IMP:
47 		return GENMASK(9, 0);
48 	case ID_AA64DFR0_EL1_PMUVer_V3P1:
49 	case ID_AA64DFR0_EL1_PMUVer_V3P4:
50 	case ID_AA64DFR0_EL1_PMUVer_V3P5:
51 	case ID_AA64DFR0_EL1_PMUVer_V3P7:
52 		return GENMASK(15, 0);
53 	default:		/* Shouldn't be here, just for sanity */
54 		WARN_ONCE(1, "Unknown PMU version %d\n", pmuver);
55 		return 0;
56 	}
57 }
58 
59 static u32 kvm_pmu_event_mask(struct kvm *kvm)
60 {
61 	u64 dfr0 = kvm_read_vm_id_reg(kvm, SYS_ID_AA64DFR0_EL1);
62 	u8 pmuver = SYS_FIELD_GET(ID_AA64DFR0_EL1, PMUVer, dfr0);
63 
64 	return __kvm_pmu_event_mask(pmuver);
65 }
66 
67 u64 kvm_pmu_evtyper_mask(struct kvm *kvm)
68 {
69 	u64 mask = ARMV8_PMU_EXCLUDE_EL1 | ARMV8_PMU_EXCLUDE_EL0 |
70 		   kvm_pmu_event_mask(kvm);
71 
72 	if (kvm_has_feat(kvm, ID_AA64PFR0_EL1, EL2, IMP))
73 		mask |= ARMV8_PMU_INCLUDE_EL2;
74 
75 	if (kvm_has_feat(kvm, ID_AA64PFR0_EL1, EL3, IMP))
76 		mask |= ARMV8_PMU_EXCLUDE_NS_EL0 |
77 			ARMV8_PMU_EXCLUDE_NS_EL1 |
78 			ARMV8_PMU_EXCLUDE_EL3;
79 
80 	return mask;
81 }
82 
83 /**
84  * kvm_pmc_is_64bit - determine if counter is 64bit
85  * @pmc: counter context
86  */
87 static bool kvm_pmc_is_64bit(struct kvm_pmc *pmc)
88 {
89 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
90 
91 	return (pmc->idx == ARMV8_PMU_CYCLE_IDX ||
92 		kvm_has_feat(vcpu->kvm, ID_AA64DFR0_EL1, PMUVer, V3P5));
93 }
94 
95 static bool kvm_pmc_has_64bit_overflow(struct kvm_pmc *pmc)
96 {
97 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
98 	u64 val = kvm_vcpu_read_pmcr(vcpu);
99 
100 	if (kvm_pmu_counter_is_hyp(vcpu, pmc->idx))
101 		return __vcpu_sys_reg(vcpu, MDCR_EL2) & MDCR_EL2_HLP;
102 
103 	return (pmc->idx < ARMV8_PMU_CYCLE_IDX && (val & ARMV8_PMU_PMCR_LP)) ||
104 	       (pmc->idx == ARMV8_PMU_CYCLE_IDX && (val & ARMV8_PMU_PMCR_LC));
105 }
106 
107 static bool kvm_pmu_counter_can_chain(struct kvm_pmc *pmc)
108 {
109 	return (!(pmc->idx & 1) && (pmc->idx + 1) < ARMV8_PMU_CYCLE_IDX &&
110 		!kvm_pmc_has_64bit_overflow(pmc));
111 }
112 
113 static u32 counter_index_to_reg(u64 idx)
114 {
115 	return (idx == ARMV8_PMU_CYCLE_IDX) ? PMCCNTR_EL0 : PMEVCNTR0_EL0 + idx;
116 }
117 
118 static u32 counter_index_to_evtreg(u64 idx)
119 {
120 	return (idx == ARMV8_PMU_CYCLE_IDX) ? PMCCFILTR_EL0 : PMEVTYPER0_EL0 + idx;
121 }
122 
123 static u64 kvm_pmc_read_evtreg(const struct kvm_pmc *pmc)
124 {
125 	return __vcpu_sys_reg(kvm_pmc_to_vcpu(pmc), counter_index_to_evtreg(pmc->idx));
126 }
127 
128 static u64 kvm_pmu_get_pmc_value(struct kvm_pmc *pmc)
129 {
130 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
131 	u64 counter, reg, enabled, running;
132 
133 	reg = counter_index_to_reg(pmc->idx);
134 	counter = __vcpu_sys_reg(vcpu, reg);
135 
136 	/*
137 	 * The real counter value is equal to the value of counter register plus
138 	 * the value perf event counts.
139 	 */
140 	if (pmc->perf_event)
141 		counter += perf_event_read_value(pmc->perf_event, &enabled,
142 						 &running);
143 
144 	if (!kvm_pmc_is_64bit(pmc))
145 		counter = lower_32_bits(counter);
146 
147 	return counter;
148 }
149 
150 /**
151  * kvm_pmu_get_counter_value - get PMU counter value
152  * @vcpu: The vcpu pointer
153  * @select_idx: The counter index
154  */
155 u64 kvm_pmu_get_counter_value(struct kvm_vcpu *vcpu, u64 select_idx)
156 {
157 	return kvm_pmu_get_pmc_value(kvm_vcpu_idx_to_pmc(vcpu, select_idx));
158 }
159 
160 static void kvm_pmu_set_pmc_value(struct kvm_pmc *pmc, u64 val, bool force)
161 {
162 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
163 	u64 reg;
164 
165 	kvm_pmu_release_perf_event(pmc);
166 
167 	reg = counter_index_to_reg(pmc->idx);
168 
169 	if (vcpu_mode_is_32bit(vcpu) && pmc->idx != ARMV8_PMU_CYCLE_IDX &&
170 	    !force) {
171 		/*
172 		 * Even with PMUv3p5, AArch32 cannot write to the top
173 		 * 32bit of the counters. The only possible course of
174 		 * action is to use PMCR.P, which will reset them to
175 		 * 0 (the only use of the 'force' parameter).
176 		 */
177 		val = (__vcpu_sys_reg(vcpu, reg) & GENMASK(63, 32)) |
178 		      lower_32_bits(val);
179 	}
180 
181 	__vcpu_assign_sys_reg(vcpu, reg, val);
182 
183 	/* Recreate the perf event to reflect the updated sample_period */
184 	kvm_pmu_create_perf_event(pmc);
185 }
186 
187 /**
188  * kvm_pmu_set_counter_value - set PMU counter value
189  * @vcpu: The vcpu pointer
190  * @select_idx: The counter index
191  * @val: The counter value
192  */
193 void kvm_pmu_set_counter_value(struct kvm_vcpu *vcpu, u64 select_idx, u64 val)
194 {
195 	kvm_pmu_set_pmc_value(kvm_vcpu_idx_to_pmc(vcpu, select_idx), val, false);
196 }
197 
198 /**
199  * kvm_pmu_set_counter_value_user - set PMU counter value from user
200  * @vcpu: The vcpu pointer
201  * @select_idx: The counter index
202  * @val: The counter value
203  */
204 void kvm_pmu_set_counter_value_user(struct kvm_vcpu *vcpu, u64 select_idx, u64 val)
205 {
206 	kvm_pmu_release_perf_event(kvm_vcpu_idx_to_pmc(vcpu, select_idx));
207 	__vcpu_assign_sys_reg(vcpu, counter_index_to_reg(select_idx), val);
208 	kvm_make_request(KVM_REQ_RELOAD_PMU, vcpu);
209 }
210 
211 /**
212  * kvm_pmu_release_perf_event - remove the perf event
213  * @pmc: The PMU counter pointer
214  */
215 static void kvm_pmu_release_perf_event(struct kvm_pmc *pmc)
216 {
217 	if (pmc->perf_event) {
218 		perf_event_disable(pmc->perf_event);
219 		perf_event_release_kernel(pmc->perf_event);
220 		pmc->perf_event = NULL;
221 	}
222 }
223 
224 /**
225  * kvm_pmu_stop_counter - stop PMU counter
226  * @pmc: The PMU counter pointer
227  *
228  * If this counter has been configured to monitor some event, release it here.
229  */
230 static void kvm_pmu_stop_counter(struct kvm_pmc *pmc)
231 {
232 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
233 	u64 reg, val;
234 
235 	if (!pmc->perf_event)
236 		return;
237 
238 	val = kvm_pmu_get_pmc_value(pmc);
239 
240 	reg = counter_index_to_reg(pmc->idx);
241 
242 	__vcpu_assign_sys_reg(vcpu, reg, val);
243 
244 	kvm_pmu_release_perf_event(pmc);
245 }
246 
247 /**
248  * kvm_pmu_vcpu_init - assign pmu counter idx for cpu
249  * @vcpu: The vcpu pointer
250  *
251  */
252 void kvm_pmu_vcpu_init(struct kvm_vcpu *vcpu)
253 {
254 	int i;
255 	struct kvm_pmu *pmu = &vcpu->arch.pmu;
256 
257 	for (i = 0; i < KVM_ARMV8_PMU_MAX_COUNTERS; i++)
258 		pmu->pmc[i].idx = i;
259 }
260 
261 /**
262  * kvm_pmu_vcpu_destroy - free perf event of PMU for cpu
263  * @vcpu: The vcpu pointer
264  *
265  */
266 void kvm_pmu_vcpu_destroy(struct kvm_vcpu *vcpu)
267 {
268 	int i;
269 
270 	for (i = 0; i < KVM_ARMV8_PMU_MAX_COUNTERS; i++)
271 		kvm_pmu_release_perf_event(kvm_vcpu_idx_to_pmc(vcpu, i));
272 	irq_work_sync(&vcpu->arch.pmu.overflow_work);
273 }
274 
275 static u64 kvm_pmu_hyp_counter_mask(struct kvm_vcpu *vcpu)
276 {
277 	unsigned int hpmn, n;
278 
279 	if (!vcpu_has_nv(vcpu))
280 		return 0;
281 
282 	hpmn = SYS_FIELD_GET(MDCR_EL2, HPMN, __vcpu_sys_reg(vcpu, MDCR_EL2));
283 	n = vcpu->kvm->arch.nr_pmu_counters;
284 
285 	/*
286 	 * Programming HPMN to a value greater than PMCR_EL0.N is
287 	 * CONSTRAINED UNPREDICTABLE. Make the implementation choice that an
288 	 * UNKNOWN number of counters (in our case, zero) are reserved for EL2.
289 	 */
290 	if (hpmn >= n)
291 		return 0;
292 
293 	/*
294 	 * Programming HPMN=0 is CONSTRAINED UNPREDICTABLE if FEAT_HPMN0 isn't
295 	 * implemented. Since KVM's ability to emulate HPMN=0 does not directly
296 	 * depend on hardware (all PMU registers are trapped), make the
297 	 * implementation choice that all counters are included in the second
298 	 * range reserved for EL2/EL3.
299 	 */
300 	return GENMASK(n - 1, hpmn);
301 }
302 
303 bool kvm_pmu_counter_is_hyp(struct kvm_vcpu *vcpu, unsigned int idx)
304 {
305 	return kvm_pmu_hyp_counter_mask(vcpu) & BIT(idx);
306 }
307 
308 u64 kvm_pmu_accessible_counter_mask(struct kvm_vcpu *vcpu)
309 {
310 	u64 mask = kvm_pmu_implemented_counter_mask(vcpu);
311 
312 	if (!vcpu_has_nv(vcpu) || vcpu_is_el2(vcpu))
313 		return mask;
314 
315 	return mask & ~kvm_pmu_hyp_counter_mask(vcpu);
316 }
317 
318 u64 kvm_pmu_implemented_counter_mask(struct kvm_vcpu *vcpu)
319 {
320 	u64 val = FIELD_GET(ARMV8_PMU_PMCR_N, kvm_vcpu_read_pmcr(vcpu));
321 
322 	if (val == 0)
323 		return BIT(ARMV8_PMU_CYCLE_IDX);
324 	else
325 		return GENMASK(val - 1, 0) | BIT(ARMV8_PMU_CYCLE_IDX);
326 }
327 
328 static void kvm_pmc_enable_perf_event(struct kvm_pmc *pmc)
329 {
330 	if (!pmc->perf_event) {
331 		kvm_pmu_create_perf_event(pmc);
332 		return;
333 	}
334 
335 	perf_event_enable(pmc->perf_event);
336 	if (pmc->perf_event->state != PERF_EVENT_STATE_ACTIVE)
337 		kvm_debug("fail to enable perf event\n");
338 }
339 
340 static void kvm_pmc_disable_perf_event(struct kvm_pmc *pmc)
341 {
342 	if (pmc->perf_event)
343 		perf_event_disable(pmc->perf_event);
344 }
345 
346 void kvm_pmu_reprogram_counter_mask(struct kvm_vcpu *vcpu, u64 val)
347 {
348 	int i;
349 
350 	if (!val)
351 		return;
352 
353 	for (i = 0; i < KVM_ARMV8_PMU_MAX_COUNTERS; i++) {
354 		struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, i);
355 
356 		if (!(val & BIT(i)))
357 			continue;
358 
359 		if (kvm_pmu_counter_is_enabled(pmc))
360 			kvm_pmc_enable_perf_event(pmc);
361 		else
362 			kvm_pmc_disable_perf_event(pmc);
363 	}
364 
365 	kvm_vcpu_pmu_restore_guest(vcpu);
366 }
367 
368 /*
369  * Returns the PMU overflow state, which is true if there exists an event
370  * counter where the values of the global enable control, PMOVSSET_EL0[n], and
371  * PMINTENSET_EL1[n] are all 1.
372  */
373 static bool kvm_pmu_overflow_status(struct kvm_vcpu *vcpu)
374 {
375 	u64 reg = __vcpu_sys_reg(vcpu, PMOVSSET_EL0);
376 
377 	reg &= __vcpu_sys_reg(vcpu, PMINTENSET_EL1);
378 
379 	/*
380 	 * PMCR_EL0.E is the global enable control for event counters available
381 	 * to EL0 and EL1.
382 	 */
383 	if (!(kvm_vcpu_read_pmcr(vcpu) & ARMV8_PMU_PMCR_E))
384 		reg &= kvm_pmu_hyp_counter_mask(vcpu);
385 
386 	/*
387 	 * Otherwise, MDCR_EL2.HPME is the global enable control for event
388 	 * counters reserved for EL2.
389 	 */
390 	if (!(vcpu_read_sys_reg(vcpu, MDCR_EL2) & MDCR_EL2_HPME))
391 		reg &= ~kvm_pmu_hyp_counter_mask(vcpu);
392 
393 	return reg;
394 }
395 
396 static void kvm_pmu_update_state(struct kvm_vcpu *vcpu)
397 {
398 	struct kvm_pmu *pmu = &vcpu->arch.pmu;
399 
400 	if (unlikely(!irqchip_in_kernel(vcpu->kvm)))
401 		return;
402 
403 	WARN_ON(kvm_vgic_inject_irq(vcpu->kvm, vcpu, pmu->irq_num,
404 				    kvm_pmu_overflow_status(vcpu), pmu));
405 }
406 
407 bool kvm_pmu_should_notify_user(struct kvm_vcpu *vcpu)
408 {
409 	struct kvm_sync_regs *sregs = &vcpu->run->s.regs;
410 	bool run_level = sregs->device_irq_level & KVM_ARM_DEV_PMU;
411 
412 	return kvm_pmu_overflow_status(vcpu) != run_level;
413 }
414 
415 /*
416  * Reflect the PMU overflow interrupt output level into the kvm_run structure
417  */
418 bool kvm_pmu_update_run(struct kvm_vcpu *vcpu)
419 {
420 	bool update = kvm_pmu_should_notify_user(vcpu);
421 	if (update)
422 		vcpu->run->s.regs.device_irq_level ^= KVM_ARM_DEV_PMU;
423 	return update;
424 }
425 
426 /**
427  * kvm_pmu_flush_hwstate - flush pmu state to cpu
428  * @vcpu: The vcpu pointer
429  *
430  * Check if the PMU has overflowed while we were running in the host, and inject
431  * an interrupt if that was the case.
432  */
433 void kvm_pmu_flush_hwstate(struct kvm_vcpu *vcpu)
434 {
435 	kvm_pmu_update_state(vcpu);
436 }
437 
438 /**
439  * kvm_pmu_sync_hwstate - sync pmu state from cpu
440  * @vcpu: The vcpu pointer
441  *
442  * Check if the PMU has overflowed while we were running in the guest, and
443  * inject an interrupt if that was the case.
444  */
445 void kvm_pmu_sync_hwstate(struct kvm_vcpu *vcpu)
446 {
447 	kvm_pmu_update_state(vcpu);
448 }
449 
450 /*
451  * When perf interrupt is an NMI, we cannot safely notify the vcpu corresponding
452  * to the event.
453  * This is why we need a callback to do it once outside of the NMI context.
454  */
455 static void kvm_pmu_perf_overflow_notify_vcpu(struct irq_work *work)
456 {
457 	struct kvm_vcpu *vcpu;
458 
459 	vcpu = container_of(work, struct kvm_vcpu, arch.pmu.overflow_work);
460 	kvm_vcpu_kick(vcpu);
461 }
462 
463 /*
464  * Perform an increment on any of the counters described in @mask,
465  * generating the overflow if required, and propagate it as a chained
466  * event if possible.
467  */
468 static void kvm_pmu_counter_increment(struct kvm_vcpu *vcpu,
469 				      unsigned long mask, u32 event)
470 {
471 	int i;
472 
473 	if (!(kvm_vcpu_read_pmcr(vcpu) & ARMV8_PMU_PMCR_E))
474 		return;
475 
476 	/* Weed out disabled counters */
477 	mask &= __vcpu_sys_reg(vcpu, PMCNTENSET_EL0);
478 
479 	for_each_set_bit(i, &mask, ARMV8_PMU_CYCLE_IDX) {
480 		struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, i);
481 		u64 type, reg;
482 
483 		/* Filter on event type */
484 		type = __vcpu_sys_reg(vcpu, counter_index_to_evtreg(i));
485 		type &= kvm_pmu_event_mask(vcpu->kvm);
486 		if (type != event)
487 			continue;
488 
489 		/* Increment this counter */
490 		reg = __vcpu_sys_reg(vcpu, counter_index_to_reg(i)) + 1;
491 		if (!kvm_pmc_is_64bit(pmc))
492 			reg = lower_32_bits(reg);
493 		__vcpu_assign_sys_reg(vcpu, counter_index_to_reg(i), reg);
494 
495 		/* No overflow? move on */
496 		if (kvm_pmc_has_64bit_overflow(pmc) ? reg : lower_32_bits(reg))
497 			continue;
498 
499 		/* Mark overflow */
500 		__vcpu_rmw_sys_reg(vcpu, PMOVSSET_EL0, |=, BIT(i));
501 
502 		if (kvm_pmu_counter_can_chain(pmc))
503 			kvm_pmu_counter_increment(vcpu, BIT(i + 1),
504 						  ARMV8_PMUV3_PERFCTR_CHAIN);
505 	}
506 }
507 
508 /* Compute the sample period for a given counter value */
509 static u64 compute_period(struct kvm_pmc *pmc, u64 counter)
510 {
511 	u64 val;
512 
513 	if (kvm_pmc_is_64bit(pmc) && kvm_pmc_has_64bit_overflow(pmc))
514 		val = (-counter) & GENMASK(63, 0);
515 	else
516 		val = (-counter) & GENMASK(31, 0);
517 
518 	return val;
519 }
520 
521 /*
522  * When the perf event overflows, set the overflow status and inform the vcpu.
523  */
524 static void kvm_pmu_perf_overflow(struct perf_event *perf_event,
525 				  struct perf_sample_data *data,
526 				  struct pt_regs *regs)
527 {
528 	struct kvm_pmc *pmc = perf_event->overflow_handler_context;
529 	struct arm_pmu *cpu_pmu = to_arm_pmu(perf_event->pmu);
530 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
531 	int idx = pmc->idx;
532 	u64 period;
533 
534 	cpu_pmu->pmu.stop(perf_event, PERF_EF_UPDATE);
535 
536 	/*
537 	 * Reset the sample period to the architectural limit,
538 	 * i.e. the point where the counter overflows.
539 	 */
540 	period = compute_period(pmc, local64_read(&perf_event->count));
541 
542 	local64_set(&perf_event->hw.period_left, 0);
543 	perf_event->attr.sample_period = period;
544 	perf_event->hw.sample_period = period;
545 
546 	__vcpu_rmw_sys_reg(vcpu, PMOVSSET_EL0, |=, BIT(idx));
547 
548 	if (kvm_pmu_counter_can_chain(pmc))
549 		kvm_pmu_counter_increment(vcpu, BIT(idx + 1),
550 					  ARMV8_PMUV3_PERFCTR_CHAIN);
551 
552 	if (kvm_pmu_overflow_status(vcpu)) {
553 		kvm_make_request(KVM_REQ_IRQ_PENDING, vcpu);
554 
555 		if (!in_nmi())
556 			kvm_vcpu_kick(vcpu);
557 		else
558 			irq_work_queue(&vcpu->arch.pmu.overflow_work);
559 	}
560 
561 	cpu_pmu->pmu.start(perf_event, PERF_EF_RELOAD);
562 }
563 
564 /**
565  * kvm_pmu_software_increment - do software increment
566  * @vcpu: The vcpu pointer
567  * @val: the value guest writes to PMSWINC register
568  */
569 void kvm_pmu_software_increment(struct kvm_vcpu *vcpu, u64 val)
570 {
571 	kvm_pmu_counter_increment(vcpu, val, ARMV8_PMUV3_PERFCTR_SW_INCR);
572 }
573 
574 /**
575  * kvm_pmu_handle_pmcr - handle PMCR register
576  * @vcpu: The vcpu pointer
577  * @val: the value guest writes to PMCR register
578  */
579 void kvm_pmu_handle_pmcr(struct kvm_vcpu *vcpu, u64 val)
580 {
581 	int i;
582 
583 	/* Fixup PMCR_EL0 to reconcile the PMU version and the LP bit */
584 	if (!kvm_has_feat(vcpu->kvm, ID_AA64DFR0_EL1, PMUVer, V3P5))
585 		val &= ~ARMV8_PMU_PMCR_LP;
586 
587 	/* Request a reload of the PMU to enable/disable affected counters */
588 	if ((__vcpu_sys_reg(vcpu, PMCR_EL0) ^ val) & ARMV8_PMU_PMCR_E)
589 		kvm_make_request(KVM_REQ_RELOAD_PMU, vcpu);
590 
591 	/* The reset bits don't indicate any state, and shouldn't be saved. */
592 	__vcpu_assign_sys_reg(vcpu, PMCR_EL0, (val & ~(ARMV8_PMU_PMCR_C | ARMV8_PMU_PMCR_P)));
593 
594 	if (val & ARMV8_PMU_PMCR_C)
595 		kvm_pmu_set_counter_value(vcpu, ARMV8_PMU_CYCLE_IDX, 0);
596 
597 	if (val & ARMV8_PMU_PMCR_P) {
598 		unsigned long mask = kvm_pmu_implemented_counter_mask(vcpu) &
599 				     ~BIT(ARMV8_PMU_CYCLE_IDX);
600 
601 		if (!vcpu_is_el2(vcpu))
602 			mask &= ~kvm_pmu_hyp_counter_mask(vcpu);
603 
604 		for_each_set_bit(i, &mask, 32)
605 			kvm_pmu_set_pmc_value(kvm_vcpu_idx_to_pmc(vcpu, i), 0, true);
606 	}
607 }
608 
609 static bool kvm_pmu_counter_is_enabled(struct kvm_pmc *pmc)
610 {
611 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
612 	unsigned int mdcr = __vcpu_sys_reg(vcpu, MDCR_EL2);
613 
614 	if (!(__vcpu_sys_reg(vcpu, PMCNTENSET_EL0) & BIT(pmc->idx)))
615 		return false;
616 
617 	if (kvm_pmu_counter_is_hyp(vcpu, pmc->idx))
618 		return mdcr & MDCR_EL2_HPME;
619 
620 	return kvm_vcpu_read_pmcr(vcpu) & ARMV8_PMU_PMCR_E;
621 }
622 
623 static bool kvm_pmc_counts_at_el0(struct kvm_pmc *pmc)
624 {
625 	u64 evtreg = kvm_pmc_read_evtreg(pmc);
626 	bool nsu = evtreg & ARMV8_PMU_EXCLUDE_NS_EL0;
627 	bool u = evtreg & ARMV8_PMU_EXCLUDE_EL0;
628 
629 	return u == nsu;
630 }
631 
632 static bool kvm_pmc_counts_at_el1(struct kvm_pmc *pmc)
633 {
634 	u64 evtreg = kvm_pmc_read_evtreg(pmc);
635 	bool nsk = evtreg & ARMV8_PMU_EXCLUDE_NS_EL1;
636 	bool p = evtreg & ARMV8_PMU_EXCLUDE_EL1;
637 
638 	return p == nsk;
639 }
640 
641 static bool kvm_pmc_counts_at_el2(struct kvm_pmc *pmc)
642 {
643 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
644 	u64 mdcr = __vcpu_sys_reg(vcpu, MDCR_EL2);
645 
646 	if (!kvm_pmu_counter_is_hyp(vcpu, pmc->idx) && (mdcr & MDCR_EL2_HPMD))
647 		return false;
648 
649 	return kvm_pmc_read_evtreg(pmc) & ARMV8_PMU_INCLUDE_EL2;
650 }
651 
652 static int kvm_map_pmu_event(struct kvm *kvm, unsigned int eventsel)
653 {
654 	struct arm_pmu *pmu = kvm->arch.arm_pmu;
655 
656 	/*
657 	 * The CPU PMU likely isn't PMUv3; let the driver provide a mapping
658 	 * for the guest's PMUv3 event ID.
659 	 */
660 	if (unlikely(pmu->map_pmuv3_event))
661 		return pmu->map_pmuv3_event(eventsel);
662 
663 	return eventsel;
664 }
665 
666 /**
667  * kvm_pmu_create_perf_event - create a perf event for a counter
668  * @pmc: Counter context
669  */
670 static void kvm_pmu_create_perf_event(struct kvm_pmc *pmc)
671 {
672 	struct kvm_vcpu *vcpu = kvm_pmc_to_vcpu(pmc);
673 	struct arm_pmu *arm_pmu = vcpu->kvm->arch.arm_pmu;
674 	struct perf_event *event;
675 	struct perf_event_attr attr;
676 	int eventsel;
677 	u64 evtreg;
678 
679 	evtreg = kvm_pmc_read_evtreg(pmc);
680 
681 	kvm_pmu_stop_counter(pmc);
682 	if (pmc->idx == ARMV8_PMU_CYCLE_IDX)
683 		eventsel = ARMV8_PMUV3_PERFCTR_CPU_CYCLES;
684 	else
685 		eventsel = evtreg & kvm_pmu_event_mask(vcpu->kvm);
686 
687 	/*
688 	 * Neither SW increment nor chained events need to be backed
689 	 * by a perf event.
690 	 */
691 	if (eventsel == ARMV8_PMUV3_PERFCTR_SW_INCR ||
692 	    eventsel == ARMV8_PMUV3_PERFCTR_CHAIN)
693 		return;
694 
695 	/*
696 	 * If we have a filter in place and that the event isn't allowed, do
697 	 * not install a perf event either.
698 	 */
699 	if (vcpu->kvm->arch.pmu_filter &&
700 	    !test_bit(eventsel, vcpu->kvm->arch.pmu_filter))
701 		return;
702 
703 	/*
704 	 * Don't create an event if we're running on hardware that requires
705 	 * PMUv3 event translation and we couldn't find a valid mapping.
706 	 */
707 	eventsel = kvm_map_pmu_event(vcpu->kvm, eventsel);
708 	if (eventsel < 0)
709 		return;
710 
711 	memset(&attr, 0, sizeof(struct perf_event_attr));
712 	attr.type = arm_pmu->pmu.type;
713 	attr.size = sizeof(attr);
714 	attr.pinned = 1;
715 	attr.disabled = !kvm_pmu_counter_is_enabled(pmc);
716 	attr.exclude_user = !kvm_pmc_counts_at_el0(pmc);
717 	attr.exclude_hv = 1; /* Don't count EL2 events */
718 	attr.exclude_host = 1; /* Don't count host events */
719 	attr.config = eventsel;
720 
721 	/*
722 	 * Filter events at EL1 (i.e. vEL2) when in a hyp context based on the
723 	 * guest's EL2 filter.
724 	 */
725 	if (unlikely(is_hyp_ctxt(vcpu)))
726 		attr.exclude_kernel = !kvm_pmc_counts_at_el2(pmc);
727 	else
728 		attr.exclude_kernel = !kvm_pmc_counts_at_el1(pmc);
729 
730 	/*
731 	 * If counting with a 64bit counter, advertise it to the perf
732 	 * code, carefully dealing with the initial sample period
733 	 * which also depends on the overflow.
734 	 */
735 	if (kvm_pmc_is_64bit(pmc))
736 		attr.config1 |= PERF_ATTR_CFG1_COUNTER_64BIT;
737 
738 	attr.sample_period = compute_period(pmc, kvm_pmu_get_pmc_value(pmc));
739 
740 	event = perf_event_create_kernel_counter(&attr, -1, current,
741 						 kvm_pmu_perf_overflow, pmc);
742 
743 	if (IS_ERR(event)) {
744 		pr_err_once("kvm: pmu event creation failed %ld\n",
745 			    PTR_ERR(event));
746 		return;
747 	}
748 
749 	pmc->perf_event = event;
750 }
751 
752 /**
753  * kvm_pmu_set_counter_event_type - set selected counter to monitor some event
754  * @vcpu: The vcpu pointer
755  * @data: The data guest writes to PMXEVTYPER_EL0
756  * @select_idx: The number of selected counter
757  *
758  * When OS accesses PMXEVTYPER_EL0, that means it wants to set a PMC to count an
759  * event with given hardware event number. Here we call perf_event API to
760  * emulate this action and create a kernel perf event for it.
761  */
762 void kvm_pmu_set_counter_event_type(struct kvm_vcpu *vcpu, u64 data,
763 				    u64 select_idx)
764 {
765 	struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, select_idx);
766 	u64 reg;
767 
768 	reg = counter_index_to_evtreg(pmc->idx);
769 	__vcpu_assign_sys_reg(vcpu, reg, (data & kvm_pmu_evtyper_mask(vcpu->kvm)));
770 
771 	kvm_pmu_create_perf_event(pmc);
772 }
773 
774 void kvm_host_pmu_init(struct arm_pmu *pmu)
775 {
776 	struct arm_pmu_entry *entry;
777 
778 	/*
779 	 * Check the sanitised PMU version for the system, as KVM does not
780 	 * support implementations where PMUv3 exists on a subset of CPUs.
781 	 */
782 	if (!pmuv3_implemented(kvm_arm_pmu_get_pmuver_limit()))
783 		return;
784 
785 	guard(mutex)(&arm_pmus_lock);
786 
787 	entry = kmalloc_obj(*entry);
788 	if (!entry)
789 		return;
790 
791 	entry->arm_pmu = pmu;
792 	list_add_tail(&entry->entry, &arm_pmus);
793 }
794 
795 static struct arm_pmu *kvm_pmu_probe_armpmu(void)
796 {
797 	struct arm_pmu_entry *entry;
798 	struct arm_pmu *pmu;
799 	int cpu;
800 
801 	guard(mutex)(&arm_pmus_lock);
802 
803 	/*
804 	 * It is safe to use a stale cpu to iterate the list of PMUs so long as
805 	 * the same value is used for the entirety of the loop. Given this, and
806 	 * the fact that no percpu data is used for the lookup there is no need
807 	 * to disable preemption.
808 	 *
809 	 * It is still necessary to get a valid cpu, though, to probe for the
810 	 * default PMU instance as userspace is not required to specify a PMU
811 	 * type. In order to uphold the preexisting behavior KVM selects the
812 	 * PMU instance for the core during vcpu init. A dependent use
813 	 * case would be a user with disdain of all things big.LITTLE that
814 	 * affines the VMM to a particular cluster of cores.
815 	 *
816 	 * In any case, userspace should just do the sane thing and use the UAPI
817 	 * to select a PMU type directly. But, be wary of the baggage being
818 	 * carried here.
819 	 */
820 	cpu = raw_smp_processor_id();
821 	list_for_each_entry(entry, &arm_pmus, entry) {
822 		pmu = entry->arm_pmu;
823 
824 		if (cpumask_test_cpu(cpu, &pmu->supported_cpus))
825 			return pmu;
826 	}
827 
828 	return NULL;
829 }
830 
831 static u64 __compute_pmceid(struct arm_pmu *pmu, bool pmceid1)
832 {
833 	u32 hi[2], lo[2];
834 
835 	bitmap_to_arr32(lo, pmu->pmceid_bitmap, ARMV8_PMUV3_MAX_COMMON_EVENTS);
836 	bitmap_to_arr32(hi, pmu->pmceid_ext_bitmap, ARMV8_PMUV3_MAX_COMMON_EVENTS);
837 
838 	return ((u64)hi[pmceid1] << 32) | lo[pmceid1];
839 }
840 
841 static u64 compute_pmceid0(struct arm_pmu *pmu)
842 {
843 	u64 val = __compute_pmceid(pmu, 0);
844 
845 	/* always support SW_INCR */
846 	val |= BIT(ARMV8_PMUV3_PERFCTR_SW_INCR);
847 	/* always support CHAIN */
848 	val |= BIT(ARMV8_PMUV3_PERFCTR_CHAIN);
849 	return val;
850 }
851 
852 static u64 compute_pmceid1(struct arm_pmu *pmu)
853 {
854 	u64 val = __compute_pmceid(pmu, 1);
855 
856 	/*
857 	 * Don't advertise STALL_SLOT*, as PMMIR_EL0 is handled
858 	 * as RAZ
859 	 */
860 	val &= ~(BIT_ULL(ARMV8_PMUV3_PERFCTR_STALL_SLOT - 32) |
861 		 BIT_ULL(ARMV8_PMUV3_PERFCTR_STALL_SLOT_FRONTEND - 32) |
862 		 BIT_ULL(ARMV8_PMUV3_PERFCTR_STALL_SLOT_BACKEND - 32));
863 	return val;
864 }
865 
866 u64 kvm_pmu_get_pmceid(struct kvm_vcpu *vcpu, bool pmceid1)
867 {
868 	struct arm_pmu *cpu_pmu = vcpu->kvm->arch.arm_pmu;
869 	unsigned long *bmap = vcpu->kvm->arch.pmu_filter;
870 	u64 val, mask = 0;
871 	int base, i, nr_events;
872 
873 	if (!pmceid1) {
874 		val = compute_pmceid0(cpu_pmu);
875 		base = 0;
876 	} else {
877 		val = compute_pmceid1(cpu_pmu);
878 		base = 32;
879 	}
880 
881 	if (!bmap)
882 		return val;
883 
884 	nr_events = kvm_pmu_event_mask(vcpu->kvm) + 1;
885 
886 	for (i = 0; i < 32; i += 8) {
887 		u64 byte;
888 
889 		byte = bitmap_get_value8(bmap, base + i);
890 		mask |= byte << i;
891 		if (nr_events >= (0x4000 + base + 32)) {
892 			byte = bitmap_get_value8(bmap, 0x4000 + base + i);
893 			mask |= byte << (32 + i);
894 		}
895 	}
896 
897 	return val & mask;
898 }
899 
900 void kvm_vcpu_reload_pmu(struct kvm_vcpu *vcpu)
901 {
902 	u64 mask = kvm_pmu_implemented_counter_mask(vcpu);
903 
904 	__vcpu_rmw_sys_reg(vcpu, PMOVSSET_EL0, &=, mask);
905 	__vcpu_rmw_sys_reg(vcpu, PMINTENSET_EL1, &=, mask);
906 	__vcpu_rmw_sys_reg(vcpu, PMCNTENSET_EL0, &=, mask);
907 
908 	kvm_pmu_reprogram_counter_mask(vcpu, mask);
909 }
910 
911 int kvm_arm_pmu_v3_enable(struct kvm_vcpu *vcpu)
912 {
913 	if (!vcpu->arch.pmu.created)
914 		return -EINVAL;
915 
916 	/*
917 	 * A valid interrupt configuration for the PMU is either to have a
918 	 * properly configured interrupt number and using an in-kernel
919 	 * irqchip, or to not have an in-kernel GIC and not set an IRQ.
920 	 */
921 	if (irqchip_in_kernel(vcpu->kvm)) {
922 		int irq = vcpu->arch.pmu.irq_num;
923 		/*
924 		 * If we are using an in-kernel vgic, at this point we know
925 		 * the vgic will be initialized, so we can check the PMU irq
926 		 * number against the dimensions of the vgic and make sure
927 		 * it's valid.
928 		 */
929 		if (!irq_is_ppi(vcpu->kvm, irq) &&
930 		    !vgic_valid_spi(vcpu->kvm, irq))
931 			return -EINVAL;
932 	} else if (kvm_arm_pmu_irq_initialized(vcpu)) {
933 		   return -EINVAL;
934 	}
935 
936 	return 0;
937 }
938 
939 static int kvm_arm_pmu_v3_init(struct kvm_vcpu *vcpu)
940 {
941 	if (irqchip_in_kernel(vcpu->kvm)) {
942 		int ret;
943 
944 		/*
945 		 * If using the PMU with an in-kernel virtual GIC
946 		 * implementation, we require the GIC to be already
947 		 * initialized when initializing the PMU.
948 		 */
949 		if (!vgic_initialized(vcpu->kvm))
950 			return -ENODEV;
951 
952 		if (!kvm_arm_pmu_irq_initialized(vcpu)) {
953 			if (!vgic_is_v5(vcpu->kvm))
954 				return -ENXIO;
955 
956 			/* Use the architected irq number for GICv5. */
957 			vcpu->arch.pmu.irq_num = KVM_ARMV8_PMU_GICV5_IRQ;
958 		}
959 
960 		ret = kvm_vgic_set_owner(vcpu, vcpu->arch.pmu.irq_num,
961 					 &vcpu->arch.pmu);
962 		if (ret)
963 			return ret;
964 	}
965 
966 	init_irq_work(&vcpu->arch.pmu.overflow_work,
967 		      kvm_pmu_perf_overflow_notify_vcpu);
968 
969 	vcpu->arch.pmu.created = true;
970 	return 0;
971 }
972 
973 /*
974  * For one VM the interrupt type must be same for each vcpu.
975  * As a PPI, the interrupt number is the same for all vcpus,
976  * while as an SPI it must be a separate number per vcpu.
977  */
978 static bool pmu_irq_is_valid(struct kvm *kvm, int irq)
979 {
980 	unsigned long i;
981 	struct kvm_vcpu *vcpu;
982 
983 	/* On GICv5, the PMUIRQ is architecturally mandated to be PPI 23 */
984 	if (vgic_is_v5(kvm) && irq != KVM_ARMV8_PMU_GICV5_IRQ)
985 		return false;
986 
987 	kvm_for_each_vcpu(i, vcpu, kvm) {
988 		if (!kvm_arm_pmu_irq_initialized(vcpu))
989 			continue;
990 
991 		if (irq_is_ppi(vcpu->kvm, irq)) {
992 			if (vcpu->arch.pmu.irq_num != irq)
993 				return false;
994 		} else {
995 			if (vcpu->arch.pmu.irq_num == irq)
996 				return false;
997 		}
998 	}
999 
1000 	return true;
1001 }
1002 
1003 /**
1004  * kvm_arm_pmu_get_max_counters - Return the max number of PMU counters.
1005  * @kvm: The kvm pointer
1006  */
1007 u8 kvm_arm_pmu_get_max_counters(struct kvm *kvm)
1008 {
1009 	struct arm_pmu *arm_pmu = kvm->arch.arm_pmu;
1010 
1011 	/*
1012 	 * PMUv3 requires that all event counters are capable of counting any
1013 	 * event, though the same may not be true of non-PMUv3 hardware.
1014 	 */
1015 	if (cpus_have_final_cap(ARM64_WORKAROUND_PMUV3_IMPDEF_TRAPS))
1016 		return 1;
1017 
1018 	/*
1019 	 * The arm_pmu->cntr_mask considers the fixed counter(s) as well.
1020 	 * Ignore those and return only the general-purpose counters.
1021 	 */
1022 	return bitmap_weight(arm_pmu->cntr_mask, ARMV8_PMU_MAX_GENERAL_COUNTERS);
1023 }
1024 
1025 static void kvm_arm_set_nr_counters(struct kvm *kvm, unsigned int nr)
1026 {
1027 	kvm->arch.nr_pmu_counters = nr;
1028 
1029 	/* Reset MDCR_EL2.HPMN behind the vcpus' back... */
1030 	if (test_bit(KVM_ARM_VCPU_HAS_EL2, kvm->arch.vcpu_features)) {
1031 		struct kvm_vcpu *vcpu;
1032 		unsigned long i;
1033 
1034 		kvm_for_each_vcpu(i, vcpu, kvm) {
1035 			u64 val = __vcpu_sys_reg(vcpu, MDCR_EL2);
1036 			val &= ~MDCR_EL2_HPMN;
1037 			val |= FIELD_PREP(MDCR_EL2_HPMN, kvm->arch.nr_pmu_counters);
1038 			__vcpu_assign_sys_reg(vcpu, MDCR_EL2, val);
1039 		}
1040 	}
1041 }
1042 
1043 static void kvm_arm_set_pmu(struct kvm *kvm, struct arm_pmu *arm_pmu)
1044 {
1045 	lockdep_assert_held(&kvm->arch.config_lock);
1046 
1047 	kvm->arch.arm_pmu = arm_pmu;
1048 	kvm_arm_set_nr_counters(kvm, kvm_arm_pmu_get_max_counters(kvm));
1049 }
1050 
1051 /**
1052  * kvm_arm_set_default_pmu - No PMU set, get the default one.
1053  * @kvm: The kvm pointer
1054  *
1055  * The observant among you will notice that the supported_cpus
1056  * mask does not get updated for the default PMU even though it
1057  * is quite possible the selected instance supports only a
1058  * subset of cores in the system. This is intentional, and
1059  * upholds the preexisting behavior on heterogeneous systems
1060  * where vCPUs can be scheduled on any core but the guest
1061  * counters could stop working.
1062  */
1063 int kvm_arm_set_default_pmu(struct kvm *kvm)
1064 {
1065 	struct arm_pmu *arm_pmu = kvm_pmu_probe_armpmu();
1066 
1067 	if (!arm_pmu)
1068 		return -ENODEV;
1069 
1070 	kvm_arm_set_pmu(kvm, arm_pmu);
1071 	return 0;
1072 }
1073 
1074 static int kvm_arm_pmu_v3_set_pmu(struct kvm_vcpu *vcpu, int pmu_id)
1075 {
1076 	struct kvm *kvm = vcpu->kvm;
1077 	struct arm_pmu_entry *entry;
1078 	struct arm_pmu *arm_pmu;
1079 	int ret = -ENXIO;
1080 
1081 	lockdep_assert_held(&kvm->arch.config_lock);
1082 	mutex_lock(&arm_pmus_lock);
1083 
1084 	list_for_each_entry(entry, &arm_pmus, entry) {
1085 		arm_pmu = entry->arm_pmu;
1086 		if (arm_pmu->pmu.type == pmu_id) {
1087 			if (kvm_vm_has_ran_once(kvm) ||
1088 			    (kvm->arch.pmu_filter && kvm->arch.arm_pmu != arm_pmu)) {
1089 				ret = -EBUSY;
1090 				break;
1091 			}
1092 
1093 			kvm_arm_set_pmu(kvm, arm_pmu);
1094 			cpumask_copy(kvm->arch.supported_cpus, &arm_pmu->supported_cpus);
1095 			ret = 0;
1096 			break;
1097 		}
1098 	}
1099 
1100 	mutex_unlock(&arm_pmus_lock);
1101 	return ret;
1102 }
1103 
1104 static int kvm_arm_pmu_v3_set_nr_counters(struct kvm_vcpu *vcpu, unsigned int n)
1105 {
1106 	struct kvm *kvm = vcpu->kvm;
1107 
1108 	if (!kvm->arch.arm_pmu)
1109 		return -EINVAL;
1110 
1111 	if (n > kvm_arm_pmu_get_max_counters(kvm))
1112 		return -EINVAL;
1113 
1114 	kvm_arm_set_nr_counters(kvm, n);
1115 	return 0;
1116 }
1117 
1118 int kvm_arm_pmu_v3_set_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1119 {
1120 	struct kvm *kvm = vcpu->kvm;
1121 
1122 	lockdep_assert_held(&kvm->arch.config_lock);
1123 
1124 	if (!kvm_vcpu_has_pmu(vcpu))
1125 		return -ENODEV;
1126 
1127 	if (vcpu->arch.pmu.created)
1128 		return -EBUSY;
1129 
1130 	switch (attr->attr) {
1131 	case KVM_ARM_VCPU_PMU_V3_IRQ: {
1132 		int __user *uaddr = (int __user *)(long)attr->addr;
1133 		int irq;
1134 
1135 		if (!irqchip_in_kernel(kvm))
1136 			return -EINVAL;
1137 
1138 		if (get_user(irq, uaddr))
1139 			return -EFAULT;
1140 
1141 		/* The PMU overflow interrupt can be a PPI or a valid SPI. */
1142 		if (!(irq_is_ppi(vcpu->kvm, irq) || irq_is_spi(vcpu->kvm, irq)))
1143 			return -EINVAL;
1144 
1145 		if (!pmu_irq_is_valid(kvm, irq))
1146 			return -EINVAL;
1147 
1148 		if (kvm_arm_pmu_irq_initialized(vcpu))
1149 			return -EBUSY;
1150 
1151 		kvm_debug("Set kvm ARM PMU irq: %d\n", irq);
1152 		vcpu->arch.pmu.irq_num = irq;
1153 		return 0;
1154 	}
1155 	case KVM_ARM_VCPU_PMU_V3_FILTER: {
1156 		u8 pmuver = kvm_arm_pmu_get_pmuver_limit();
1157 		struct kvm_pmu_event_filter __user *uaddr;
1158 		struct kvm_pmu_event_filter filter;
1159 		int nr_events;
1160 
1161 		/*
1162 		 * Allow userspace to specify an event filter for the entire
1163 		 * event range supported by PMUVer of the hardware, rather
1164 		 * than the guest's PMUVer for KVM backward compatibility.
1165 		 */
1166 		nr_events = __kvm_pmu_event_mask(pmuver) + 1;
1167 
1168 		uaddr = (struct kvm_pmu_event_filter __user *)(long)attr->addr;
1169 
1170 		if (copy_from_user(&filter, uaddr, sizeof(filter)))
1171 			return -EFAULT;
1172 
1173 		if (((u32)filter.base_event + filter.nevents) > nr_events ||
1174 		    (filter.action != KVM_PMU_EVENT_ALLOW &&
1175 		     filter.action != KVM_PMU_EVENT_DENY))
1176 			return -EINVAL;
1177 
1178 		if (kvm_vm_has_ran_once(kvm))
1179 			return -EBUSY;
1180 
1181 		if (!kvm->arch.pmu_filter) {
1182 			kvm->arch.pmu_filter = bitmap_alloc(nr_events, GFP_KERNEL_ACCOUNT);
1183 			if (!kvm->arch.pmu_filter)
1184 				return -ENOMEM;
1185 
1186 			/*
1187 			 * The default depends on the first applied filter.
1188 			 * If it allows events, the default is to deny.
1189 			 * Conversely, if the first filter denies a set of
1190 			 * events, the default is to allow.
1191 			 */
1192 			if (filter.action == KVM_PMU_EVENT_ALLOW)
1193 				bitmap_zero(kvm->arch.pmu_filter, nr_events);
1194 			else
1195 				bitmap_fill(kvm->arch.pmu_filter, nr_events);
1196 		}
1197 
1198 		if (filter.action == KVM_PMU_EVENT_ALLOW)
1199 			bitmap_set(kvm->arch.pmu_filter, filter.base_event, filter.nevents);
1200 		else
1201 			bitmap_clear(kvm->arch.pmu_filter, filter.base_event, filter.nevents);
1202 
1203 		return 0;
1204 	}
1205 	case KVM_ARM_VCPU_PMU_V3_SET_PMU: {
1206 		int __user *uaddr = (int __user *)(long)attr->addr;
1207 		int pmu_id;
1208 
1209 		if (get_user(pmu_id, uaddr))
1210 			return -EFAULT;
1211 
1212 		return kvm_arm_pmu_v3_set_pmu(vcpu, pmu_id);
1213 	}
1214 	case KVM_ARM_VCPU_PMU_V3_SET_NR_COUNTERS: {
1215 		unsigned int __user *uaddr = (unsigned int __user *)(long)attr->addr;
1216 		unsigned int n;
1217 
1218 		if (get_user(n, uaddr))
1219 			return -EFAULT;
1220 
1221 		return kvm_arm_pmu_v3_set_nr_counters(vcpu, n);
1222 	}
1223 	case KVM_ARM_VCPU_PMU_V3_INIT:
1224 		return kvm_arm_pmu_v3_init(vcpu);
1225 	}
1226 
1227 	return -ENXIO;
1228 }
1229 
1230 int kvm_arm_pmu_v3_get_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1231 {
1232 	switch (attr->attr) {
1233 	case KVM_ARM_VCPU_PMU_V3_IRQ: {
1234 		int __user *uaddr = (int __user *)(long)attr->addr;
1235 		int irq;
1236 
1237 		if (!irqchip_in_kernel(vcpu->kvm))
1238 			return -EINVAL;
1239 
1240 		if (!kvm_vcpu_has_pmu(vcpu))
1241 			return -ENODEV;
1242 
1243 		if (!kvm_arm_pmu_irq_initialized(vcpu))
1244 			return -ENXIO;
1245 
1246 		irq = vcpu->arch.pmu.irq_num;
1247 		return put_user(irq, uaddr);
1248 	}
1249 	}
1250 
1251 	return -ENXIO;
1252 }
1253 
1254 int kvm_arm_pmu_v3_has_attr(struct kvm_vcpu *vcpu, struct kvm_device_attr *attr)
1255 {
1256 	switch (attr->attr) {
1257 	case KVM_ARM_VCPU_PMU_V3_IRQ:
1258 	case KVM_ARM_VCPU_PMU_V3_INIT:
1259 	case KVM_ARM_VCPU_PMU_V3_FILTER:
1260 	case KVM_ARM_VCPU_PMU_V3_SET_PMU:
1261 	case KVM_ARM_VCPU_PMU_V3_SET_NR_COUNTERS:
1262 		if (kvm_vcpu_has_pmu(vcpu))
1263 			return 0;
1264 	}
1265 
1266 	return -ENXIO;
1267 }
1268 
1269 u8 kvm_arm_pmu_get_pmuver_limit(void)
1270 {
1271 	unsigned int pmuver;
1272 
1273 	pmuver = SYS_FIELD_GET(ID_AA64DFR0_EL1, PMUVer,
1274 			       read_sanitised_ftr_reg(SYS_ID_AA64DFR0_EL1));
1275 
1276 	/*
1277 	 * Spoof a barebones PMUv3 implementation if the system supports IMPDEF
1278 	 * traps of the PMUv3 sysregs
1279 	 */
1280 	if (cpus_have_final_cap(ARM64_WORKAROUND_PMUV3_IMPDEF_TRAPS))
1281 		return ID_AA64DFR0_EL1_PMUVer_IMP;
1282 
1283 	/*
1284 	 * Otherwise, treat IMPLEMENTATION DEFINED functionality as
1285 	 * unimplemented
1286 	 */
1287 	if (pmuver == ID_AA64DFR0_EL1_PMUVer_IMP_DEF)
1288 		return 0;
1289 
1290 	return min(pmuver, ID_AA64DFR0_EL1_PMUVer_V3P5);
1291 }
1292 
1293 /**
1294  * kvm_vcpu_read_pmcr - Read PMCR_EL0 register for the vCPU
1295  * @vcpu: The vcpu pointer
1296  */
1297 u64 kvm_vcpu_read_pmcr(struct kvm_vcpu *vcpu)
1298 {
1299 	u64 pmcr = __vcpu_sys_reg(vcpu, PMCR_EL0);
1300 	u64 n = vcpu->kvm->arch.nr_pmu_counters;
1301 
1302 	if (vcpu_has_nv(vcpu) && !vcpu_is_el2(vcpu))
1303 		n = FIELD_GET(MDCR_EL2_HPMN, __vcpu_sys_reg(vcpu, MDCR_EL2));
1304 
1305 	return u64_replace_bits(pmcr, n, ARMV8_PMU_PMCR_N);
1306 }
1307 
1308 void kvm_pmu_nested_transition(struct kvm_vcpu *vcpu)
1309 {
1310 	bool reprogrammed = false;
1311 	unsigned long mask;
1312 	int i;
1313 
1314 	mask = __vcpu_sys_reg(vcpu, PMCNTENSET_EL0);
1315 	for_each_set_bit(i, &mask, 32) {
1316 		struct kvm_pmc *pmc = kvm_vcpu_idx_to_pmc(vcpu, i);
1317 
1318 		/*
1319 		 * We only need to reconfigure events where the filter is
1320 		 * different at EL1 vs. EL2, as we're multiplexing the true EL1
1321 		 * event filter bit for nested.
1322 		 */
1323 		if (kvm_pmc_counts_at_el1(pmc) == kvm_pmc_counts_at_el2(pmc))
1324 			continue;
1325 
1326 		kvm_pmu_create_perf_event(pmc);
1327 		reprogrammed = true;
1328 	}
1329 
1330 	if (reprogrammed)
1331 		kvm_vcpu_pmu_restore_guest(vcpu);
1332 }
1333