xref: /linux/arch/x86/kvm/vmx/pmu_intel.c (revision f694f30e81c4ade358eb8c75273bac1a48f0cb8f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * KVM PMU support for Intel CPUs
4  *
5  * Copyright 2011 Red Hat, Inc. and/or its affiliates.
6  *
7  * Authors:
8  *   Avi Kivity   <avi@redhat.com>
9  *   Gleb Natapov <gleb@redhat.com>
10  */
11 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
12 
13 #include <linux/types.h>
14 #include <linux/kvm_host.h>
15 #include <linux/perf_event.h>
16 #include <asm/perf_event.h>
17 #include "x86.h"
18 #include "cpuid.h"
19 #include "lapic.h"
20 #include "nested.h"
21 #include "pmu.h"
22 #include "tdx.h"
23 
24 /*
25  * Perf's "BASE" is wildly misleading, architectural PMUs use bits 31:16 of ECX
26  * to encode the "type" of counter to read, i.e. this is not a "base".  And to
27  * further confuse things, non-architectural PMUs use bit 31 as a flag for
28  * "fast" reads, whereas the "type" is an explicit value.
29  */
30 #define INTEL_RDPMC_GP		0
31 #define INTEL_RDPMC_FIXED	INTEL_PMC_FIXED_RDPMC_BASE
32 
33 #define INTEL_RDPMC_TYPE_MASK	GENMASK(31, 16)
34 #define INTEL_RDPMC_INDEX_MASK	GENMASK(15, 0)
35 
36 #define MSR_PMC_FULL_WIDTH_BIT      (MSR_IA32_PMC0 - MSR_IA32_PERFCTR0)
37 
38 static struct lbr_desc *vcpu_to_lbr_desc(struct kvm_vcpu *vcpu)
39 {
40 	if (is_td_vcpu(vcpu))
41 		return NULL;
42 
43 	return &to_vmx(vcpu)->lbr_desc;
44 }
45 
46 static struct x86_pmu_lbr *vcpu_to_lbr_records(struct kvm_vcpu *vcpu)
47 {
48 	if (is_td_vcpu(vcpu))
49 		return NULL;
50 
51 	return &to_vmx(vcpu)->lbr_desc.records;
52 }
53 
54 #pragma GCC poison to_vmx
55 
56 static void reprogram_fixed_counters(struct kvm_pmu *pmu, u64 data)
57 {
58 	struct kvm_pmc *pmc;
59 	u64 old_fixed_ctr_ctrl = pmu->fixed_ctr_ctrl;
60 	int i;
61 
62 	pmu->fixed_ctr_ctrl = data;
63 	for (i = 0; i < pmu->nr_arch_fixed_counters; i++) {
64 		u8 new_ctrl = fixed_ctrl_field(data, i);
65 		u8 old_ctrl = fixed_ctrl_field(old_fixed_ctr_ctrl, i);
66 
67 		if (old_ctrl == new_ctrl)
68 			continue;
69 
70 		pmc = get_fixed_pmc(pmu, MSR_CORE_PERF_FIXED_CTR0 + i);
71 
72 		__set_bit(KVM_FIXED_PMC_BASE_IDX + i, pmu->pmc_in_use);
73 		kvm_pmu_request_counter_reprogram(pmc);
74 	}
75 }
76 
77 static struct kvm_pmc *intel_rdpmc_ecx_to_pmc(struct kvm_vcpu *vcpu,
78 					    unsigned int idx, u64 *mask)
79 {
80 	unsigned int type = idx & INTEL_RDPMC_TYPE_MASK;
81 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
82 	struct kvm_pmc *counters;
83 	unsigned int num_counters;
84 	u64 bitmask;
85 
86 	/*
87 	 * The encoding of ECX for RDPMC is different for architectural versus
88 	 * non-architecturals PMUs (PMUs with version '0').  For architectural
89 	 * PMUs, bits 31:16 specify the PMC type and bits 15:0 specify the PMC
90 	 * index.  For non-architectural PMUs, bit 31 is a "fast" flag, and
91 	 * bits 30:0 specify the PMC index.
92 	 *
93 	 * Yell and reject attempts to read PMCs for a non-architectural PMU,
94 	 * as KVM doesn't support such PMUs.
95 	 */
96 	if (WARN_ON_ONCE(!pmu->version))
97 		return NULL;
98 
99 	/*
100 	 * General Purpose (GP) PMCs are supported on all PMUs, and fixed PMCs
101 	 * are supported on all architectural PMUs, i.e. on all virtual PMUs
102 	 * supported by KVM.  Note, KVM only emulates fixed PMCs for PMU v2+,
103 	 * but the type itself is still valid, i.e. let RDPMC fail due to
104 	 * accessing a non-existent counter.  Reject attempts to read all other
105 	 * types, which are unknown/unsupported.
106 	 */
107 	switch (type) {
108 	case INTEL_RDPMC_FIXED:
109 		counters = pmu->fixed_counters;
110 		num_counters = pmu->nr_arch_fixed_counters;
111 		bitmask = pmu->counter_bitmask[KVM_PMC_FIXED];
112 		break;
113 	case INTEL_RDPMC_GP:
114 		counters = pmu->gp_counters;
115 		num_counters = pmu->nr_arch_gp_counters;
116 		bitmask = pmu->counter_bitmask[KVM_PMC_GP];
117 		break;
118 	default:
119 		return NULL;
120 	}
121 
122 	idx &= INTEL_RDPMC_INDEX_MASK;
123 	if (idx >= num_counters)
124 		return NULL;
125 
126 	*mask &= bitmask;
127 	return &counters[array_index_nospec(idx, num_counters)];
128 }
129 
130 static inline u64 vcpu_get_perf_capabilities(struct kvm_vcpu *vcpu)
131 {
132 	if (!guest_cpu_cap_has(vcpu, X86_FEATURE_PDCM))
133 		return 0;
134 
135 	return vcpu->arch.perf_capabilities;
136 }
137 
138 static inline bool fw_writes_is_enabled(struct kvm_vcpu *vcpu)
139 {
140 	return (vcpu_get_perf_capabilities(vcpu) & PMU_CAP_FW_WRITES) != 0;
141 }
142 
143 static inline struct kvm_pmc *get_fw_gp_pmc(struct kvm_pmu *pmu, u32 msr)
144 {
145 	if (!fw_writes_is_enabled(pmu_to_vcpu(pmu)))
146 		return NULL;
147 
148 	return get_gp_pmc(pmu, msr, MSR_IA32_PMC0);
149 }
150 
151 static bool intel_pmu_lbr_is_compatible(struct kvm_vcpu *vcpu)
152 {
153 	if (is_td_vcpu(vcpu))
154 		return false;
155 
156 	return cpuid_model_is_consistent(vcpu);
157 }
158 
159 bool intel_pmu_lbr_is_enabled(struct kvm_vcpu *vcpu)
160 {
161 	if (is_td_vcpu(vcpu))
162 		return false;
163 
164 	return !!vcpu_to_lbr_records(vcpu)->nr;
165 }
166 
167 static bool intel_pmu_is_valid_lbr_msr(struct kvm_vcpu *vcpu, u32 index)
168 {
169 	struct x86_pmu_lbr *records = vcpu_to_lbr_records(vcpu);
170 	bool ret = false;
171 
172 	if (!intel_pmu_lbr_is_enabled(vcpu))
173 		return ret;
174 
175 	ret = (index == MSR_LBR_SELECT) || (index == MSR_LBR_TOS) ||
176 		(index >= records->from && index < records->from + records->nr) ||
177 		(index >= records->to && index < records->to + records->nr);
178 
179 	if (!ret && records->info)
180 		ret = (index >= records->info && index < records->info + records->nr);
181 
182 	return ret;
183 }
184 
185 static bool intel_is_valid_msr(struct kvm_vcpu *vcpu, u32 msr)
186 {
187 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
188 	u64 perf_capabilities;
189 	int ret;
190 
191 	switch (msr) {
192 	case MSR_CORE_PERF_FIXED_CTR_CTRL:
193 		return kvm_pmu_has_perf_global_ctrl(pmu);
194 	case MSR_IA32_PEBS_ENABLE:
195 		ret = vcpu_get_perf_capabilities(vcpu) & PERF_CAP_PEBS_FORMAT;
196 		break;
197 	case MSR_IA32_DS_AREA:
198 		ret = guest_cpu_cap_has(vcpu, X86_FEATURE_DS);
199 		break;
200 	case MSR_PEBS_DATA_CFG:
201 		perf_capabilities = vcpu_get_perf_capabilities(vcpu);
202 		ret = (perf_capabilities & PERF_CAP_PEBS_BASELINE) &&
203 			((perf_capabilities & PERF_CAP_PEBS_FORMAT) > 3);
204 		break;
205 	default:
206 		ret = get_gp_pmc(pmu, msr, MSR_IA32_PERFCTR0) ||
207 			get_gp_pmc(pmu, msr, MSR_P6_EVNTSEL0) ||
208 			get_fixed_pmc(pmu, msr) || get_fw_gp_pmc(pmu, msr) ||
209 			intel_pmu_is_valid_lbr_msr(vcpu, msr);
210 		break;
211 	}
212 
213 	return ret;
214 }
215 
216 static struct kvm_pmc *intel_msr_idx_to_pmc(struct kvm_vcpu *vcpu, u32 msr)
217 {
218 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
219 	struct kvm_pmc *pmc;
220 
221 	pmc = get_fixed_pmc(pmu, msr);
222 	pmc = pmc ? pmc : get_gp_pmc(pmu, msr, MSR_P6_EVNTSEL0);
223 	pmc = pmc ? pmc : get_gp_pmc(pmu, msr, MSR_IA32_PERFCTR0);
224 
225 	return pmc;
226 }
227 
228 static inline void intel_pmu_release_guest_lbr_event(struct kvm_vcpu *vcpu)
229 {
230 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
231 
232 	if (!lbr_desc)
233 		return;
234 
235 	if (lbr_desc->event) {
236 		perf_event_release_kernel(lbr_desc->event);
237 		lbr_desc->event = NULL;
238 		vcpu_to_pmu(vcpu)->event_count--;
239 	}
240 }
241 
242 int intel_pmu_create_guest_lbr_event(struct kvm_vcpu *vcpu)
243 {
244 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
245 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
246 	struct perf_event *event;
247 
248 	/*
249 	 * The perf_event_attr is constructed in the minimum efficient way:
250 	 * - set 'pinned = true' to make it task pinned so that if another
251 	 *   cpu pinned event reclaims LBR, the event->oncpu will be set to -1;
252 	 * - set '.exclude_host = true' to record guest branches behavior;
253 	 *
254 	 * - set '.config = INTEL_FIXED_VLBR_EVENT' to indicates host perf
255 	 *   schedule the event without a real HW counter but a fake one;
256 	 *   check is_guest_lbr_event() and __intel_get_event_constraints();
257 	 *
258 	 * - set 'sample_type = PERF_SAMPLE_BRANCH_STACK' and
259 	 *   'branch_sample_type = PERF_SAMPLE_BRANCH_CALL_STACK |
260 	 *   PERF_SAMPLE_BRANCH_USER' to configure it as a LBR callstack
261 	 *   event, which helps KVM to save/restore guest LBR records
262 	 *   during host context switches and reduces quite a lot overhead,
263 	 *   check branch_user_callstack() and intel_pmu_lbr_sched_task();
264 	 */
265 	struct perf_event_attr attr = {
266 		.type = PERF_TYPE_RAW,
267 		.size = sizeof(attr),
268 		.config = INTEL_FIXED_VLBR_EVENT,
269 		.sample_type = PERF_SAMPLE_BRANCH_STACK,
270 		.pinned = true,
271 		.exclude_host = true,
272 		.branch_sample_type = PERF_SAMPLE_BRANCH_CALL_STACK |
273 					PERF_SAMPLE_BRANCH_USER,
274 	};
275 
276 	if (WARN_ON_ONCE(!lbr_desc))
277 		return 0;
278 
279 	if (unlikely(lbr_desc->event)) {
280 		__set_bit(INTEL_PMC_IDX_FIXED_VLBR, pmu->pmc_in_use);
281 		return 0;
282 	}
283 
284 	event = perf_event_create_kernel_counter(&attr, -1,
285 						current, NULL, NULL);
286 	if (IS_ERR(event)) {
287 		pr_debug_ratelimited("%s: failed %ld\n",
288 					__func__, PTR_ERR(event));
289 		return PTR_ERR(event);
290 	}
291 	lbr_desc->event = event;
292 	pmu->event_count++;
293 	__set_bit(INTEL_PMC_IDX_FIXED_VLBR, pmu->pmc_in_use);
294 	return 0;
295 }
296 
297 /*
298  * It's safe to access LBR msrs from guest when they have not
299  * been passthrough since the host would help restore or reset
300  * the LBR msrs records when the guest LBR event is scheduled in.
301  */
302 static bool intel_pmu_handle_lbr_msrs_access(struct kvm_vcpu *vcpu,
303 				     struct msr_data *msr_info, bool read)
304 {
305 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
306 	u32 index = msr_info->index;
307 
308 	if (!intel_pmu_is_valid_lbr_msr(vcpu, index))
309 		return false;
310 
311 	if (!lbr_desc->event && intel_pmu_create_guest_lbr_event(vcpu) < 0)
312 		goto dummy;
313 
314 	/*
315 	 * Disable irq to ensure the LBR feature doesn't get reclaimed by the
316 	 * host at the time the value is read from the msr, and this avoids the
317 	 * host LBR value to be leaked to the guest. If LBR has been reclaimed,
318 	 * return 0 on guest reads.
319 	 */
320 	local_irq_disable();
321 	if (lbr_desc->event->state == PERF_EVENT_STATE_ACTIVE) {
322 		if (read)
323 			rdmsrl(index, msr_info->data);
324 		else
325 			wrmsrl(index, msr_info->data);
326 		__set_bit(INTEL_PMC_IDX_FIXED_VLBR, vcpu_to_pmu(vcpu)->pmc_in_use);
327 		local_irq_enable();
328 		return true;
329 	}
330 	clear_bit(INTEL_PMC_IDX_FIXED_VLBR, vcpu_to_pmu(vcpu)->pmc_in_use);
331 	local_irq_enable();
332 
333 dummy:
334 	if (read)
335 		msr_info->data = 0;
336 	return true;
337 }
338 
339 static int intel_pmu_get_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
340 {
341 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
342 	struct kvm_pmc *pmc;
343 	u32 msr = msr_info->index;
344 
345 	switch (msr) {
346 	case MSR_CORE_PERF_FIXED_CTR_CTRL:
347 		msr_info->data = pmu->fixed_ctr_ctrl;
348 		break;
349 	case MSR_IA32_PEBS_ENABLE:
350 		msr_info->data = pmu->pebs_enable;
351 		break;
352 	case MSR_IA32_DS_AREA:
353 		msr_info->data = pmu->ds_area;
354 		break;
355 	case MSR_PEBS_DATA_CFG:
356 		msr_info->data = pmu->pebs_data_cfg;
357 		break;
358 	default:
359 		if ((pmc = get_gp_pmc(pmu, msr, MSR_IA32_PERFCTR0)) ||
360 		    (pmc = get_gp_pmc(pmu, msr, MSR_IA32_PMC0))) {
361 			u64 val = pmc_read_counter(pmc);
362 			msr_info->data =
363 				val & pmu->counter_bitmask[KVM_PMC_GP];
364 			break;
365 		} else if ((pmc = get_fixed_pmc(pmu, msr))) {
366 			u64 val = pmc_read_counter(pmc);
367 			msr_info->data =
368 				val & pmu->counter_bitmask[KVM_PMC_FIXED];
369 			break;
370 		} else if ((pmc = get_gp_pmc(pmu, msr, MSR_P6_EVNTSEL0))) {
371 			msr_info->data = pmc->eventsel;
372 			break;
373 		} else if (intel_pmu_handle_lbr_msrs_access(vcpu, msr_info, true)) {
374 			break;
375 		}
376 		return 1;
377 	}
378 
379 	return 0;
380 }
381 
382 static int intel_pmu_set_msr(struct kvm_vcpu *vcpu, struct msr_data *msr_info)
383 {
384 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
385 	struct kvm_pmc *pmc;
386 	u32 msr = msr_info->index;
387 	u64 data = msr_info->data;
388 	u64 reserved_bits, diff;
389 
390 	switch (msr) {
391 	case MSR_CORE_PERF_FIXED_CTR_CTRL:
392 		if (data & pmu->fixed_ctr_ctrl_rsvd)
393 			return 1;
394 
395 		if (pmu->fixed_ctr_ctrl != data)
396 			reprogram_fixed_counters(pmu, data);
397 		break;
398 	case MSR_IA32_PEBS_ENABLE:
399 		if (data & pmu->pebs_enable_rsvd)
400 			return 1;
401 
402 		if (pmu->pebs_enable != data) {
403 			diff = pmu->pebs_enable ^ data;
404 			pmu->pebs_enable = data;
405 			reprogram_counters(pmu, diff);
406 		}
407 		break;
408 	case MSR_IA32_DS_AREA:
409 		if (is_noncanonical_msr_address(data, vcpu))
410 			return 1;
411 
412 		pmu->ds_area = data;
413 		break;
414 	case MSR_PEBS_DATA_CFG:
415 		if (data & pmu->pebs_data_cfg_rsvd)
416 			return 1;
417 
418 		pmu->pebs_data_cfg = data;
419 		break;
420 	default:
421 		if ((pmc = get_gp_pmc(pmu, msr, MSR_IA32_PERFCTR0)) ||
422 		    (pmc = get_gp_pmc(pmu, msr, MSR_IA32_PMC0))) {
423 			if ((msr & MSR_PMC_FULL_WIDTH_BIT) &&
424 			    (data & ~pmu->counter_bitmask[KVM_PMC_GP]))
425 				return 1;
426 
427 			if (!msr_info->host_initiated &&
428 			    !(msr & MSR_PMC_FULL_WIDTH_BIT))
429 				data = (s64)(s32)data;
430 			pmc_write_counter(pmc, data);
431 			break;
432 		} else if ((pmc = get_fixed_pmc(pmu, msr))) {
433 			pmc_write_counter(pmc, data);
434 			break;
435 		} else if ((pmc = get_gp_pmc(pmu, msr, MSR_P6_EVNTSEL0))) {
436 			reserved_bits = pmu->reserved_bits;
437 			if ((pmc->idx == 2) &&
438 			    (pmu->raw_event_mask & HSW_IN_TX_CHECKPOINTED))
439 				reserved_bits ^= HSW_IN_TX_CHECKPOINTED;
440 			if (data & reserved_bits)
441 				return 1;
442 
443 			if (data != pmc->eventsel) {
444 				pmc->eventsel = data;
445 				kvm_pmu_request_counter_reprogram(pmc);
446 			}
447 			break;
448 		} else if (intel_pmu_handle_lbr_msrs_access(vcpu, msr_info, false)) {
449 			break;
450 		}
451 		/* Not a known PMU MSR. */
452 		return 1;
453 	}
454 
455 	return 0;
456 }
457 
458 /*
459  * Map fixed counter events to architectural general purpose event encodings.
460  * Perf doesn't provide APIs to allow KVM to directly program a fixed counter,
461  * and so KVM instead programs the architectural event to effectively request
462  * the fixed counter.  Perf isn't guaranteed to use a fixed counter and may
463  * instead program the encoding into a general purpose counter, e.g. if a
464  * different perf_event is already utilizing the requested counter, but the end
465  * result is the same (ignoring the fact that using a general purpose counter
466  * will likely exacerbate counter contention).
467  *
468  * Forcibly inlined to allow asserting on @index at build time, and there should
469  * never be more than one user.
470  */
471 static __always_inline u64 intel_get_fixed_pmc_eventsel(unsigned int index)
472 {
473 	const enum perf_hw_id fixed_pmc_perf_ids[] = {
474 		[0] = PERF_COUNT_HW_INSTRUCTIONS,
475 		[1] = PERF_COUNT_HW_CPU_CYCLES,
476 		[2] = PERF_COUNT_HW_REF_CPU_CYCLES,
477 	};
478 	u64 eventsel;
479 
480 	BUILD_BUG_ON(ARRAY_SIZE(fixed_pmc_perf_ids) != KVM_MAX_NR_INTEL_FIXED_COUTNERS);
481 	BUILD_BUG_ON(index >= KVM_MAX_NR_INTEL_FIXED_COUTNERS);
482 
483 	/*
484 	 * Yell if perf reports support for a fixed counter but perf doesn't
485 	 * have a known encoding for the associated general purpose event.
486 	 */
487 	eventsel = perf_get_hw_event_config(fixed_pmc_perf_ids[index]);
488 	WARN_ON_ONCE(!eventsel && index < kvm_pmu_cap.num_counters_fixed);
489 	return eventsel;
490 }
491 
492 static void intel_pmu_enable_fixed_counter_bits(struct kvm_pmu *pmu, u64 bits)
493 {
494 	int i;
495 
496 	for (i = 0; i < pmu->nr_arch_fixed_counters; i++)
497 		pmu->fixed_ctr_ctrl_rsvd &= ~intel_fixed_bits_by_idx(i, bits);
498 }
499 
500 static void intel_pmu_refresh(struct kvm_vcpu *vcpu)
501 {
502 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
503 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
504 	struct kvm_cpuid_entry2 *entry;
505 	union cpuid10_eax eax;
506 	union cpuid10_edx edx;
507 	u64 perf_capabilities;
508 	u64 counter_rsvd;
509 
510 	if (!lbr_desc)
511 		return;
512 
513 	memset(&lbr_desc->records, 0, sizeof(lbr_desc->records));
514 
515 	/*
516 	 * Setting passthrough of LBR MSRs is done only in the VM-Entry loop,
517 	 * and PMU refresh is disallowed after the vCPU has run, i.e. this code
518 	 * should never be reached while KVM is passing through MSRs.
519 	 */
520 	if (KVM_BUG_ON(lbr_desc->msr_passthrough, vcpu->kvm))
521 		return;
522 
523 	entry = kvm_find_cpuid_entry(vcpu, 0xa);
524 	if (!entry)
525 		return;
526 
527 	eax.full = entry->eax;
528 	edx.full = entry->edx;
529 
530 	pmu->version = eax.split.version_id;
531 	if (!pmu->version)
532 		return;
533 
534 	pmu->nr_arch_gp_counters = min_t(int, eax.split.num_counters,
535 					 kvm_pmu_cap.num_counters_gp);
536 	eax.split.bit_width = min_t(int, eax.split.bit_width,
537 				    kvm_pmu_cap.bit_width_gp);
538 	pmu->counter_bitmask[KVM_PMC_GP] = ((u64)1 << eax.split.bit_width) - 1;
539 	eax.split.mask_length = min_t(int, eax.split.mask_length,
540 				      kvm_pmu_cap.events_mask_len);
541 	pmu->available_event_types = ~entry->ebx &
542 					((1ull << eax.split.mask_length) - 1);
543 
544 	if (pmu->version == 1) {
545 		pmu->nr_arch_fixed_counters = 0;
546 	} else {
547 		pmu->nr_arch_fixed_counters = min_t(int, edx.split.num_counters_fixed,
548 						    kvm_pmu_cap.num_counters_fixed);
549 		edx.split.bit_width_fixed = min_t(int, edx.split.bit_width_fixed,
550 						  kvm_pmu_cap.bit_width_fixed);
551 		pmu->counter_bitmask[KVM_PMC_FIXED] =
552 			((u64)1 << edx.split.bit_width_fixed) - 1;
553 	}
554 
555 	intel_pmu_enable_fixed_counter_bits(pmu, INTEL_FIXED_0_KERNEL |
556 						 INTEL_FIXED_0_USER |
557 						 INTEL_FIXED_0_ENABLE_PMI);
558 
559 	counter_rsvd = ~(((1ull << pmu->nr_arch_gp_counters) - 1) |
560 		(((1ull << pmu->nr_arch_fixed_counters) - 1) << KVM_FIXED_PMC_BASE_IDX));
561 	pmu->global_ctrl_rsvd = counter_rsvd;
562 
563 	/*
564 	 * GLOBAL_STATUS and GLOBAL_OVF_CONTROL (a.k.a. GLOBAL_STATUS_RESET)
565 	 * share reserved bit definitions.  The kernel just happens to use
566 	 * OVF_CTRL for the names.
567 	 */
568 	pmu->global_status_rsvd = pmu->global_ctrl_rsvd
569 			& ~(MSR_CORE_PERF_GLOBAL_OVF_CTRL_OVF_BUF |
570 			    MSR_CORE_PERF_GLOBAL_OVF_CTRL_COND_CHGD);
571 	if (vmx_pt_mode_is_host_guest())
572 		pmu->global_status_rsvd &=
573 				~MSR_CORE_PERF_GLOBAL_OVF_CTRL_TRACE_TOPA_PMI;
574 
575 	entry = kvm_find_cpuid_entry_index(vcpu, 7, 0);
576 	if (entry &&
577 	    (boot_cpu_has(X86_FEATURE_HLE) || boot_cpu_has(X86_FEATURE_RTM)) &&
578 	    (entry->ebx & (X86_FEATURE_HLE|X86_FEATURE_RTM))) {
579 		pmu->reserved_bits ^= HSW_IN_TX;
580 		pmu->raw_event_mask |= (HSW_IN_TX|HSW_IN_TX_CHECKPOINTED);
581 	}
582 
583 	bitmap_set(pmu->all_valid_pmc_idx,
584 		0, pmu->nr_arch_gp_counters);
585 	bitmap_set(pmu->all_valid_pmc_idx,
586 		INTEL_PMC_MAX_GENERIC, pmu->nr_arch_fixed_counters);
587 
588 	perf_capabilities = vcpu_get_perf_capabilities(vcpu);
589 	if (intel_pmu_lbr_is_compatible(vcpu) &&
590 	    (perf_capabilities & PMU_CAP_LBR_FMT))
591 		memcpy(&lbr_desc->records, &vmx_lbr_caps, sizeof(vmx_lbr_caps));
592 	else
593 		lbr_desc->records.nr = 0;
594 
595 	if (lbr_desc->records.nr)
596 		bitmap_set(pmu->all_valid_pmc_idx, INTEL_PMC_IDX_FIXED_VLBR, 1);
597 
598 	if (perf_capabilities & PERF_CAP_PEBS_FORMAT) {
599 		if (perf_capabilities & PERF_CAP_PEBS_BASELINE) {
600 			pmu->pebs_enable_rsvd = counter_rsvd;
601 			pmu->reserved_bits &= ~ICL_EVENTSEL_ADAPTIVE;
602 			pmu->pebs_data_cfg_rsvd = ~0xff00000full;
603 			intel_pmu_enable_fixed_counter_bits(pmu, ICL_FIXED_0_ADAPTIVE);
604 		} else {
605 			pmu->pebs_enable_rsvd =
606 				~((1ull << pmu->nr_arch_gp_counters) - 1);
607 		}
608 	}
609 }
610 
611 static void intel_pmu_init(struct kvm_vcpu *vcpu)
612 {
613 	int i;
614 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
615 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
616 
617 	if (!lbr_desc)
618 		return;
619 
620 	for (i = 0; i < KVM_MAX_NR_INTEL_GP_COUNTERS; i++) {
621 		pmu->gp_counters[i].type = KVM_PMC_GP;
622 		pmu->gp_counters[i].vcpu = vcpu;
623 		pmu->gp_counters[i].idx = i;
624 		pmu->gp_counters[i].current_config = 0;
625 	}
626 
627 	for (i = 0; i < KVM_MAX_NR_INTEL_FIXED_COUTNERS; i++) {
628 		pmu->fixed_counters[i].type = KVM_PMC_FIXED;
629 		pmu->fixed_counters[i].vcpu = vcpu;
630 		pmu->fixed_counters[i].idx = i + KVM_FIXED_PMC_BASE_IDX;
631 		pmu->fixed_counters[i].current_config = 0;
632 		pmu->fixed_counters[i].eventsel = intel_get_fixed_pmc_eventsel(i);
633 	}
634 
635 	lbr_desc->records.nr = 0;
636 	lbr_desc->event = NULL;
637 	lbr_desc->msr_passthrough = false;
638 }
639 
640 static void intel_pmu_reset(struct kvm_vcpu *vcpu)
641 {
642 	intel_pmu_release_guest_lbr_event(vcpu);
643 }
644 
645 /*
646  * Emulate LBR_On_PMI behavior for 1 < pmu.version < 4.
647  *
648  * If Freeze_LBR_On_PMI = 1, the LBR is frozen on PMI and
649  * the KVM emulates to clear the LBR bit (bit 0) in IA32_DEBUGCTL.
650  *
651  * Guest needs to re-enable LBR to resume branches recording.
652  */
653 static void intel_pmu_legacy_freezing_lbrs_on_pmi(struct kvm_vcpu *vcpu)
654 {
655 	u64 data = vmcs_read64(GUEST_IA32_DEBUGCTL);
656 
657 	if (data & DEBUGCTLMSR_FREEZE_LBRS_ON_PMI) {
658 		data &= ~DEBUGCTLMSR_LBR;
659 		vmcs_write64(GUEST_IA32_DEBUGCTL, data);
660 	}
661 }
662 
663 static void intel_pmu_deliver_pmi(struct kvm_vcpu *vcpu)
664 {
665 	u8 version = vcpu_to_pmu(vcpu)->version;
666 
667 	if (!intel_pmu_lbr_is_enabled(vcpu))
668 		return;
669 
670 	if (version > 1 && version < 4)
671 		intel_pmu_legacy_freezing_lbrs_on_pmi(vcpu);
672 }
673 
674 static void vmx_update_intercept_for_lbr_msrs(struct kvm_vcpu *vcpu, bool set)
675 {
676 	struct x86_pmu_lbr *lbr = vcpu_to_lbr_records(vcpu);
677 	int i;
678 
679 	for (i = 0; i < lbr->nr; i++) {
680 		vmx_set_intercept_for_msr(vcpu, lbr->from + i, MSR_TYPE_RW, set);
681 		vmx_set_intercept_for_msr(vcpu, lbr->to + i, MSR_TYPE_RW, set);
682 		if (lbr->info)
683 			vmx_set_intercept_for_msr(vcpu, lbr->info + i, MSR_TYPE_RW, set);
684 	}
685 
686 	vmx_set_intercept_for_msr(vcpu, MSR_LBR_SELECT, MSR_TYPE_RW, set);
687 	vmx_set_intercept_for_msr(vcpu, MSR_LBR_TOS, MSR_TYPE_RW, set);
688 }
689 
690 static inline void vmx_disable_lbr_msrs_passthrough(struct kvm_vcpu *vcpu)
691 {
692 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
693 
694 	if (!lbr_desc->msr_passthrough)
695 		return;
696 
697 	vmx_update_intercept_for_lbr_msrs(vcpu, true);
698 	lbr_desc->msr_passthrough = false;
699 }
700 
701 static inline void vmx_enable_lbr_msrs_passthrough(struct kvm_vcpu *vcpu)
702 {
703 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
704 
705 	if (lbr_desc->msr_passthrough)
706 		return;
707 
708 	vmx_update_intercept_for_lbr_msrs(vcpu, false);
709 	lbr_desc->msr_passthrough = true;
710 }
711 
712 /*
713  * Higher priority host perf events (e.g. cpu pinned) could reclaim the
714  * pmu resources (e.g. LBR) that were assigned to the guest. This is
715  * usually done via ipi calls (more details in perf_install_in_context).
716  *
717  * Before entering the non-root mode (with irq disabled here), double
718  * confirm that the pmu features enabled to the guest are not reclaimed
719  * by higher priority host events. Otherwise, disallow vcpu's access to
720  * the reclaimed features.
721  */
722 void vmx_passthrough_lbr_msrs(struct kvm_vcpu *vcpu)
723 {
724 	struct kvm_pmu *pmu = vcpu_to_pmu(vcpu);
725 	struct lbr_desc *lbr_desc = vcpu_to_lbr_desc(vcpu);
726 
727 	if (WARN_ON_ONCE(!lbr_desc))
728 		return;
729 
730 	if (!lbr_desc->event) {
731 		vmx_disable_lbr_msrs_passthrough(vcpu);
732 		if (vmcs_read64(GUEST_IA32_DEBUGCTL) & DEBUGCTLMSR_LBR)
733 			goto warn;
734 		if (test_bit(INTEL_PMC_IDX_FIXED_VLBR, pmu->pmc_in_use))
735 			goto warn;
736 		return;
737 	}
738 
739 	if (lbr_desc->event->state < PERF_EVENT_STATE_ACTIVE) {
740 		vmx_disable_lbr_msrs_passthrough(vcpu);
741 		__clear_bit(INTEL_PMC_IDX_FIXED_VLBR, pmu->pmc_in_use);
742 		goto warn;
743 	} else
744 		vmx_enable_lbr_msrs_passthrough(vcpu);
745 
746 	return;
747 
748 warn:
749 	pr_warn_ratelimited("vcpu-%d: fail to passthrough LBR.\n", vcpu->vcpu_id);
750 }
751 
752 static void intel_pmu_cleanup(struct kvm_vcpu *vcpu)
753 {
754 	if (!(vmcs_read64(GUEST_IA32_DEBUGCTL) & DEBUGCTLMSR_LBR))
755 		intel_pmu_release_guest_lbr_event(vcpu);
756 }
757 
758 void intel_pmu_cross_mapped_check(struct kvm_pmu *pmu)
759 {
760 	struct kvm_pmc *pmc = NULL;
761 	int bit, hw_idx;
762 
763 	kvm_for_each_pmc(pmu, pmc, bit, (unsigned long *)&pmu->global_ctrl) {
764 		if (!pmc_speculative_in_use(pmc) ||
765 		    !pmc_is_globally_enabled(pmc) || !pmc->perf_event)
766 			continue;
767 
768 		/*
769 		 * A negative index indicates the event isn't mapped to a
770 		 * physical counter in the host, e.g. due to contention.
771 		 */
772 		hw_idx = pmc->perf_event->hw.idx;
773 		if (hw_idx != pmc->idx && hw_idx > -1)
774 			pmu->host_cross_mapped_mask |= BIT_ULL(hw_idx);
775 	}
776 }
777 
778 struct kvm_pmu_ops intel_pmu_ops __initdata = {
779 	.rdpmc_ecx_to_pmc = intel_rdpmc_ecx_to_pmc,
780 	.msr_idx_to_pmc = intel_msr_idx_to_pmc,
781 	.is_valid_msr = intel_is_valid_msr,
782 	.get_msr = intel_pmu_get_msr,
783 	.set_msr = intel_pmu_set_msr,
784 	.refresh = intel_pmu_refresh,
785 	.init = intel_pmu_init,
786 	.reset = intel_pmu_reset,
787 	.deliver_pmi = intel_pmu_deliver_pmi,
788 	.cleanup = intel_pmu_cleanup,
789 	.EVENTSEL_EVENT = ARCH_PERFMON_EVENTSEL_EVENT,
790 	.MAX_NR_GP_COUNTERS = KVM_MAX_NR_INTEL_GP_COUNTERS,
791 	.MIN_NR_GP_COUNTERS = 1,
792 };
793