xref: /openbmc/linux/arch/x86/kvm/pmu.c (revision 6a5cba7bed35580effda9fb1872b274da47e6b23)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Kernel-based Virtual Machine -- Performance Monitoring Unit support
4  *
5  * Copyright 2015 Red Hat, Inc. and/or its affiliates.
6  *
7  * Authors:
8  *   Avi Kivity   <avi@redhat.com>
9  *   Gleb Natapov <gleb@redhat.com>
10  *   Wei Huang    <wei@redhat.com>
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 
14 #include <linux/types.h>
15 #include <linux/kvm_host.h>
16 #include <linux/perf_event.h>
17 #include <linux/bsearch.h>
18 #include <linux/sort.h>
19 #include <asm/perf_event.h>
20 #include <asm/cpu_device_id.h>
21 #include "x86.h"
22 #include "cpuid.h"
23 #include "lapic.h"
24 #include "pmu.h"
25 
26 /* This is enough to filter the vast majority of currently defined events. */
27 #define KVM_PMU_EVENT_FILTER_MAX_EVENTS 300
28 
29 struct x86_pmu_capability __read_mostly kvm_pmu_cap;
30 EXPORT_SYMBOL_GPL(kvm_pmu_cap);
31 
32 static const struct x86_cpu_id vmx_icl_pebs_cpu[] = {
33 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D, NULL),
34 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X, NULL),
35 	{}
36 };
37 
38 /* NOTE:
39  * - Each perf counter is defined as "struct kvm_pmc";
40  * - There are two types of perf counters: general purpose (gp) and fixed.
41  *   gp counters are stored in gp_counters[] and fixed counters are stored
42  *   in fixed_counters[] respectively. Both of them are part of "struct
43  *   kvm_pmu";
44  * - pmu.c understands the difference between gp counters and fixed counters.
45  *   However AMD doesn't support fixed-counters;
46  * - There are three types of index to access perf counters (PMC):
47  *     1. MSR (named msr): For example Intel has MSR_IA32_PERFCTRn and AMD
48  *        has MSR_K7_PERFCTRn and, for families 15H and later,
49  *        MSR_F15H_PERF_CTRn, where MSR_F15H_PERF_CTR[0-3] are
50  *        aliased to MSR_K7_PERFCTRn.
51  *     2. MSR Index (named idx): This normally is used by RDPMC instruction.
52  *        For instance AMD RDPMC instruction uses 0000_0003h in ECX to access
53  *        C001_0007h (MSR_K7_PERCTR3). Intel has a similar mechanism, except
54  *        that it also supports fixed counters. idx can be used to as index to
55  *        gp and fixed counters.
56  *     3. Global PMC Index (named pmc): pmc is an index specific to PMU
57  *        code. Each pmc, stored in kvm_pmc.idx field, is unique across
58  *        all perf counters (both gp and fixed). The mapping relationship
59  *        between pmc and perf counters is as the following:
60  *        * Intel: [0 .. KVM_INTEL_PMC_MAX_GENERIC-1] <=> gp counters
61  *                 [INTEL_PMC_IDX_FIXED .. INTEL_PMC_IDX_FIXED + 2] <=> fixed
62  *        * AMD:   [0 .. AMD64_NUM_COUNTERS-1] and, for families 15H
63  *          and later, [0 .. AMD64_NUM_COUNTERS_CORE-1] <=> gp counters
64  */
65 
66 static struct kvm_pmu_ops kvm_pmu_ops __read_mostly;
67 
68 #define KVM_X86_PMU_OP(func)					     \
69 	DEFINE_STATIC_CALL_NULL(kvm_x86_pmu_##func,			     \
70 				*(((struct kvm_pmu_ops *)0)->func));
71 #define KVM_X86_PMU_OP_OPTIONAL KVM_X86_PMU_OP
72 #include <asm/kvm-x86-pmu-ops.h>
73 
74 void kvm_pmu_ops_update(const struct kvm_pmu_ops *pmu_ops)
75 {
76 	memcpy(&kvm_pmu_ops, pmu_ops, sizeof(kvm_pmu_ops));
77 
78 #define __KVM_X86_PMU_OP(func) \
79 	static_call_update(kvm_x86_pmu_##func, kvm_pmu_ops.func);
80 #define KVM_X86_PMU_OP(func) \
81 	WARN_ON(!kvm_pmu_ops.func); __KVM_X86_PMU_OP(func)
82 #define KVM_X86_PMU_OP_OPTIONAL __KVM_X86_PMU_OP
83 #include <asm/kvm-x86-pmu-ops.h>
84 #undef __KVM_X86_PMU_OP
85 }
86 
87 static inline bool pmc_is_enabled(struct kvm_pmc *pmc)
88 {
89 	return static_call(kvm_x86_pmu_pmc_is_enabled)(pmc);
90 }
91 
92 static void kvm_pmi_trigger_fn(struct irq_work *irq_work)
93 {
94 	struct kvm_pmu *pmu = container_of(irq_work, struct kvm_pmu, irq_work);
95 	struct kvm_vcpu *vcpu = pmu_to_vcpu(pmu);
96 
97 	kvm_pmu_deliver_pmi(vcpu);
98 }
99 
100 static inline void __kvm_perf_overflow(struct kvm_pmc *pmc, bool in_pmi)
101 {
102 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
103 	bool skip_pmi = false;
104 
105 	if (pmc->perf_event && pmc->perf_event->attr.precise_ip) {
106 		if (!in_pmi) {
107 			/*
108 			 * TODO: KVM is currently _choosing_ to not generate records
109 			 * for emulated instructions, avoiding BUFFER_OVF PMI when
110 			 * there are no records. Strictly speaking, it should be done
111 			 * as well in the right context to improve sampling accuracy.
112 			 */
113 			skip_pmi = true;
114 		} else {
115 			/* Indicate PEBS overflow PMI to guest. */
116 			skip_pmi = __test_and_set_bit(GLOBAL_STATUS_BUFFER_OVF_BIT,
117 						      (unsigned long *)&pmu->global_status);
118 		}
119 	} else {
120 		__set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
121 	}
122 
123 	if (!pmc->intr || skip_pmi)
124 		return;
125 
126 	/*
127 	 * Inject PMI. If vcpu was in a guest mode during NMI PMI
128 	 * can be ejected on a guest mode re-entry. Otherwise we can't
129 	 * be sure that vcpu wasn't executing hlt instruction at the
130 	 * time of vmexit and is not going to re-enter guest mode until
131 	 * woken up. So we should wake it, but this is impossible from
132 	 * NMI context. Do it from irq work instead.
133 	 */
134 	if (in_pmi && !kvm_handling_nmi_from_guest(pmc->vcpu))
135 		irq_work_queue(&pmc_to_pmu(pmc)->irq_work);
136 	else
137 		kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
138 }
139 
140 static void kvm_perf_overflow(struct perf_event *perf_event,
141 			      struct perf_sample_data *data,
142 			      struct pt_regs *regs)
143 {
144 	struct kvm_pmc *pmc = perf_event->overflow_handler_context;
145 
146 	/*
147 	 * Ignore overflow events for counters that are scheduled to be
148 	 * reprogrammed, e.g. if a PMI for the previous event races with KVM's
149 	 * handling of a related guest WRMSR.
150 	 */
151 	if (test_and_set_bit(pmc->idx, pmc_to_pmu(pmc)->reprogram_pmi))
152 		return;
153 
154 	__kvm_perf_overflow(pmc, true);
155 
156 	kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
157 }
158 
159 static int pmc_reprogram_counter(struct kvm_pmc *pmc, u32 type, u64 config,
160 				 bool exclude_user, bool exclude_kernel,
161 				 bool intr)
162 {
163 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
164 	struct perf_event *event;
165 	struct perf_event_attr attr = {
166 		.type = type,
167 		.size = sizeof(attr),
168 		.pinned = true,
169 		.exclude_idle = true,
170 		.exclude_host = 1,
171 		.exclude_user = exclude_user,
172 		.exclude_kernel = exclude_kernel,
173 		.config = config,
174 	};
175 	bool pebs = test_bit(pmc->idx, (unsigned long *)&pmu->pebs_enable);
176 
177 	attr.sample_period = get_sample_period(pmc, pmc->counter);
178 
179 	if ((attr.config & HSW_IN_TX_CHECKPOINTED) &&
180 	    guest_cpuid_is_intel(pmc->vcpu)) {
181 		/*
182 		 * HSW_IN_TX_CHECKPOINTED is not supported with nonzero
183 		 * period. Just clear the sample period so at least
184 		 * allocating the counter doesn't fail.
185 		 */
186 		attr.sample_period = 0;
187 	}
188 	if (pebs) {
189 		/*
190 		 * The non-zero precision level of guest event makes the ordinary
191 		 * guest event becomes a guest PEBS event and triggers the host
192 		 * PEBS PMI handler to determine whether the PEBS overflow PMI
193 		 * comes from the host counters or the guest.
194 		 *
195 		 * For most PEBS hardware events, the difference in the software
196 		 * precision levels of guest and host PEBS events will not affect
197 		 * the accuracy of the PEBS profiling result, because the "event IP"
198 		 * in the PEBS record is calibrated on the guest side.
199 		 *
200 		 * On Icelake everything is fine. Other hardware (GLC+, TNT+) that
201 		 * could possibly care here is unsupported and needs changes.
202 		 */
203 		attr.precise_ip = 1;
204 		if (x86_match_cpu(vmx_icl_pebs_cpu) && pmc->idx == 32)
205 			attr.precise_ip = 3;
206 	}
207 
208 	event = perf_event_create_kernel_counter(&attr, -1, current,
209 						 kvm_perf_overflow, pmc);
210 	if (IS_ERR(event)) {
211 		pr_debug_ratelimited("kvm_pmu: event creation failed %ld for pmc->idx = %d\n",
212 			    PTR_ERR(event), pmc->idx);
213 		return PTR_ERR(event);
214 	}
215 
216 	pmc->perf_event = event;
217 	pmc_to_pmu(pmc)->event_count++;
218 	pmc->is_paused = false;
219 	pmc->intr = intr || pebs;
220 	return 0;
221 }
222 
223 static void pmc_pause_counter(struct kvm_pmc *pmc)
224 {
225 	u64 counter = pmc->counter;
226 
227 	if (!pmc->perf_event || pmc->is_paused)
228 		return;
229 
230 	/* update counter, reset event value to avoid redundant accumulation */
231 	counter += perf_event_pause(pmc->perf_event, true);
232 	pmc->counter = counter & pmc_bitmask(pmc);
233 	pmc->is_paused = true;
234 }
235 
236 static bool pmc_resume_counter(struct kvm_pmc *pmc)
237 {
238 	if (!pmc->perf_event)
239 		return false;
240 
241 	/* recalibrate sample period and check if it's accepted by perf core */
242 	if (is_sampling_event(pmc->perf_event) &&
243 	    perf_event_period(pmc->perf_event,
244 			      get_sample_period(pmc, pmc->counter)))
245 		return false;
246 
247 	if (test_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->pebs_enable) !=
248 	    (!!pmc->perf_event->attr.precise_ip))
249 		return false;
250 
251 	/* reuse perf_event to serve as pmc_reprogram_counter() does*/
252 	perf_event_enable(pmc->perf_event);
253 	pmc->is_paused = false;
254 
255 	return true;
256 }
257 
258 static int cmp_u64(const void *pa, const void *pb)
259 {
260 	u64 a = *(u64 *)pa;
261 	u64 b = *(u64 *)pb;
262 
263 	return (a > b) - (a < b);
264 }
265 
266 static bool check_pmu_event_filter(struct kvm_pmc *pmc)
267 {
268 	struct kvm_pmu_event_filter *filter;
269 	struct kvm *kvm = pmc->vcpu->kvm;
270 	bool allow_event = true;
271 	__u64 key;
272 	int idx;
273 
274 	if (!static_call(kvm_x86_pmu_hw_event_available)(pmc))
275 		return false;
276 
277 	filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
278 	if (!filter)
279 		goto out;
280 
281 	if (pmc_is_gp(pmc)) {
282 		key = pmc->eventsel & (kvm_pmu_ops.EVENTSEL_EVENT |
283 				       ARCH_PERFMON_EVENTSEL_UMASK);
284 		if (bsearch(&key, filter->events, filter->nevents,
285 			    sizeof(__u64), cmp_u64))
286 			allow_event = filter->action == KVM_PMU_EVENT_ALLOW;
287 		else
288 			allow_event = filter->action == KVM_PMU_EVENT_DENY;
289 	} else {
290 		idx = pmc->idx - INTEL_PMC_IDX_FIXED;
291 		if (filter->action == KVM_PMU_EVENT_DENY &&
292 		    test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
293 			allow_event = false;
294 		if (filter->action == KVM_PMU_EVENT_ALLOW &&
295 		    !test_bit(idx, (ulong *)&filter->fixed_counter_bitmap))
296 			allow_event = false;
297 	}
298 
299 out:
300 	return allow_event;
301 }
302 
303 static void reprogram_counter(struct kvm_pmc *pmc)
304 {
305 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
306 	u64 eventsel = pmc->eventsel;
307 	u64 new_config = eventsel;
308 	u8 fixed_ctr_ctrl;
309 
310 	pmc_pause_counter(pmc);
311 
312 	if (!pmc_speculative_in_use(pmc) || !pmc_is_enabled(pmc))
313 		goto reprogram_complete;
314 
315 	if (!check_pmu_event_filter(pmc))
316 		goto reprogram_complete;
317 
318 	if (pmc->counter < pmc->prev_counter)
319 		__kvm_perf_overflow(pmc, false);
320 
321 	if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
322 		printk_once("kvm pmu: pin control bit is ignored\n");
323 
324 	if (pmc_is_fixed(pmc)) {
325 		fixed_ctr_ctrl = fixed_ctrl_field(pmu->fixed_ctr_ctrl,
326 						  pmc->idx - INTEL_PMC_IDX_FIXED);
327 		if (fixed_ctr_ctrl & 0x1)
328 			eventsel |= ARCH_PERFMON_EVENTSEL_OS;
329 		if (fixed_ctr_ctrl & 0x2)
330 			eventsel |= ARCH_PERFMON_EVENTSEL_USR;
331 		if (fixed_ctr_ctrl & 0x8)
332 			eventsel |= ARCH_PERFMON_EVENTSEL_INT;
333 		new_config = (u64)fixed_ctr_ctrl;
334 	}
335 
336 	if (pmc->current_config == new_config && pmc_resume_counter(pmc))
337 		goto reprogram_complete;
338 
339 	pmc_release_perf_event(pmc);
340 
341 	pmc->current_config = new_config;
342 
343 	/*
344 	 * If reprogramming fails, e.g. due to contention, leave the counter's
345 	 * regprogram bit set, i.e. opportunistically try again on the next PMU
346 	 * refresh.  Don't make a new request as doing so can stall the guest
347 	 * if reprogramming repeatedly fails.
348 	 */
349 	if (pmc_reprogram_counter(pmc, PERF_TYPE_RAW,
350 				  (eventsel & pmu->raw_event_mask),
351 				  !(eventsel & ARCH_PERFMON_EVENTSEL_USR),
352 				  !(eventsel & ARCH_PERFMON_EVENTSEL_OS),
353 				  eventsel & ARCH_PERFMON_EVENTSEL_INT))
354 		return;
355 
356 reprogram_complete:
357 	clear_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->reprogram_pmi);
358 	pmc->prev_counter = 0;
359 }
360 
361 void kvm_pmu_handle_event(struct kvm_vcpu *vcpu)
362 {
363 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
364 	int bit;
365 
366 	for_each_set_bit(bit, pmu->reprogram_pmi, X86_PMC_IDX_MAX) {
367 		struct kvm_pmc *pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, bit);
368 
369 		if (unlikely(!pmc)) {
370 			clear_bit(bit, pmu->reprogram_pmi);
371 			continue;
372 		}
373 
374 		reprogram_counter(pmc);
375 	}
376 
377 	/*
378 	 * Unused perf_events are only released if the corresponding MSRs
379 	 * weren't accessed during the last vCPU time slice. kvm_arch_sched_in
380 	 * triggers KVM_REQ_PMU if cleanup is needed.
381 	 */
382 	if (unlikely(pmu->need_cleanup))
383 		kvm_pmu_cleanup(vcpu);
384 }
385 
386 /* check if idx is a valid index to access PMU */
387 bool kvm_pmu_is_valid_rdpmc_ecx(struct kvm_vcpu *vcpu, unsigned int idx)
388 {
389 	return static_call(kvm_x86_pmu_is_valid_rdpmc_ecx)(vcpu, idx);
390 }
391 
392 bool is_vmware_backdoor_pmc(u32 pmc_idx)
393 {
394 	switch (pmc_idx) {
395 	case VMWARE_BACKDOOR_PMC_HOST_TSC:
396 	case VMWARE_BACKDOOR_PMC_REAL_TIME:
397 	case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
398 		return true;
399 	}
400 	return false;
401 }
402 
403 static int kvm_pmu_rdpmc_vmware(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
404 {
405 	u64 ctr_val;
406 
407 	switch (idx) {
408 	case VMWARE_BACKDOOR_PMC_HOST_TSC:
409 		ctr_val = rdtsc();
410 		break;
411 	case VMWARE_BACKDOOR_PMC_REAL_TIME:
412 		ctr_val = ktime_get_boottime_ns();
413 		break;
414 	case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
415 		ctr_val = ktime_get_boottime_ns() +
416 			vcpu->kvm->arch.kvmclock_offset;
417 		break;
418 	default:
419 		return 1;
420 	}
421 
422 	*data = ctr_val;
423 	return 0;
424 }
425 
426 int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
427 {
428 	bool fast_mode = idx & (1u << 31);
429 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
430 	struct kvm_pmc *pmc;
431 	u64 mask = fast_mode ? ~0u : ~0ull;
432 
433 	if (!pmu->version)
434 		return 1;
435 
436 	if (is_vmware_backdoor_pmc(idx))
437 		return kvm_pmu_rdpmc_vmware(vcpu, idx, data);
438 
439 	pmc = static_call(kvm_x86_pmu_rdpmc_ecx_to_pmc)(vcpu, idx, &mask);
440 	if (!pmc)
441 		return 1;
442 
443 	if (!(kvm_read_cr4(vcpu) & X86_CR4_PCE) &&
444 	    (static_call(kvm_x86_get_cpl)(vcpu) != 0) &&
445 	    (kvm_read_cr0(vcpu) & X86_CR0_PE))
446 		return 1;
447 
448 	*data = pmc_read_counter(pmc) & mask;
449 	return 0;
450 }
451 
452 void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
453 {
454 	if (lapic_in_kernel(vcpu)) {
455 		static_call_cond(kvm_x86_pmu_deliver_pmi)(vcpu);
456 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
457 	}
458 }
459 
460 bool kvm_pmu_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
461 {
462 	return static_call(kvm_x86_pmu_msr_idx_to_pmc)(vcpu, msr) ||
463 		static_call(kvm_x86_pmu_is_valid_msr)(vcpu, msr);
464 }
465 
466 static void kvm_pmu_mark_pmc_in_use(struct kvm_vcpu *vcpu, u32 msr)
467 {
468 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
469 	struct kvm_pmc *pmc = static_call(kvm_x86_pmu_msr_idx_to_pmc)(vcpu, msr);
470 
471 	if (pmc)
472 		__set_bit(pmc->idx, pmu->pmc_in_use);
473 }
474 
475 int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
476 {
477 	return static_call(kvm_x86_pmu_get_msr)(vcpu, msr_info);
478 }
479 
480 int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
481 {
482 	kvm_pmu_mark_pmc_in_use(vcpu, msr_info->index);
483 	return static_call(kvm_x86_pmu_set_msr)(vcpu, msr_info);
484 }
485 
486 /* refresh PMU settings. This function generally is called when underlying
487  * settings are changed (such as changes of PMU CPUID by guest VMs), which
488  * should rarely happen.
489  */
490 void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
491 {
492 	static_call(kvm_x86_pmu_refresh)(vcpu);
493 }
494 
495 void kvm_pmu_reset(struct kvm_vcpu *vcpu)
496 {
497 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
498 
499 	irq_work_sync(&pmu->irq_work);
500 	static_call(kvm_x86_pmu_reset)(vcpu);
501 }
502 
503 void kvm_pmu_init(struct kvm_vcpu *vcpu)
504 {
505 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
506 
507 	memset(pmu, 0, sizeof(*pmu));
508 	static_call(kvm_x86_pmu_init)(vcpu);
509 	init_irq_work(&pmu->irq_work, kvm_pmi_trigger_fn);
510 	pmu->event_count = 0;
511 	pmu->need_cleanup = false;
512 	kvm_pmu_refresh(vcpu);
513 }
514 
515 /* Release perf_events for vPMCs that have been unused for a full time slice.  */
516 void kvm_pmu_cleanup(struct kvm_vcpu *vcpu)
517 {
518 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
519 	struct kvm_pmc *pmc = NULL;
520 	DECLARE_BITMAP(bitmask, X86_PMC_IDX_MAX);
521 	int i;
522 
523 	pmu->need_cleanup = false;
524 
525 	bitmap_andnot(bitmask, pmu->all_valid_pmc_idx,
526 		      pmu->pmc_in_use, X86_PMC_IDX_MAX);
527 
528 	for_each_set_bit(i, bitmask, X86_PMC_IDX_MAX) {
529 		pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, i);
530 
531 		if (pmc && pmc->perf_event && !pmc_speculative_in_use(pmc))
532 			pmc_stop_counter(pmc);
533 	}
534 
535 	static_call_cond(kvm_x86_pmu_cleanup)(vcpu);
536 
537 	bitmap_zero(pmu->pmc_in_use, X86_PMC_IDX_MAX);
538 }
539 
540 void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
541 {
542 	kvm_pmu_reset(vcpu);
543 }
544 
545 static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
546 {
547 	pmc->prev_counter = pmc->counter;
548 	pmc->counter = (pmc->counter + 1) & pmc_bitmask(pmc);
549 	kvm_pmu_request_counter_reprogam(pmc);
550 }
551 
552 static inline bool eventsel_match_perf_hw_id(struct kvm_pmc *pmc,
553 	unsigned int perf_hw_id)
554 {
555 	return !((pmc->eventsel ^ perf_get_hw_event_config(perf_hw_id)) &
556 		AMD64_RAW_EVENT_MASK_NB);
557 }
558 
559 static inline bool cpl_is_matched(struct kvm_pmc *pmc)
560 {
561 	bool select_os, select_user;
562 	u64 config;
563 
564 	if (pmc_is_gp(pmc)) {
565 		config = pmc->eventsel;
566 		select_os = config & ARCH_PERFMON_EVENTSEL_OS;
567 		select_user = config & ARCH_PERFMON_EVENTSEL_USR;
568 	} else {
569 		config = fixed_ctrl_field(pmc_to_pmu(pmc)->fixed_ctr_ctrl,
570 					  pmc->idx - INTEL_PMC_IDX_FIXED);
571 		select_os = config & 0x1;
572 		select_user = config & 0x2;
573 	}
574 
575 	return (static_call(kvm_x86_get_cpl)(pmc->vcpu) == 0) ? select_os : select_user;
576 }
577 
578 void kvm_pmu_trigger_event(struct kvm_vcpu *vcpu, u64 perf_hw_id)
579 {
580 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
581 	struct kvm_pmc *pmc;
582 	int i;
583 
584 	for_each_set_bit(i, pmu->all_valid_pmc_idx, X86_PMC_IDX_MAX) {
585 		pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, i);
586 
587 		if (!pmc || !pmc_is_enabled(pmc) || !pmc_speculative_in_use(pmc))
588 			continue;
589 
590 		/* Ignore checks for edge detect, pin control, invert and CMASK bits */
591 		if (eventsel_match_perf_hw_id(pmc, perf_hw_id) && cpl_is_matched(pmc))
592 			kvm_pmu_incr_counter(pmc);
593 	}
594 }
595 EXPORT_SYMBOL_GPL(kvm_pmu_trigger_event);
596 
597 int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
598 {
599 	struct kvm_pmu_event_filter tmp, *filter;
600 	struct kvm_vcpu *vcpu;
601 	unsigned long i;
602 	size_t size;
603 	int r;
604 
605 	if (copy_from_user(&tmp, argp, sizeof(tmp)))
606 		return -EFAULT;
607 
608 	if (tmp.action != KVM_PMU_EVENT_ALLOW &&
609 	    tmp.action != KVM_PMU_EVENT_DENY)
610 		return -EINVAL;
611 
612 	if (tmp.flags != 0)
613 		return -EINVAL;
614 
615 	if (tmp.nevents > KVM_PMU_EVENT_FILTER_MAX_EVENTS)
616 		return -E2BIG;
617 
618 	size = struct_size(filter, events, tmp.nevents);
619 	filter = kmalloc(size, GFP_KERNEL_ACCOUNT);
620 	if (!filter)
621 		return -ENOMEM;
622 
623 	r = -EFAULT;
624 	if (copy_from_user(filter, argp, size))
625 		goto cleanup;
626 
627 	/* Ensure nevents can't be changed between the user copies. */
628 	*filter = tmp;
629 
630 	/*
631 	 * Sort the in-kernel list so that we can search it with bsearch.
632 	 */
633 	sort(&filter->events, filter->nevents, sizeof(__u64), cmp_u64, NULL);
634 
635 	mutex_lock(&kvm->lock);
636 	filter = rcu_replace_pointer(kvm->arch.pmu_event_filter, filter,
637 				     mutex_is_locked(&kvm->lock));
638 	synchronize_srcu_expedited(&kvm->srcu);
639 
640 	BUILD_BUG_ON(sizeof(((struct kvm_pmu *)0)->reprogram_pmi) >
641 		     sizeof(((struct kvm_pmu *)0)->__reprogram_pmi));
642 
643 	kvm_for_each_vcpu(i, vcpu, kvm)
644 		atomic64_set(&vcpu_to_pmu(vcpu)->__reprogram_pmi, -1ull);
645 
646 	kvm_make_all_cpus_request(kvm, KVM_REQ_PMU);
647 
648 	mutex_unlock(&kvm->lock);
649 
650 	r = 0;
651 cleanup:
652 	kfree(filter);
653 	return r;
654 }
655