xref: /openbmc/linux/arch/x86/kvm/pmu.c (revision 404e077a)
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 /* Precise Distribution of Instructions Retired (PDIR) */
33 static const struct x86_cpu_id vmx_pebs_pdir_cpu[] = {
34 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_D, NULL),
35 	X86_MATCH_INTEL_FAM6_MODEL(ICELAKE_X, NULL),
36 	/* Instruction-Accurate PDIR (PDIR++) */
37 	X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X, NULL),
38 	{}
39 };
40 
41 /* Precise Distribution (PDist) */
42 static const struct x86_cpu_id vmx_pebs_pdist_cpu[] = {
43 	X86_MATCH_INTEL_FAM6_MODEL(SAPPHIRERAPIDS_X, NULL),
44 	{}
45 };
46 
47 /* NOTE:
48  * - Each perf counter is defined as "struct kvm_pmc";
49  * - There are two types of perf counters: general purpose (gp) and fixed.
50  *   gp counters are stored in gp_counters[] and fixed counters are stored
51  *   in fixed_counters[] respectively. Both of them are part of "struct
52  *   kvm_pmu";
53  * - pmu.c understands the difference between gp counters and fixed counters.
54  *   However AMD doesn't support fixed-counters;
55  * - There are three types of index to access perf counters (PMC):
56  *     1. MSR (named msr): For example Intel has MSR_IA32_PERFCTRn and AMD
57  *        has MSR_K7_PERFCTRn and, for families 15H and later,
58  *        MSR_F15H_PERF_CTRn, where MSR_F15H_PERF_CTR[0-3] are
59  *        aliased to MSR_K7_PERFCTRn.
60  *     2. MSR Index (named idx): This normally is used by RDPMC instruction.
61  *        For instance AMD RDPMC instruction uses 0000_0003h in ECX to access
62  *        C001_0007h (MSR_K7_PERCTR3). Intel has a similar mechanism, except
63  *        that it also supports fixed counters. idx can be used to as index to
64  *        gp and fixed counters.
65  *     3. Global PMC Index (named pmc): pmc is an index specific to PMU
66  *        code. Each pmc, stored in kvm_pmc.idx field, is unique across
67  *        all perf counters (both gp and fixed). The mapping relationship
68  *        between pmc and perf counters is as the following:
69  *        * Intel: [0 .. KVM_INTEL_PMC_MAX_GENERIC-1] <=> gp counters
70  *                 [INTEL_PMC_IDX_FIXED .. INTEL_PMC_IDX_FIXED + 2] <=> fixed
71  *        * AMD:   [0 .. AMD64_NUM_COUNTERS-1] and, for families 15H
72  *          and later, [0 .. AMD64_NUM_COUNTERS_CORE-1] <=> gp counters
73  */
74 
75 static struct kvm_pmu_ops kvm_pmu_ops __read_mostly;
76 
77 #define KVM_X86_PMU_OP(func)					     \
78 	DEFINE_STATIC_CALL_NULL(kvm_x86_pmu_##func,			     \
79 				*(((struct kvm_pmu_ops *)0)->func));
80 #define KVM_X86_PMU_OP_OPTIONAL KVM_X86_PMU_OP
81 #include <asm/kvm-x86-pmu-ops.h>
82 
83 void kvm_pmu_ops_update(const struct kvm_pmu_ops *pmu_ops)
84 {
85 	memcpy(&kvm_pmu_ops, pmu_ops, sizeof(kvm_pmu_ops));
86 
87 #define __KVM_X86_PMU_OP(func) \
88 	static_call_update(kvm_x86_pmu_##func, kvm_pmu_ops.func);
89 #define KVM_X86_PMU_OP(func) \
90 	WARN_ON(!kvm_pmu_ops.func); __KVM_X86_PMU_OP(func)
91 #define KVM_X86_PMU_OP_OPTIONAL __KVM_X86_PMU_OP
92 #include <asm/kvm-x86-pmu-ops.h>
93 #undef __KVM_X86_PMU_OP
94 }
95 
96 static void kvm_pmi_trigger_fn(struct irq_work *irq_work)
97 {
98 	struct kvm_pmu *pmu = container_of(irq_work, struct kvm_pmu, irq_work);
99 	struct kvm_vcpu *vcpu = pmu_to_vcpu(pmu);
100 
101 	kvm_pmu_deliver_pmi(vcpu);
102 }
103 
104 static inline void __kvm_perf_overflow(struct kvm_pmc *pmc, bool in_pmi)
105 {
106 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
107 	bool skip_pmi = false;
108 
109 	if (pmc->perf_event && pmc->perf_event->attr.precise_ip) {
110 		if (!in_pmi) {
111 			/*
112 			 * TODO: KVM is currently _choosing_ to not generate records
113 			 * for emulated instructions, avoiding BUFFER_OVF PMI when
114 			 * there are no records. Strictly speaking, it should be done
115 			 * as well in the right context to improve sampling accuracy.
116 			 */
117 			skip_pmi = true;
118 		} else {
119 			/* Indicate PEBS overflow PMI to guest. */
120 			skip_pmi = __test_and_set_bit(GLOBAL_STATUS_BUFFER_OVF_BIT,
121 						      (unsigned long *)&pmu->global_status);
122 		}
123 	} else {
124 		__set_bit(pmc->idx, (unsigned long *)&pmu->global_status);
125 	}
126 
127 	if (!pmc->intr || skip_pmi)
128 		return;
129 
130 	/*
131 	 * Inject PMI. If vcpu was in a guest mode during NMI PMI
132 	 * can be ejected on a guest mode re-entry. Otherwise we can't
133 	 * be sure that vcpu wasn't executing hlt instruction at the
134 	 * time of vmexit and is not going to re-enter guest mode until
135 	 * woken up. So we should wake it, but this is impossible from
136 	 * NMI context. Do it from irq work instead.
137 	 */
138 	if (in_pmi && !kvm_handling_nmi_from_guest(pmc->vcpu))
139 		irq_work_queue(&pmc_to_pmu(pmc)->irq_work);
140 	else
141 		kvm_make_request(KVM_REQ_PMI, pmc->vcpu);
142 }
143 
144 static void kvm_perf_overflow(struct perf_event *perf_event,
145 			      struct perf_sample_data *data,
146 			      struct pt_regs *regs)
147 {
148 	struct kvm_pmc *pmc = perf_event->overflow_handler_context;
149 
150 	/*
151 	 * Ignore overflow events for counters that are scheduled to be
152 	 * reprogrammed, e.g. if a PMI for the previous event races with KVM's
153 	 * handling of a related guest WRMSR.
154 	 */
155 	if (test_and_set_bit(pmc->idx, pmc_to_pmu(pmc)->reprogram_pmi))
156 		return;
157 
158 	__kvm_perf_overflow(pmc, true);
159 
160 	kvm_make_request(KVM_REQ_PMU, pmc->vcpu);
161 }
162 
163 static u64 pmc_get_pebs_precise_level(struct kvm_pmc *pmc)
164 {
165 	/*
166 	 * For some model specific pebs counters with special capabilities
167 	 * (PDIR, PDIR++, PDIST), KVM needs to raise the event precise
168 	 * level to the maximum value (currently 3, backwards compatible)
169 	 * so that the perf subsystem would assign specific hardware counter
170 	 * with that capability for vPMC.
171 	 */
172 	if ((pmc->idx == 0 && x86_match_cpu(vmx_pebs_pdist_cpu)) ||
173 	    (pmc->idx == 32 && x86_match_cpu(vmx_pebs_pdir_cpu)))
174 		return 3;
175 
176 	/*
177 	 * The non-zero precision level of guest event makes the ordinary
178 	 * guest event becomes a guest PEBS event and triggers the host
179 	 * PEBS PMI handler to determine whether the PEBS overflow PMI
180 	 * comes from the host counters or the guest.
181 	 */
182 	return 1;
183 }
184 
185 static int pmc_reprogram_counter(struct kvm_pmc *pmc, u32 type, u64 config,
186 				 bool exclude_user, bool exclude_kernel,
187 				 bool intr)
188 {
189 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
190 	struct perf_event *event;
191 	struct perf_event_attr attr = {
192 		.type = type,
193 		.size = sizeof(attr),
194 		.pinned = true,
195 		.exclude_idle = true,
196 		.exclude_host = 1,
197 		.exclude_user = exclude_user,
198 		.exclude_kernel = exclude_kernel,
199 		.config = config,
200 	};
201 	bool pebs = test_bit(pmc->idx, (unsigned long *)&pmu->pebs_enable);
202 
203 	attr.sample_period = get_sample_period(pmc, pmc->counter);
204 
205 	if ((attr.config & HSW_IN_TX_CHECKPOINTED) &&
206 	    guest_cpuid_is_intel(pmc->vcpu)) {
207 		/*
208 		 * HSW_IN_TX_CHECKPOINTED is not supported with nonzero
209 		 * period. Just clear the sample period so at least
210 		 * allocating the counter doesn't fail.
211 		 */
212 		attr.sample_period = 0;
213 	}
214 	if (pebs) {
215 		/*
216 		 * For most PEBS hardware events, the difference in the software
217 		 * precision levels of guest and host PEBS events will not affect
218 		 * the accuracy of the PEBS profiling result, because the "event IP"
219 		 * in the PEBS record is calibrated on the guest side.
220 		 */
221 		attr.precise_ip = pmc_get_pebs_precise_level(pmc);
222 	}
223 
224 	event = perf_event_create_kernel_counter(&attr, -1, current,
225 						 kvm_perf_overflow, pmc);
226 	if (IS_ERR(event)) {
227 		pr_debug_ratelimited("kvm_pmu: event creation failed %ld for pmc->idx = %d\n",
228 			    PTR_ERR(event), pmc->idx);
229 		return PTR_ERR(event);
230 	}
231 
232 	pmc->perf_event = event;
233 	pmc_to_pmu(pmc)->event_count++;
234 	pmc->is_paused = false;
235 	pmc->intr = intr || pebs;
236 	return 0;
237 }
238 
239 static void pmc_pause_counter(struct kvm_pmc *pmc)
240 {
241 	u64 counter = pmc->counter;
242 
243 	if (!pmc->perf_event || pmc->is_paused)
244 		return;
245 
246 	/* update counter, reset event value to avoid redundant accumulation */
247 	counter += perf_event_pause(pmc->perf_event, true);
248 	pmc->counter = counter & pmc_bitmask(pmc);
249 	pmc->is_paused = true;
250 }
251 
252 static bool pmc_resume_counter(struct kvm_pmc *pmc)
253 {
254 	if (!pmc->perf_event)
255 		return false;
256 
257 	/* recalibrate sample period and check if it's accepted by perf core */
258 	if (is_sampling_event(pmc->perf_event) &&
259 	    perf_event_period(pmc->perf_event,
260 			      get_sample_period(pmc, pmc->counter)))
261 		return false;
262 
263 	if (test_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->pebs_enable) !=
264 	    (!!pmc->perf_event->attr.precise_ip))
265 		return false;
266 
267 	/* reuse perf_event to serve as pmc_reprogram_counter() does*/
268 	perf_event_enable(pmc->perf_event);
269 	pmc->is_paused = false;
270 
271 	return true;
272 }
273 
274 static int filter_cmp(const void *pa, const void *pb, u64 mask)
275 {
276 	u64 a = *(u64 *)pa & mask;
277 	u64 b = *(u64 *)pb & mask;
278 
279 	return (a > b) - (a < b);
280 }
281 
282 
283 static int filter_sort_cmp(const void *pa, const void *pb)
284 {
285 	return filter_cmp(pa, pb, (KVM_PMU_MASKED_ENTRY_EVENT_SELECT |
286 				   KVM_PMU_MASKED_ENTRY_EXCLUDE));
287 }
288 
289 /*
290  * For the event filter, searching is done on the 'includes' list and
291  * 'excludes' list separately rather than on the 'events' list (which
292  * has both).  As a result the exclude bit can be ignored.
293  */
294 static int filter_event_cmp(const void *pa, const void *pb)
295 {
296 	return filter_cmp(pa, pb, (KVM_PMU_MASKED_ENTRY_EVENT_SELECT));
297 }
298 
299 static int find_filter_index(u64 *events, u64 nevents, u64 key)
300 {
301 	u64 *fe = bsearch(&key, events, nevents, sizeof(events[0]),
302 			  filter_event_cmp);
303 
304 	if (!fe)
305 		return -1;
306 
307 	return fe - events;
308 }
309 
310 static bool is_filter_entry_match(u64 filter_event, u64 umask)
311 {
312 	u64 mask = filter_event >> (KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT - 8);
313 	u64 match = filter_event & KVM_PMU_MASKED_ENTRY_UMASK_MATCH;
314 
315 	BUILD_BUG_ON((KVM_PMU_ENCODE_MASKED_ENTRY(0, 0xff, 0, false) >>
316 		     (KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT - 8)) !=
317 		     ARCH_PERFMON_EVENTSEL_UMASK);
318 
319 	return (umask & mask) == match;
320 }
321 
322 static bool filter_contains_match(u64 *events, u64 nevents, u64 eventsel)
323 {
324 	u64 event_select = eventsel & kvm_pmu_ops.EVENTSEL_EVENT;
325 	u64 umask = eventsel & ARCH_PERFMON_EVENTSEL_UMASK;
326 	int i, index;
327 
328 	index = find_filter_index(events, nevents, event_select);
329 	if (index < 0)
330 		return false;
331 
332 	/*
333 	 * Entries are sorted by the event select.  Walk the list in both
334 	 * directions to process all entries with the targeted event select.
335 	 */
336 	for (i = index; i < nevents; i++) {
337 		if (filter_event_cmp(&events[i], &event_select))
338 			break;
339 
340 		if (is_filter_entry_match(events[i], umask))
341 			return true;
342 	}
343 
344 	for (i = index - 1; i >= 0; i--) {
345 		if (filter_event_cmp(&events[i], &event_select))
346 			break;
347 
348 		if (is_filter_entry_match(events[i], umask))
349 			return true;
350 	}
351 
352 	return false;
353 }
354 
355 static bool is_gp_event_allowed(struct kvm_x86_pmu_event_filter *f,
356 				u64 eventsel)
357 {
358 	if (filter_contains_match(f->includes, f->nr_includes, eventsel) &&
359 	    !filter_contains_match(f->excludes, f->nr_excludes, eventsel))
360 		return f->action == KVM_PMU_EVENT_ALLOW;
361 
362 	return f->action == KVM_PMU_EVENT_DENY;
363 }
364 
365 static bool is_fixed_event_allowed(struct kvm_x86_pmu_event_filter *filter,
366 				   int idx)
367 {
368 	int fixed_idx = idx - INTEL_PMC_IDX_FIXED;
369 
370 	if (filter->action == KVM_PMU_EVENT_DENY &&
371 	    test_bit(fixed_idx, (ulong *)&filter->fixed_counter_bitmap))
372 		return false;
373 	if (filter->action == KVM_PMU_EVENT_ALLOW &&
374 	    !test_bit(fixed_idx, (ulong *)&filter->fixed_counter_bitmap))
375 		return false;
376 
377 	return true;
378 }
379 
380 static bool check_pmu_event_filter(struct kvm_pmc *pmc)
381 {
382 	struct kvm_x86_pmu_event_filter *filter;
383 	struct kvm *kvm = pmc->vcpu->kvm;
384 
385 	if (!static_call(kvm_x86_pmu_hw_event_available)(pmc))
386 		return false;
387 
388 	filter = srcu_dereference(kvm->arch.pmu_event_filter, &kvm->srcu);
389 	if (!filter)
390 		return true;
391 
392 	if (pmc_is_gp(pmc))
393 		return is_gp_event_allowed(filter, pmc->eventsel);
394 
395 	return is_fixed_event_allowed(filter, pmc->idx);
396 }
397 
398 static bool pmc_event_is_allowed(struct kvm_pmc *pmc)
399 {
400 	return pmc_is_globally_enabled(pmc) && pmc_speculative_in_use(pmc) &&
401 	       check_pmu_event_filter(pmc);
402 }
403 
404 static void reprogram_counter(struct kvm_pmc *pmc)
405 {
406 	struct kvm_pmu *pmu = pmc_to_pmu(pmc);
407 	u64 eventsel = pmc->eventsel;
408 	u64 new_config = eventsel;
409 	u8 fixed_ctr_ctrl;
410 
411 	pmc_pause_counter(pmc);
412 
413 	if (!pmc_event_is_allowed(pmc))
414 		goto reprogram_complete;
415 
416 	if (pmc->counter < pmc->prev_counter)
417 		__kvm_perf_overflow(pmc, false);
418 
419 	if (eventsel & ARCH_PERFMON_EVENTSEL_PIN_CONTROL)
420 		printk_once("kvm pmu: pin control bit is ignored\n");
421 
422 	if (pmc_is_fixed(pmc)) {
423 		fixed_ctr_ctrl = fixed_ctrl_field(pmu->fixed_ctr_ctrl,
424 						  pmc->idx - INTEL_PMC_IDX_FIXED);
425 		if (fixed_ctr_ctrl & 0x1)
426 			eventsel |= ARCH_PERFMON_EVENTSEL_OS;
427 		if (fixed_ctr_ctrl & 0x2)
428 			eventsel |= ARCH_PERFMON_EVENTSEL_USR;
429 		if (fixed_ctr_ctrl & 0x8)
430 			eventsel |= ARCH_PERFMON_EVENTSEL_INT;
431 		new_config = (u64)fixed_ctr_ctrl;
432 	}
433 
434 	if (pmc->current_config == new_config && pmc_resume_counter(pmc))
435 		goto reprogram_complete;
436 
437 	pmc_release_perf_event(pmc);
438 
439 	pmc->current_config = new_config;
440 
441 	/*
442 	 * If reprogramming fails, e.g. due to contention, leave the counter's
443 	 * regprogram bit set, i.e. opportunistically try again on the next PMU
444 	 * refresh.  Don't make a new request as doing so can stall the guest
445 	 * if reprogramming repeatedly fails.
446 	 */
447 	if (pmc_reprogram_counter(pmc, PERF_TYPE_RAW,
448 				  (eventsel & pmu->raw_event_mask),
449 				  !(eventsel & ARCH_PERFMON_EVENTSEL_USR),
450 				  !(eventsel & ARCH_PERFMON_EVENTSEL_OS),
451 				  eventsel & ARCH_PERFMON_EVENTSEL_INT))
452 		return;
453 
454 reprogram_complete:
455 	clear_bit(pmc->idx, (unsigned long *)&pmc_to_pmu(pmc)->reprogram_pmi);
456 	pmc->prev_counter = 0;
457 }
458 
459 void kvm_pmu_handle_event(struct kvm_vcpu *vcpu)
460 {
461 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
462 	int bit;
463 
464 	for_each_set_bit(bit, pmu->reprogram_pmi, X86_PMC_IDX_MAX) {
465 		struct kvm_pmc *pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, bit);
466 
467 		if (unlikely(!pmc)) {
468 			clear_bit(bit, pmu->reprogram_pmi);
469 			continue;
470 		}
471 
472 		reprogram_counter(pmc);
473 	}
474 
475 	/*
476 	 * Unused perf_events are only released if the corresponding MSRs
477 	 * weren't accessed during the last vCPU time slice. kvm_arch_sched_in
478 	 * triggers KVM_REQ_PMU if cleanup is needed.
479 	 */
480 	if (unlikely(pmu->need_cleanup))
481 		kvm_pmu_cleanup(vcpu);
482 }
483 
484 /* check if idx is a valid index to access PMU */
485 bool kvm_pmu_is_valid_rdpmc_ecx(struct kvm_vcpu *vcpu, unsigned int idx)
486 {
487 	return static_call(kvm_x86_pmu_is_valid_rdpmc_ecx)(vcpu, idx);
488 }
489 
490 bool is_vmware_backdoor_pmc(u32 pmc_idx)
491 {
492 	switch (pmc_idx) {
493 	case VMWARE_BACKDOOR_PMC_HOST_TSC:
494 	case VMWARE_BACKDOOR_PMC_REAL_TIME:
495 	case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
496 		return true;
497 	}
498 	return false;
499 }
500 
501 static int kvm_pmu_rdpmc_vmware(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
502 {
503 	u64 ctr_val;
504 
505 	switch (idx) {
506 	case VMWARE_BACKDOOR_PMC_HOST_TSC:
507 		ctr_val = rdtsc();
508 		break;
509 	case VMWARE_BACKDOOR_PMC_REAL_TIME:
510 		ctr_val = ktime_get_boottime_ns();
511 		break;
512 	case VMWARE_BACKDOOR_PMC_APPARENT_TIME:
513 		ctr_val = ktime_get_boottime_ns() +
514 			vcpu->kvm->arch.kvmclock_offset;
515 		break;
516 	default:
517 		return 1;
518 	}
519 
520 	*data = ctr_val;
521 	return 0;
522 }
523 
524 int kvm_pmu_rdpmc(struct kvm_vcpu *vcpu, unsigned idx, u64 *data)
525 {
526 	bool fast_mode = idx & (1u << 31);
527 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
528 	struct kvm_pmc *pmc;
529 	u64 mask = fast_mode ? ~0u : ~0ull;
530 
531 	if (!pmu->version)
532 		return 1;
533 
534 	if (is_vmware_backdoor_pmc(idx))
535 		return kvm_pmu_rdpmc_vmware(vcpu, idx, data);
536 
537 	pmc = static_call(kvm_x86_pmu_rdpmc_ecx_to_pmc)(vcpu, idx, &mask);
538 	if (!pmc)
539 		return 1;
540 
541 	if (!kvm_is_cr4_bit_set(vcpu, X86_CR4_PCE) &&
542 	    (static_call(kvm_x86_get_cpl)(vcpu) != 0) &&
543 	    kvm_is_cr0_bit_set(vcpu, X86_CR0_PE))
544 		return 1;
545 
546 	*data = pmc_read_counter(pmc) & mask;
547 	return 0;
548 }
549 
550 void kvm_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
551 {
552 	if (lapic_in_kernel(vcpu)) {
553 		static_call_cond(kvm_x86_pmu_deliver_pmi)(vcpu);
554 		kvm_apic_local_deliver(vcpu->arch.apic, APIC_LVTPC);
555 	}
556 }
557 
558 bool kvm_pmu_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
559 {
560 	switch (msr) {
561 	case MSR_CORE_PERF_GLOBAL_STATUS:
562 	case MSR_CORE_PERF_GLOBAL_CTRL:
563 	case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
564 		return kvm_pmu_has_perf_global_ctrl(vcpu_to_pmu(vcpu));
565 	default:
566 		break;
567 	}
568 	return static_call(kvm_x86_pmu_msr_idx_to_pmc)(vcpu, msr) ||
569 		static_call(kvm_x86_pmu_is_valid_msr)(vcpu, msr);
570 }
571 
572 static void kvm_pmu_mark_pmc_in_use(struct kvm_vcpu *vcpu, u32 msr)
573 {
574 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
575 	struct kvm_pmc *pmc = static_call(kvm_x86_pmu_msr_idx_to_pmc)(vcpu, msr);
576 
577 	if (pmc)
578 		__set_bit(pmc->idx, pmu->pmc_in_use);
579 }
580 
581 int kvm_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
582 {
583 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
584 	u32 msr = msr_info->index;
585 
586 	switch (msr) {
587 	case MSR_CORE_PERF_GLOBAL_STATUS:
588 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
589 		msr_info->data = pmu->global_status;
590 		break;
591 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
592 	case MSR_CORE_PERF_GLOBAL_CTRL:
593 		msr_info->data = pmu->global_ctrl;
594 		break;
595 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
596 	case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
597 		msr_info->data = 0;
598 		break;
599 	default:
600 		return static_call(kvm_x86_pmu_get_msr)(vcpu, msr_info);
601 	}
602 
603 	return 0;
604 }
605 
606 int kvm_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
607 {
608 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
609 	u32 msr = msr_info->index;
610 	u64 data = msr_info->data;
611 	u64 diff;
612 
613 	/*
614 	 * Note, AMD ignores writes to reserved bits and read-only PMU MSRs,
615 	 * whereas Intel generates #GP on attempts to write reserved/RO MSRs.
616 	 */
617 	switch (msr) {
618 	case MSR_CORE_PERF_GLOBAL_STATUS:
619 		if (!msr_info->host_initiated)
620 			return 1; /* RO MSR */
621 		fallthrough;
622 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS:
623 		/* Per PPR, Read-only MSR. Writes are ignored. */
624 		if (!msr_info->host_initiated)
625 			break;
626 
627 		if (data & pmu->global_status_mask)
628 			return 1;
629 
630 		pmu->global_status = data;
631 		break;
632 	case MSR_AMD64_PERF_CNTR_GLOBAL_CTL:
633 		data &= ~pmu->global_ctrl_mask;
634 		fallthrough;
635 	case MSR_CORE_PERF_GLOBAL_CTRL:
636 		if (!kvm_valid_perf_global_ctrl(pmu, data))
637 			return 1;
638 
639 		if (pmu->global_ctrl != data) {
640 			diff = pmu->global_ctrl ^ data;
641 			pmu->global_ctrl = data;
642 			reprogram_counters(pmu, diff);
643 		}
644 		break;
645 	case MSR_CORE_PERF_GLOBAL_OVF_CTRL:
646 		/*
647 		 * GLOBAL_OVF_CTRL, a.k.a. GLOBAL STATUS_RESET, clears bits in
648 		 * GLOBAL_STATUS, and so the set of reserved bits is the same.
649 		 */
650 		if (data & pmu->global_status_mask)
651 			return 1;
652 		fallthrough;
653 	case MSR_AMD64_PERF_CNTR_GLOBAL_STATUS_CLR:
654 		if (!msr_info->host_initiated)
655 			pmu->global_status &= ~data;
656 		break;
657 	default:
658 		kvm_pmu_mark_pmc_in_use(vcpu, msr_info->index);
659 		return static_call(kvm_x86_pmu_set_msr)(vcpu, msr_info);
660 	}
661 
662 	return 0;
663 }
664 
665 /* refresh PMU settings. This function generally is called when underlying
666  * settings are changed (such as changes of PMU CPUID by guest VMs), which
667  * should rarely happen.
668  */
669 void kvm_pmu_refresh(struct kvm_vcpu *vcpu)
670 {
671 	if (KVM_BUG_ON(kvm_vcpu_has_run(vcpu), vcpu->kvm))
672 		return;
673 
674 	bitmap_zero(vcpu_to_pmu(vcpu)->all_valid_pmc_idx, X86_PMC_IDX_MAX);
675 	static_call(kvm_x86_pmu_refresh)(vcpu);
676 }
677 
678 void kvm_pmu_reset(struct kvm_vcpu *vcpu)
679 {
680 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
681 
682 	irq_work_sync(&pmu->irq_work);
683 	static_call(kvm_x86_pmu_reset)(vcpu);
684 }
685 
686 void kvm_pmu_init(struct kvm_vcpu *vcpu)
687 {
688 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
689 
690 	memset(pmu, 0, sizeof(*pmu));
691 	static_call(kvm_x86_pmu_init)(vcpu);
692 	init_irq_work(&pmu->irq_work, kvm_pmi_trigger_fn);
693 	pmu->event_count = 0;
694 	pmu->need_cleanup = false;
695 	kvm_pmu_refresh(vcpu);
696 }
697 
698 /* Release perf_events for vPMCs that have been unused for a full time slice.  */
699 void kvm_pmu_cleanup(struct kvm_vcpu *vcpu)
700 {
701 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
702 	struct kvm_pmc *pmc = NULL;
703 	DECLARE_BITMAP(bitmask, X86_PMC_IDX_MAX);
704 	int i;
705 
706 	pmu->need_cleanup = false;
707 
708 	bitmap_andnot(bitmask, pmu->all_valid_pmc_idx,
709 		      pmu->pmc_in_use, X86_PMC_IDX_MAX);
710 
711 	for_each_set_bit(i, bitmask, X86_PMC_IDX_MAX) {
712 		pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, i);
713 
714 		if (pmc && pmc->perf_event && !pmc_speculative_in_use(pmc))
715 			pmc_stop_counter(pmc);
716 	}
717 
718 	static_call_cond(kvm_x86_pmu_cleanup)(vcpu);
719 
720 	bitmap_zero(pmu->pmc_in_use, X86_PMC_IDX_MAX);
721 }
722 
723 void kvm_pmu_destroy(struct kvm_vcpu *vcpu)
724 {
725 	kvm_pmu_reset(vcpu);
726 }
727 
728 static void kvm_pmu_incr_counter(struct kvm_pmc *pmc)
729 {
730 	pmc->prev_counter = pmc->counter;
731 	pmc->counter = (pmc->counter + 1) & pmc_bitmask(pmc);
732 	kvm_pmu_request_counter_reprogram(pmc);
733 }
734 
735 static inline bool eventsel_match_perf_hw_id(struct kvm_pmc *pmc,
736 	unsigned int perf_hw_id)
737 {
738 	return !((pmc->eventsel ^ perf_get_hw_event_config(perf_hw_id)) &
739 		AMD64_RAW_EVENT_MASK_NB);
740 }
741 
742 static inline bool cpl_is_matched(struct kvm_pmc *pmc)
743 {
744 	bool select_os, select_user;
745 	u64 config;
746 
747 	if (pmc_is_gp(pmc)) {
748 		config = pmc->eventsel;
749 		select_os = config & ARCH_PERFMON_EVENTSEL_OS;
750 		select_user = config & ARCH_PERFMON_EVENTSEL_USR;
751 	} else {
752 		config = fixed_ctrl_field(pmc_to_pmu(pmc)->fixed_ctr_ctrl,
753 					  pmc->idx - INTEL_PMC_IDX_FIXED);
754 		select_os = config & 0x1;
755 		select_user = config & 0x2;
756 	}
757 
758 	return (static_call(kvm_x86_get_cpl)(pmc->vcpu) == 0) ? select_os : select_user;
759 }
760 
761 void kvm_pmu_trigger_event(struct kvm_vcpu *vcpu, u64 perf_hw_id)
762 {
763 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
764 	struct kvm_pmc *pmc;
765 	int i;
766 
767 	for_each_set_bit(i, pmu->all_valid_pmc_idx, X86_PMC_IDX_MAX) {
768 		pmc = static_call(kvm_x86_pmu_pmc_idx_to_pmc)(pmu, i);
769 
770 		if (!pmc || !pmc_event_is_allowed(pmc))
771 			continue;
772 
773 		/* Ignore checks for edge detect, pin control, invert and CMASK bits */
774 		if (eventsel_match_perf_hw_id(pmc, perf_hw_id) && cpl_is_matched(pmc))
775 			kvm_pmu_incr_counter(pmc);
776 	}
777 }
778 EXPORT_SYMBOL_GPL(kvm_pmu_trigger_event);
779 
780 static bool is_masked_filter_valid(const struct kvm_x86_pmu_event_filter *filter)
781 {
782 	u64 mask = kvm_pmu_ops.EVENTSEL_EVENT |
783 		   KVM_PMU_MASKED_ENTRY_UMASK_MASK |
784 		   KVM_PMU_MASKED_ENTRY_UMASK_MATCH |
785 		   KVM_PMU_MASKED_ENTRY_EXCLUDE;
786 	int i;
787 
788 	for (i = 0; i < filter->nevents; i++) {
789 		if (filter->events[i] & ~mask)
790 			return false;
791 	}
792 
793 	return true;
794 }
795 
796 static void convert_to_masked_filter(struct kvm_x86_pmu_event_filter *filter)
797 {
798 	int i, j;
799 
800 	for (i = 0, j = 0; i < filter->nevents; i++) {
801 		/*
802 		 * Skip events that are impossible to match against a guest
803 		 * event.  When filtering, only the event select + unit mask
804 		 * of the guest event is used.  To maintain backwards
805 		 * compatibility, impossible filters can't be rejected :-(
806 		 */
807 		if (filter->events[i] & ~(kvm_pmu_ops.EVENTSEL_EVENT |
808 					  ARCH_PERFMON_EVENTSEL_UMASK))
809 			continue;
810 		/*
811 		 * Convert userspace events to a common in-kernel event so
812 		 * only one code path is needed to support both events.  For
813 		 * the in-kernel events use masked events because they are
814 		 * flexible enough to handle both cases.  To convert to masked
815 		 * events all that's needed is to add an "all ones" umask_mask,
816 		 * (unmasked filter events don't support EXCLUDE).
817 		 */
818 		filter->events[j++] = filter->events[i] |
819 				      (0xFFULL << KVM_PMU_MASKED_ENTRY_UMASK_MASK_SHIFT);
820 	}
821 
822 	filter->nevents = j;
823 }
824 
825 static int prepare_filter_lists(struct kvm_x86_pmu_event_filter *filter)
826 {
827 	int i;
828 
829 	if (!(filter->flags & KVM_PMU_EVENT_FLAG_MASKED_EVENTS))
830 		convert_to_masked_filter(filter);
831 	else if (!is_masked_filter_valid(filter))
832 		return -EINVAL;
833 
834 	/*
835 	 * Sort entries by event select and includes vs. excludes so that all
836 	 * entries for a given event select can be processed efficiently during
837 	 * filtering.  The EXCLUDE flag uses a more significant bit than the
838 	 * event select, and so the sorted list is also effectively split into
839 	 * includes and excludes sub-lists.
840 	 */
841 	sort(&filter->events, filter->nevents, sizeof(filter->events[0]),
842 	     filter_sort_cmp, NULL);
843 
844 	i = filter->nevents;
845 	/* Find the first EXCLUDE event (only supported for masked events). */
846 	if (filter->flags & KVM_PMU_EVENT_FLAG_MASKED_EVENTS) {
847 		for (i = 0; i < filter->nevents; i++) {
848 			if (filter->events[i] & KVM_PMU_MASKED_ENTRY_EXCLUDE)
849 				break;
850 		}
851 	}
852 
853 	filter->nr_includes = i;
854 	filter->nr_excludes = filter->nevents - filter->nr_includes;
855 	filter->includes = filter->events;
856 	filter->excludes = filter->events + filter->nr_includes;
857 
858 	return 0;
859 }
860 
861 int kvm_vm_ioctl_set_pmu_event_filter(struct kvm *kvm, void __user *argp)
862 {
863 	struct kvm_pmu_event_filter __user *user_filter = argp;
864 	struct kvm_x86_pmu_event_filter *filter;
865 	struct kvm_pmu_event_filter tmp;
866 	struct kvm_vcpu *vcpu;
867 	unsigned long i;
868 	size_t size;
869 	int r;
870 
871 	if (copy_from_user(&tmp, user_filter, sizeof(tmp)))
872 		return -EFAULT;
873 
874 	if (tmp.action != KVM_PMU_EVENT_ALLOW &&
875 	    tmp.action != KVM_PMU_EVENT_DENY)
876 		return -EINVAL;
877 
878 	if (tmp.flags & ~KVM_PMU_EVENT_FLAGS_VALID_MASK)
879 		return -EINVAL;
880 
881 	if (tmp.nevents > KVM_PMU_EVENT_FILTER_MAX_EVENTS)
882 		return -E2BIG;
883 
884 	size = struct_size(filter, events, tmp.nevents);
885 	filter = kzalloc(size, GFP_KERNEL_ACCOUNT);
886 	if (!filter)
887 		return -ENOMEM;
888 
889 	filter->action = tmp.action;
890 	filter->nevents = tmp.nevents;
891 	filter->fixed_counter_bitmap = tmp.fixed_counter_bitmap;
892 	filter->flags = tmp.flags;
893 
894 	r = -EFAULT;
895 	if (copy_from_user(filter->events, user_filter->events,
896 			   sizeof(filter->events[0]) * filter->nevents))
897 		goto cleanup;
898 
899 	r = prepare_filter_lists(filter);
900 	if (r)
901 		goto cleanup;
902 
903 	mutex_lock(&kvm->lock);
904 	filter = rcu_replace_pointer(kvm->arch.pmu_event_filter, filter,
905 				     mutex_is_locked(&kvm->lock));
906 	mutex_unlock(&kvm->lock);
907 	synchronize_srcu_expedited(&kvm->srcu);
908 
909 	BUILD_BUG_ON(sizeof(((struct kvm_pmu *)0)->reprogram_pmi) >
910 		     sizeof(((struct kvm_pmu *)0)->__reprogram_pmi));
911 
912 	kvm_for_each_vcpu(i, vcpu, kvm)
913 		atomic64_set(&vcpu_to_pmu(vcpu)->__reprogram_pmi, -1ull);
914 
915 	kvm_make_all_cpus_request(kvm, KVM_REQ_PMU);
916 
917 	r = 0;
918 cleanup:
919 	kfree(filter);
920 	return r;
921 }
922