xref: /linux/tools/testing/selftests/kvm/include/x86/processor.h (revision 9b47f288eb67b1081d20456d391ef12a47374e09)
1 /* SPDX-License-Identifier: GPL-2.0-only */
2 /*
3  * Copyright (C) 2018, Google LLC.
4  */
5 
6 #ifndef SELFTEST_KVM_PROCESSOR_H
7 #define SELFTEST_KVM_PROCESSOR_H
8 
9 #include <assert.h>
10 #include <stdint.h>
11 #include <syscall.h>
12 
13 #include <asm/msr-index.h>
14 #include <asm/prctl.h>
15 
16 #include <linux/kvm_para.h>
17 #include <linux/stringify.h>
18 
19 #include "kvm_util.h"
20 #include "ucall_common.h"
21 
22 extern bool host_cpu_is_intel;
23 extern bool host_cpu_is_amd;
24 extern uint64_t guest_tsc_khz;
25 
26 #ifndef MAX_NR_CPUID_ENTRIES
27 #define MAX_NR_CPUID_ENTRIES 100
28 #endif
29 
30 #define NONCANONICAL 0xaaaaaaaaaaaaaaaaull
31 
32 /* Forced emulation prefix, used to invoke the emulator unconditionally. */
33 #define KVM_FEP "ud2; .byte 'k', 'v', 'm';"
34 
35 #define NMI_VECTOR		0x02
36 
37 #define X86_EFLAGS_FIXED	 (1u << 1)
38 
39 #define X86_CR4_VME		(1ul << 0)
40 #define X86_CR4_PVI		(1ul << 1)
41 #define X86_CR4_TSD		(1ul << 2)
42 #define X86_CR4_DE		(1ul << 3)
43 #define X86_CR4_PSE		(1ul << 4)
44 #define X86_CR4_PAE		(1ul << 5)
45 #define X86_CR4_MCE		(1ul << 6)
46 #define X86_CR4_PGE		(1ul << 7)
47 #define X86_CR4_PCE		(1ul << 8)
48 #define X86_CR4_OSFXSR		(1ul << 9)
49 #define X86_CR4_OSXMMEXCPT	(1ul << 10)
50 #define X86_CR4_UMIP		(1ul << 11)
51 #define X86_CR4_LA57		(1ul << 12)
52 #define X86_CR4_VMXE		(1ul << 13)
53 #define X86_CR4_SMXE		(1ul << 14)
54 #define X86_CR4_FSGSBASE	(1ul << 16)
55 #define X86_CR4_PCIDE		(1ul << 17)
56 #define X86_CR4_OSXSAVE		(1ul << 18)
57 #define X86_CR4_SMEP		(1ul << 20)
58 #define X86_CR4_SMAP		(1ul << 21)
59 #define X86_CR4_PKE		(1ul << 22)
60 
61 struct xstate_header {
62 	u64				xstate_bv;
63 	u64				xcomp_bv;
64 	u64				reserved[6];
65 } __attribute__((packed));
66 
67 struct xstate {
68 	u8				i387[512];
69 	struct xstate_header		header;
70 	u8				extended_state_area[0];
71 } __attribute__ ((packed, aligned (64)));
72 
73 #define XFEATURE_MASK_FP		BIT_ULL(0)
74 #define XFEATURE_MASK_SSE		BIT_ULL(1)
75 #define XFEATURE_MASK_YMM		BIT_ULL(2)
76 #define XFEATURE_MASK_BNDREGS		BIT_ULL(3)
77 #define XFEATURE_MASK_BNDCSR		BIT_ULL(4)
78 #define XFEATURE_MASK_OPMASK		BIT_ULL(5)
79 #define XFEATURE_MASK_ZMM_Hi256		BIT_ULL(6)
80 #define XFEATURE_MASK_Hi16_ZMM		BIT_ULL(7)
81 #define XFEATURE_MASK_PT		BIT_ULL(8)
82 #define XFEATURE_MASK_PKRU		BIT_ULL(9)
83 #define XFEATURE_MASK_PASID		BIT_ULL(10)
84 #define XFEATURE_MASK_CET_USER		BIT_ULL(11)
85 #define XFEATURE_MASK_CET_KERNEL	BIT_ULL(12)
86 #define XFEATURE_MASK_LBR		BIT_ULL(15)
87 #define XFEATURE_MASK_XTILE_CFG		BIT_ULL(17)
88 #define XFEATURE_MASK_XTILE_DATA	BIT_ULL(18)
89 
90 #define XFEATURE_MASK_AVX512		(XFEATURE_MASK_OPMASK | \
91 					 XFEATURE_MASK_ZMM_Hi256 | \
92 					 XFEATURE_MASK_Hi16_ZMM)
93 #define XFEATURE_MASK_XTILE		(XFEATURE_MASK_XTILE_DATA | \
94 					 XFEATURE_MASK_XTILE_CFG)
95 
96 /* Note, these are ordered alphabetically to match kvm_cpuid_entry2.  Eww. */
97 enum cpuid_output_regs {
98 	KVM_CPUID_EAX,
99 	KVM_CPUID_EBX,
100 	KVM_CPUID_ECX,
101 	KVM_CPUID_EDX
102 };
103 
104 /*
105  * Pack the information into a 64-bit value so that each X86_FEATURE_XXX can be
106  * passed by value with no overhead.
107  */
108 struct kvm_x86_cpu_feature {
109 	u32	function;
110 	u16	index;
111 	u8	reg;
112 	u8	bit;
113 };
114 #define	KVM_X86_CPU_FEATURE(fn, idx, gpr, __bit)				\
115 ({										\
116 	struct kvm_x86_cpu_feature feature = {					\
117 		.function = fn,							\
118 		.index = idx,							\
119 		.reg = KVM_CPUID_##gpr,						\
120 		.bit = __bit,							\
121 	};									\
122 										\
123 	kvm_static_assert((fn & 0xc0000000) == 0 ||				\
124 			  (fn & 0xc0000000) == 0x40000000 ||			\
125 			  (fn & 0xc0000000) == 0x80000000 ||			\
126 			  (fn & 0xc0000000) == 0xc0000000);			\
127 	kvm_static_assert(idx < BIT(sizeof(feature.index) * BITS_PER_BYTE));	\
128 	feature;								\
129 })
130 
131 /*
132  * Basic Leafs, a.k.a. Intel defined
133  */
134 #define	X86_FEATURE_MWAIT		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 3)
135 #define	X86_FEATURE_VMX			KVM_X86_CPU_FEATURE(0x1, 0, ECX, 5)
136 #define	X86_FEATURE_SMX			KVM_X86_CPU_FEATURE(0x1, 0, ECX, 6)
137 #define	X86_FEATURE_PDCM		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 15)
138 #define	X86_FEATURE_PCID		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 17)
139 #define X86_FEATURE_X2APIC		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 21)
140 #define	X86_FEATURE_MOVBE		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 22)
141 #define	X86_FEATURE_TSC_DEADLINE_TIMER	KVM_X86_CPU_FEATURE(0x1, 0, ECX, 24)
142 #define	X86_FEATURE_XSAVE		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 26)
143 #define	X86_FEATURE_OSXSAVE		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 27)
144 #define	X86_FEATURE_RDRAND		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 30)
145 #define	X86_FEATURE_HYPERVISOR		KVM_X86_CPU_FEATURE(0x1, 0, ECX, 31)
146 #define X86_FEATURE_PAE			KVM_X86_CPU_FEATURE(0x1, 0, EDX, 6)
147 #define	X86_FEATURE_MCE			KVM_X86_CPU_FEATURE(0x1, 0, EDX, 7)
148 #define	X86_FEATURE_APIC		KVM_X86_CPU_FEATURE(0x1, 0, EDX, 9)
149 #define	X86_FEATURE_CLFLUSH		KVM_X86_CPU_FEATURE(0x1, 0, EDX, 19)
150 #define	X86_FEATURE_XMM			KVM_X86_CPU_FEATURE(0x1, 0, EDX, 25)
151 #define	X86_FEATURE_XMM2		KVM_X86_CPU_FEATURE(0x1, 0, EDX, 26)
152 #define	X86_FEATURE_FSGSBASE		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 0)
153 #define	X86_FEATURE_TSC_ADJUST		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 1)
154 #define	X86_FEATURE_SGX			KVM_X86_CPU_FEATURE(0x7, 0, EBX, 2)
155 #define	X86_FEATURE_HLE			KVM_X86_CPU_FEATURE(0x7, 0, EBX, 4)
156 #define	X86_FEATURE_SMEP	        KVM_X86_CPU_FEATURE(0x7, 0, EBX, 7)
157 #define	X86_FEATURE_INVPCID		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 10)
158 #define	X86_FEATURE_RTM			KVM_X86_CPU_FEATURE(0x7, 0, EBX, 11)
159 #define	X86_FEATURE_MPX			KVM_X86_CPU_FEATURE(0x7, 0, EBX, 14)
160 #define	X86_FEATURE_SMAP		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 20)
161 #define	X86_FEATURE_PCOMMIT		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 22)
162 #define	X86_FEATURE_CLFLUSHOPT		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 23)
163 #define	X86_FEATURE_CLWB		KVM_X86_CPU_FEATURE(0x7, 0, EBX, 24)
164 #define	X86_FEATURE_UMIP		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 2)
165 #define	X86_FEATURE_PKU			KVM_X86_CPU_FEATURE(0x7, 0, ECX, 3)
166 #define	X86_FEATURE_OSPKE		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 4)
167 #define	X86_FEATURE_LA57		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 16)
168 #define	X86_FEATURE_RDPID		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 22)
169 #define	X86_FEATURE_SGX_LC		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 30)
170 #define	X86_FEATURE_SHSTK		KVM_X86_CPU_FEATURE(0x7, 0, ECX, 7)
171 #define	X86_FEATURE_IBT			KVM_X86_CPU_FEATURE(0x7, 0, EDX, 20)
172 #define	X86_FEATURE_AMX_TILE		KVM_X86_CPU_FEATURE(0x7, 0, EDX, 24)
173 #define	X86_FEATURE_SPEC_CTRL		KVM_X86_CPU_FEATURE(0x7, 0, EDX, 26)
174 #define	X86_FEATURE_ARCH_CAPABILITIES	KVM_X86_CPU_FEATURE(0x7, 0, EDX, 29)
175 #define	X86_FEATURE_PKS			KVM_X86_CPU_FEATURE(0x7, 0, ECX, 31)
176 #define	X86_FEATURE_XTILECFG		KVM_X86_CPU_FEATURE(0xD, 0, EAX, 17)
177 #define	X86_FEATURE_XTILEDATA		KVM_X86_CPU_FEATURE(0xD, 0, EAX, 18)
178 #define	X86_FEATURE_XSAVES		KVM_X86_CPU_FEATURE(0xD, 1, EAX, 3)
179 #define	X86_FEATURE_XFD			KVM_X86_CPU_FEATURE(0xD, 1, EAX, 4)
180 #define X86_FEATURE_XTILEDATA_XFD	KVM_X86_CPU_FEATURE(0xD, 18, ECX, 2)
181 
182 /*
183  * Extended Leafs, a.k.a. AMD defined
184  */
185 #define	X86_FEATURE_SVM			KVM_X86_CPU_FEATURE(0x80000001, 0, ECX, 2)
186 #define	X86_FEATURE_PERFCTR_CORE	KVM_X86_CPU_FEATURE(0x80000001, 0, ECX, 23)
187 #define	X86_FEATURE_PERFCTR_NB		KVM_X86_CPU_FEATURE(0x80000001, 0, ECX, 24)
188 #define	X86_FEATURE_PERFCTR_LLC		KVM_X86_CPU_FEATURE(0x80000001, 0, ECX, 28)
189 #define	X86_FEATURE_NX			KVM_X86_CPU_FEATURE(0x80000001, 0, EDX, 20)
190 #define	X86_FEATURE_GBPAGES		KVM_X86_CPU_FEATURE(0x80000001, 0, EDX, 26)
191 #define	X86_FEATURE_RDTSCP		KVM_X86_CPU_FEATURE(0x80000001, 0, EDX, 27)
192 #define	X86_FEATURE_LM			KVM_X86_CPU_FEATURE(0x80000001, 0, EDX, 29)
193 #define	X86_FEATURE_INVTSC		KVM_X86_CPU_FEATURE(0x80000007, 0, EDX, 8)
194 #define	X86_FEATURE_RDPRU		KVM_X86_CPU_FEATURE(0x80000008, 0, EBX, 4)
195 #define	X86_FEATURE_AMD_IBPB		KVM_X86_CPU_FEATURE(0x80000008, 0, EBX, 12)
196 #define	X86_FEATURE_NPT			KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 0)
197 #define	X86_FEATURE_LBRV		KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 1)
198 #define	X86_FEATURE_NRIPS		KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 3)
199 #define X86_FEATURE_TSCRATEMSR          KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 4)
200 #define X86_FEATURE_PAUSEFILTER         KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 10)
201 #define X86_FEATURE_PFTHRESHOLD         KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 12)
202 #define	X86_FEATURE_VGIF		KVM_X86_CPU_FEATURE(0x8000000A, 0, EDX, 16)
203 #define X86_FEATURE_SEV			KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 1)
204 #define X86_FEATURE_SEV_ES		KVM_X86_CPU_FEATURE(0x8000001F, 0, EAX, 3)
205 #define	X86_FEATURE_PERFMON_V2		KVM_X86_CPU_FEATURE(0x80000022, 0, EAX, 0)
206 #define	X86_FEATURE_LBR_PMC_FREEZE	KVM_X86_CPU_FEATURE(0x80000022, 0, EAX, 2)
207 
208 /*
209  * KVM defined paravirt features.
210  */
211 #define X86_FEATURE_KVM_CLOCKSOURCE	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 0)
212 #define X86_FEATURE_KVM_NOP_IO_DELAY	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 1)
213 #define X86_FEATURE_KVM_MMU_OP		KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 2)
214 #define X86_FEATURE_KVM_CLOCKSOURCE2	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 3)
215 #define X86_FEATURE_KVM_ASYNC_PF	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 4)
216 #define X86_FEATURE_KVM_STEAL_TIME	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 5)
217 #define X86_FEATURE_KVM_PV_EOI		KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 6)
218 #define X86_FEATURE_KVM_PV_UNHALT	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 7)
219 /* Bit 8 apparently isn't used?!?! */
220 #define X86_FEATURE_KVM_PV_TLB_FLUSH	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 9)
221 #define X86_FEATURE_KVM_ASYNC_PF_VMEXIT	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 10)
222 #define X86_FEATURE_KVM_PV_SEND_IPI	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 11)
223 #define X86_FEATURE_KVM_POLL_CONTROL	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 12)
224 #define X86_FEATURE_KVM_PV_SCHED_YIELD	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 13)
225 #define X86_FEATURE_KVM_ASYNC_PF_INT	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 14)
226 #define X86_FEATURE_KVM_MSI_EXT_DEST_ID	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 15)
227 #define X86_FEATURE_KVM_HC_MAP_GPA_RANGE	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 16)
228 #define X86_FEATURE_KVM_MIGRATION_CONTROL	KVM_X86_CPU_FEATURE(0x40000001, 0, EAX, 17)
229 
230 /*
231  * Same idea as X86_FEATURE_XXX, but X86_PROPERTY_XXX retrieves a multi-bit
232  * value/property as opposed to a single-bit feature.  Again, pack the info
233  * into a 64-bit value to pass by value with no overhead.
234  */
235 struct kvm_x86_cpu_property {
236 	u32	function;
237 	u8	index;
238 	u8	reg;
239 	u8	lo_bit;
240 	u8	hi_bit;
241 };
242 #define	KVM_X86_CPU_PROPERTY(fn, idx, gpr, low_bit, high_bit)			\
243 ({										\
244 	struct kvm_x86_cpu_property property = {				\
245 		.function = fn,							\
246 		.index = idx,							\
247 		.reg = KVM_CPUID_##gpr,						\
248 		.lo_bit = low_bit,						\
249 		.hi_bit = high_bit,						\
250 	};									\
251 										\
252 	kvm_static_assert(low_bit < high_bit);					\
253 	kvm_static_assert((fn & 0xc0000000) == 0 ||				\
254 			  (fn & 0xc0000000) == 0x40000000 ||			\
255 			  (fn & 0xc0000000) == 0x80000000 ||			\
256 			  (fn & 0xc0000000) == 0xc0000000);			\
257 	kvm_static_assert(idx < BIT(sizeof(property.index) * BITS_PER_BYTE));	\
258 	property;								\
259 })
260 
261 #define X86_PROPERTY_MAX_BASIC_LEAF		KVM_X86_CPU_PROPERTY(0, 0, EAX, 0, 31)
262 #define X86_PROPERTY_PMU_VERSION		KVM_X86_CPU_PROPERTY(0xa, 0, EAX, 0, 7)
263 #define X86_PROPERTY_PMU_NR_GP_COUNTERS		KVM_X86_CPU_PROPERTY(0xa, 0, EAX, 8, 15)
264 #define X86_PROPERTY_PMU_GP_COUNTERS_BIT_WIDTH	KVM_X86_CPU_PROPERTY(0xa, 0, EAX, 16, 23)
265 #define X86_PROPERTY_PMU_EBX_BIT_VECTOR_LENGTH	KVM_X86_CPU_PROPERTY(0xa, 0, EAX, 24, 31)
266 #define X86_PROPERTY_PMU_EVENTS_MASK		KVM_X86_CPU_PROPERTY(0xa, 0, EBX, 0, 7)
267 #define X86_PROPERTY_PMU_FIXED_COUNTERS_BITMASK	KVM_X86_CPU_PROPERTY(0xa, 0, ECX, 0, 31)
268 #define X86_PROPERTY_PMU_NR_FIXED_COUNTERS	KVM_X86_CPU_PROPERTY(0xa, 0, EDX, 0, 4)
269 #define X86_PROPERTY_PMU_FIXED_COUNTERS_BIT_WIDTH	KVM_X86_CPU_PROPERTY(0xa, 0, EDX, 5, 12)
270 
271 #define X86_PROPERTY_SUPPORTED_XCR0_LO		KVM_X86_CPU_PROPERTY(0xd,  0, EAX,  0, 31)
272 #define X86_PROPERTY_XSTATE_MAX_SIZE_XCR0	KVM_X86_CPU_PROPERTY(0xd,  0, EBX,  0, 31)
273 #define X86_PROPERTY_XSTATE_MAX_SIZE		KVM_X86_CPU_PROPERTY(0xd,  0, ECX,  0, 31)
274 #define X86_PROPERTY_SUPPORTED_XCR0_HI		KVM_X86_CPU_PROPERTY(0xd,  0, EDX,  0, 31)
275 
276 #define X86_PROPERTY_XSTATE_TILE_SIZE		KVM_X86_CPU_PROPERTY(0xd, 18, EAX,  0, 31)
277 #define X86_PROPERTY_XSTATE_TILE_OFFSET		KVM_X86_CPU_PROPERTY(0xd, 18, EBX,  0, 31)
278 #define X86_PROPERTY_AMX_MAX_PALETTE_TABLES	KVM_X86_CPU_PROPERTY(0x1d, 0, EAX,  0, 31)
279 #define X86_PROPERTY_AMX_TOTAL_TILE_BYTES	KVM_X86_CPU_PROPERTY(0x1d, 1, EAX,  0, 15)
280 #define X86_PROPERTY_AMX_BYTES_PER_TILE		KVM_X86_CPU_PROPERTY(0x1d, 1, EAX, 16, 31)
281 #define X86_PROPERTY_AMX_BYTES_PER_ROW		KVM_X86_CPU_PROPERTY(0x1d, 1, EBX, 0,  15)
282 #define X86_PROPERTY_AMX_NR_TILE_REGS		KVM_X86_CPU_PROPERTY(0x1d, 1, EBX, 16, 31)
283 #define X86_PROPERTY_AMX_MAX_ROWS		KVM_X86_CPU_PROPERTY(0x1d, 1, ECX, 0,  15)
284 
285 #define X86_PROPERTY_MAX_KVM_LEAF		KVM_X86_CPU_PROPERTY(0x40000000, 0, EAX, 0, 31)
286 
287 #define X86_PROPERTY_MAX_EXT_LEAF		KVM_X86_CPU_PROPERTY(0x80000000, 0, EAX, 0, 31)
288 #define X86_PROPERTY_MAX_PHY_ADDR		KVM_X86_CPU_PROPERTY(0x80000008, 0, EAX, 0, 7)
289 #define X86_PROPERTY_MAX_VIRT_ADDR		KVM_X86_CPU_PROPERTY(0x80000008, 0, EAX, 8, 15)
290 #define X86_PROPERTY_GUEST_MAX_PHY_ADDR		KVM_X86_CPU_PROPERTY(0x80000008, 0, EAX, 16, 23)
291 #define X86_PROPERTY_SEV_C_BIT			KVM_X86_CPU_PROPERTY(0x8000001F, 0, EBX, 0, 5)
292 #define X86_PROPERTY_PHYS_ADDR_REDUCTION	KVM_X86_CPU_PROPERTY(0x8000001F, 0, EBX, 6, 11)
293 #define X86_PROPERTY_NR_PERFCTR_CORE		KVM_X86_CPU_PROPERTY(0x80000022, 0, EBX, 0, 3)
294 #define X86_PROPERTY_NR_PERFCTR_NB		KVM_X86_CPU_PROPERTY(0x80000022, 0, EBX, 10, 15)
295 
296 #define X86_PROPERTY_MAX_CENTAUR_LEAF		KVM_X86_CPU_PROPERTY(0xC0000000, 0, EAX, 0, 31)
297 
298 /*
299  * Intel's architectural PMU events are bizarre.  They have a "feature" bit
300  * that indicates the feature is _not_ supported, and a property that states
301  * the length of the bit mask of unsupported features.  A feature is supported
302  * if the size of the bit mask is larger than the "unavailable" bit, and said
303  * bit is not set.  Fixed counters also bizarre enumeration, but inverted from
304  * arch events for general purpose counters.  Fixed counters are supported if a
305  * feature flag is set **OR** the total number of fixed counters is greater
306  * than index of the counter.
307  *
308  * Wrap the events for general purpose and fixed counters to simplify checking
309  * whether or not a given architectural event is supported.
310  */
311 struct kvm_x86_pmu_feature {
312 	struct kvm_x86_cpu_feature f;
313 };
314 #define	KVM_X86_PMU_FEATURE(__reg, __bit)				\
315 ({									\
316 	struct kvm_x86_pmu_feature feature = {				\
317 		.f = KVM_X86_CPU_FEATURE(0xa, 0, __reg, __bit),		\
318 	};								\
319 									\
320 	kvm_static_assert(KVM_CPUID_##__reg == KVM_CPUID_EBX ||		\
321 			  KVM_CPUID_##__reg == KVM_CPUID_ECX);		\
322 	feature;							\
323 })
324 
325 #define X86_PMU_FEATURE_CPU_CYCLES			KVM_X86_PMU_FEATURE(EBX, 0)
326 #define X86_PMU_FEATURE_INSNS_RETIRED			KVM_X86_PMU_FEATURE(EBX, 1)
327 #define X86_PMU_FEATURE_REFERENCE_CYCLES		KVM_X86_PMU_FEATURE(EBX, 2)
328 #define X86_PMU_FEATURE_LLC_REFERENCES			KVM_X86_PMU_FEATURE(EBX, 3)
329 #define X86_PMU_FEATURE_LLC_MISSES			KVM_X86_PMU_FEATURE(EBX, 4)
330 #define X86_PMU_FEATURE_BRANCH_INSNS_RETIRED		KVM_X86_PMU_FEATURE(EBX, 5)
331 #define X86_PMU_FEATURE_BRANCHES_MISPREDICTED		KVM_X86_PMU_FEATURE(EBX, 6)
332 #define X86_PMU_FEATURE_TOPDOWN_SLOTS			KVM_X86_PMU_FEATURE(EBX, 7)
333 
334 #define X86_PMU_FEATURE_INSNS_RETIRED_FIXED		KVM_X86_PMU_FEATURE(ECX, 0)
335 #define X86_PMU_FEATURE_CPU_CYCLES_FIXED		KVM_X86_PMU_FEATURE(ECX, 1)
336 #define X86_PMU_FEATURE_REFERENCE_TSC_CYCLES_FIXED	KVM_X86_PMU_FEATURE(ECX, 2)
337 #define X86_PMU_FEATURE_TOPDOWN_SLOTS_FIXED		KVM_X86_PMU_FEATURE(ECX, 3)
338 
339 static inline unsigned int x86_family(unsigned int eax)
340 {
341 	unsigned int x86;
342 
343 	x86 = (eax >> 8) & 0xf;
344 
345 	if (x86 == 0xf)
346 		x86 += (eax >> 20) & 0xff;
347 
348 	return x86;
349 }
350 
351 static inline unsigned int x86_model(unsigned int eax)
352 {
353 	return ((eax >> 12) & 0xf0) | ((eax >> 4) & 0x0f);
354 }
355 
356 /* Page table bitfield declarations */
357 #define PTE_PRESENT_MASK        BIT_ULL(0)
358 #define PTE_WRITABLE_MASK       BIT_ULL(1)
359 #define PTE_USER_MASK           BIT_ULL(2)
360 #define PTE_ACCESSED_MASK       BIT_ULL(5)
361 #define PTE_DIRTY_MASK          BIT_ULL(6)
362 #define PTE_LARGE_MASK          BIT_ULL(7)
363 #define PTE_GLOBAL_MASK         BIT_ULL(8)
364 #define PTE_NX_MASK             BIT_ULL(63)
365 
366 #define PHYSICAL_PAGE_MASK      GENMASK_ULL(51, 12)
367 
368 #define PAGE_SHIFT		12
369 #define PAGE_SIZE		(1ULL << PAGE_SHIFT)
370 #define PAGE_MASK		(~(PAGE_SIZE-1) & PHYSICAL_PAGE_MASK)
371 
372 #define HUGEPAGE_SHIFT(x)	(PAGE_SHIFT + (((x) - 1) * 9))
373 #define HUGEPAGE_SIZE(x)	(1UL << HUGEPAGE_SHIFT(x))
374 #define HUGEPAGE_MASK(x)	(~(HUGEPAGE_SIZE(x) - 1) & PHYSICAL_PAGE_MASK)
375 
376 #define PTE_GET_PA(pte)		((pte) & PHYSICAL_PAGE_MASK)
377 #define PTE_GET_PFN(pte)        (PTE_GET_PA(pte) >> PAGE_SHIFT)
378 
379 /* General Registers in 64-Bit Mode */
380 struct gpr64_regs {
381 	u64 rax;
382 	u64 rcx;
383 	u64 rdx;
384 	u64 rbx;
385 	u64 rsp;
386 	u64 rbp;
387 	u64 rsi;
388 	u64 rdi;
389 	u64 r8;
390 	u64 r9;
391 	u64 r10;
392 	u64 r11;
393 	u64 r12;
394 	u64 r13;
395 	u64 r14;
396 	u64 r15;
397 };
398 
399 struct desc64 {
400 	uint16_t limit0;
401 	uint16_t base0;
402 	unsigned base1:8, type:4, s:1, dpl:2, p:1;
403 	unsigned limit1:4, avl:1, l:1, db:1, g:1, base2:8;
404 	uint32_t base3;
405 	uint32_t zero1;
406 } __attribute__((packed));
407 
408 struct desc_ptr {
409 	uint16_t size;
410 	uint64_t address;
411 } __attribute__((packed));
412 
413 struct kvm_x86_state {
414 	struct kvm_xsave *xsave;
415 	struct kvm_vcpu_events events;
416 	struct kvm_mp_state mp_state;
417 	struct kvm_regs regs;
418 	struct kvm_xcrs xcrs;
419 	struct kvm_sregs sregs;
420 	struct kvm_debugregs debugregs;
421 	union {
422 		struct kvm_nested_state nested;
423 		char nested_[16384];
424 	};
425 	struct kvm_msrs msrs;
426 };
427 
428 static inline uint64_t get_desc64_base(const struct desc64 *desc)
429 {
430 	return ((uint64_t)desc->base3 << 32) |
431 		(desc->base0 | ((desc->base1) << 16) | ((desc->base2) << 24));
432 }
433 
434 static inline uint64_t rdtsc(void)
435 {
436 	uint32_t eax, edx;
437 	uint64_t tsc_val;
438 	/*
439 	 * The lfence is to wait (on Intel CPUs) until all previous
440 	 * instructions have been executed. If software requires RDTSC to be
441 	 * executed prior to execution of any subsequent instruction, it can
442 	 * execute LFENCE immediately after RDTSC
443 	 */
444 	__asm__ __volatile__("lfence; rdtsc; lfence" : "=a"(eax), "=d"(edx));
445 	tsc_val = ((uint64_t)edx) << 32 | eax;
446 	return tsc_val;
447 }
448 
449 static inline uint64_t rdtscp(uint32_t *aux)
450 {
451 	uint32_t eax, edx;
452 
453 	__asm__ __volatile__("rdtscp" : "=a"(eax), "=d"(edx), "=c"(*aux));
454 	return ((uint64_t)edx) << 32 | eax;
455 }
456 
457 static inline uint64_t rdmsr(uint32_t msr)
458 {
459 	uint32_t a, d;
460 
461 	__asm__ __volatile__("rdmsr" : "=a"(a), "=d"(d) : "c"(msr) : "memory");
462 
463 	return a | ((uint64_t) d << 32);
464 }
465 
466 static inline void wrmsr(uint32_t msr, uint64_t value)
467 {
468 	uint32_t a = value;
469 	uint32_t d = value >> 32;
470 
471 	__asm__ __volatile__("wrmsr" :: "a"(a), "d"(d), "c"(msr) : "memory");
472 }
473 
474 
475 static inline uint16_t inw(uint16_t port)
476 {
477 	uint16_t tmp;
478 
479 	__asm__ __volatile__("in %%dx, %%ax"
480 		: /* output */ "=a" (tmp)
481 		: /* input */ "d" (port));
482 
483 	return tmp;
484 }
485 
486 static inline uint16_t get_es(void)
487 {
488 	uint16_t es;
489 
490 	__asm__ __volatile__("mov %%es, %[es]"
491 			     : /* output */ [es]"=rm"(es));
492 	return es;
493 }
494 
495 static inline uint16_t get_cs(void)
496 {
497 	uint16_t cs;
498 
499 	__asm__ __volatile__("mov %%cs, %[cs]"
500 			     : /* output */ [cs]"=rm"(cs));
501 	return cs;
502 }
503 
504 static inline uint16_t get_ss(void)
505 {
506 	uint16_t ss;
507 
508 	__asm__ __volatile__("mov %%ss, %[ss]"
509 			     : /* output */ [ss]"=rm"(ss));
510 	return ss;
511 }
512 
513 static inline uint16_t get_ds(void)
514 {
515 	uint16_t ds;
516 
517 	__asm__ __volatile__("mov %%ds, %[ds]"
518 			     : /* output */ [ds]"=rm"(ds));
519 	return ds;
520 }
521 
522 static inline uint16_t get_fs(void)
523 {
524 	uint16_t fs;
525 
526 	__asm__ __volatile__("mov %%fs, %[fs]"
527 			     : /* output */ [fs]"=rm"(fs));
528 	return fs;
529 }
530 
531 static inline uint16_t get_gs(void)
532 {
533 	uint16_t gs;
534 
535 	__asm__ __volatile__("mov %%gs, %[gs]"
536 			     : /* output */ [gs]"=rm"(gs));
537 	return gs;
538 }
539 
540 static inline uint16_t get_tr(void)
541 {
542 	uint16_t tr;
543 
544 	__asm__ __volatile__("str %[tr]"
545 			     : /* output */ [tr]"=rm"(tr));
546 	return tr;
547 }
548 
549 static inline uint64_t get_cr0(void)
550 {
551 	uint64_t cr0;
552 
553 	__asm__ __volatile__("mov %%cr0, %[cr0]"
554 			     : /* output */ [cr0]"=r"(cr0));
555 	return cr0;
556 }
557 
558 static inline uint64_t get_cr3(void)
559 {
560 	uint64_t cr3;
561 
562 	__asm__ __volatile__("mov %%cr3, %[cr3]"
563 			     : /* output */ [cr3]"=r"(cr3));
564 	return cr3;
565 }
566 
567 static inline uint64_t get_cr4(void)
568 {
569 	uint64_t cr4;
570 
571 	__asm__ __volatile__("mov %%cr4, %[cr4]"
572 			     : /* output */ [cr4]"=r"(cr4));
573 	return cr4;
574 }
575 
576 static inline void set_cr4(uint64_t val)
577 {
578 	__asm__ __volatile__("mov %0, %%cr4" : : "r" (val) : "memory");
579 }
580 
581 static inline void set_idt(const struct desc_ptr *idt_desc)
582 {
583 	__asm__ __volatile__("lidt %0"::"m"(*idt_desc));
584 }
585 
586 static inline u64 xgetbv(u32 index)
587 {
588 	u32 eax, edx;
589 
590 	__asm__ __volatile__("xgetbv;"
591 		     : "=a" (eax), "=d" (edx)
592 		     : "c" (index));
593 	return eax | ((u64)edx << 32);
594 }
595 
596 static inline void xsetbv(u32 index, u64 value)
597 {
598 	u32 eax = value;
599 	u32 edx = value >> 32;
600 
601 	__asm__ __volatile__("xsetbv" :: "a" (eax), "d" (edx), "c" (index));
602 }
603 
604 static inline void wrpkru(u32 pkru)
605 {
606 	/* Note, ECX and EDX are architecturally required to be '0'. */
607 	asm volatile(".byte 0x0f,0x01,0xef\n\t"
608 		     : : "a" (pkru), "c"(0), "d"(0));
609 }
610 
611 static inline struct desc_ptr get_gdt(void)
612 {
613 	struct desc_ptr gdt;
614 	__asm__ __volatile__("sgdt %[gdt]"
615 			     : /* output */ [gdt]"=m"(gdt));
616 	return gdt;
617 }
618 
619 static inline struct desc_ptr get_idt(void)
620 {
621 	struct desc_ptr idt;
622 	__asm__ __volatile__("sidt %[idt]"
623 			     : /* output */ [idt]"=m"(idt));
624 	return idt;
625 }
626 
627 static inline void outl(uint16_t port, uint32_t value)
628 {
629 	__asm__ __volatile__("outl %%eax, %%dx" : : "d"(port), "a"(value));
630 }
631 
632 static inline void __cpuid(uint32_t function, uint32_t index,
633 			   uint32_t *eax, uint32_t *ebx,
634 			   uint32_t *ecx, uint32_t *edx)
635 {
636 	*eax = function;
637 	*ecx = index;
638 
639 	asm volatile("cpuid"
640 	    : "=a" (*eax),
641 	      "=b" (*ebx),
642 	      "=c" (*ecx),
643 	      "=d" (*edx)
644 	    : "0" (*eax), "2" (*ecx)
645 	    : "memory");
646 }
647 
648 static inline void cpuid(uint32_t function,
649 			 uint32_t *eax, uint32_t *ebx,
650 			 uint32_t *ecx, uint32_t *edx)
651 {
652 	return __cpuid(function, 0, eax, ebx, ecx, edx);
653 }
654 
655 static inline uint32_t this_cpu_fms(void)
656 {
657 	uint32_t eax, ebx, ecx, edx;
658 
659 	cpuid(1, &eax, &ebx, &ecx, &edx);
660 	return eax;
661 }
662 
663 static inline uint32_t this_cpu_family(void)
664 {
665 	return x86_family(this_cpu_fms());
666 }
667 
668 static inline uint32_t this_cpu_model(void)
669 {
670 	return x86_model(this_cpu_fms());
671 }
672 
673 static inline bool this_cpu_vendor_string_is(const char *vendor)
674 {
675 	const uint32_t *chunk = (const uint32_t *)vendor;
676 	uint32_t eax, ebx, ecx, edx;
677 
678 	cpuid(0, &eax, &ebx, &ecx, &edx);
679 	return (ebx == chunk[0] && edx == chunk[1] && ecx == chunk[2]);
680 }
681 
682 static inline bool this_cpu_is_intel(void)
683 {
684 	return this_cpu_vendor_string_is("GenuineIntel");
685 }
686 
687 /*
688  * Exclude early K5 samples with a vendor string of "AMDisbetter!"
689  */
690 static inline bool this_cpu_is_amd(void)
691 {
692 	return this_cpu_vendor_string_is("AuthenticAMD");
693 }
694 
695 static inline uint32_t __this_cpu_has(uint32_t function, uint32_t index,
696 				      uint8_t reg, uint8_t lo, uint8_t hi)
697 {
698 	uint32_t gprs[4];
699 
700 	__cpuid(function, index,
701 		&gprs[KVM_CPUID_EAX], &gprs[KVM_CPUID_EBX],
702 		&gprs[KVM_CPUID_ECX], &gprs[KVM_CPUID_EDX]);
703 
704 	return (gprs[reg] & GENMASK(hi, lo)) >> lo;
705 }
706 
707 static inline bool this_cpu_has(struct kvm_x86_cpu_feature feature)
708 {
709 	return __this_cpu_has(feature.function, feature.index,
710 			      feature.reg, feature.bit, feature.bit);
711 }
712 
713 static inline uint32_t this_cpu_property(struct kvm_x86_cpu_property property)
714 {
715 	return __this_cpu_has(property.function, property.index,
716 			      property.reg, property.lo_bit, property.hi_bit);
717 }
718 
719 static __always_inline bool this_cpu_has_p(struct kvm_x86_cpu_property property)
720 {
721 	uint32_t max_leaf;
722 
723 	switch (property.function & 0xc0000000) {
724 	case 0:
725 		max_leaf = this_cpu_property(X86_PROPERTY_MAX_BASIC_LEAF);
726 		break;
727 	case 0x40000000:
728 		max_leaf = this_cpu_property(X86_PROPERTY_MAX_KVM_LEAF);
729 		break;
730 	case 0x80000000:
731 		max_leaf = this_cpu_property(X86_PROPERTY_MAX_EXT_LEAF);
732 		break;
733 	case 0xc0000000:
734 		max_leaf = this_cpu_property(X86_PROPERTY_MAX_CENTAUR_LEAF);
735 	}
736 	return max_leaf >= property.function;
737 }
738 
739 static inline bool this_pmu_has(struct kvm_x86_pmu_feature feature)
740 {
741 	uint32_t nr_bits;
742 
743 	if (feature.f.reg == KVM_CPUID_EBX) {
744 		nr_bits = this_cpu_property(X86_PROPERTY_PMU_EBX_BIT_VECTOR_LENGTH);
745 		return nr_bits > feature.f.bit && !this_cpu_has(feature.f);
746 	}
747 
748 	GUEST_ASSERT(feature.f.reg == KVM_CPUID_ECX);
749 	nr_bits = this_cpu_property(X86_PROPERTY_PMU_NR_FIXED_COUNTERS);
750 	return nr_bits > feature.f.bit || this_cpu_has(feature.f);
751 }
752 
753 static __always_inline uint64_t this_cpu_supported_xcr0(void)
754 {
755 	if (!this_cpu_has_p(X86_PROPERTY_SUPPORTED_XCR0_LO))
756 		return 0;
757 
758 	return this_cpu_property(X86_PROPERTY_SUPPORTED_XCR0_LO) |
759 	       ((uint64_t)this_cpu_property(X86_PROPERTY_SUPPORTED_XCR0_HI) << 32);
760 }
761 
762 typedef u32		__attribute__((vector_size(16))) sse128_t;
763 #define __sse128_u	union { sse128_t vec; u64 as_u64[2]; u32 as_u32[4]; }
764 #define sse128_lo(x)	({ __sse128_u t; t.vec = x; t.as_u64[0]; })
765 #define sse128_hi(x)	({ __sse128_u t; t.vec = x; t.as_u64[1]; })
766 
767 static inline void read_sse_reg(int reg, sse128_t *data)
768 {
769 	switch (reg) {
770 	case 0:
771 		asm("movdqa %%xmm0, %0" : "=m"(*data));
772 		break;
773 	case 1:
774 		asm("movdqa %%xmm1, %0" : "=m"(*data));
775 		break;
776 	case 2:
777 		asm("movdqa %%xmm2, %0" : "=m"(*data));
778 		break;
779 	case 3:
780 		asm("movdqa %%xmm3, %0" : "=m"(*data));
781 		break;
782 	case 4:
783 		asm("movdqa %%xmm4, %0" : "=m"(*data));
784 		break;
785 	case 5:
786 		asm("movdqa %%xmm5, %0" : "=m"(*data));
787 		break;
788 	case 6:
789 		asm("movdqa %%xmm6, %0" : "=m"(*data));
790 		break;
791 	case 7:
792 		asm("movdqa %%xmm7, %0" : "=m"(*data));
793 		break;
794 	default:
795 		BUG();
796 	}
797 }
798 
799 static inline void write_sse_reg(int reg, const sse128_t *data)
800 {
801 	switch (reg) {
802 	case 0:
803 		asm("movdqa %0, %%xmm0" : : "m"(*data));
804 		break;
805 	case 1:
806 		asm("movdqa %0, %%xmm1" : : "m"(*data));
807 		break;
808 	case 2:
809 		asm("movdqa %0, %%xmm2" : : "m"(*data));
810 		break;
811 	case 3:
812 		asm("movdqa %0, %%xmm3" : : "m"(*data));
813 		break;
814 	case 4:
815 		asm("movdqa %0, %%xmm4" : : "m"(*data));
816 		break;
817 	case 5:
818 		asm("movdqa %0, %%xmm5" : : "m"(*data));
819 		break;
820 	case 6:
821 		asm("movdqa %0, %%xmm6" : : "m"(*data));
822 		break;
823 	case 7:
824 		asm("movdqa %0, %%xmm7" : : "m"(*data));
825 		break;
826 	default:
827 		BUG();
828 	}
829 }
830 
831 static inline void cpu_relax(void)
832 {
833 	asm volatile("rep; nop" ::: "memory");
834 }
835 
836 static inline void udelay(unsigned long usec)
837 {
838 	uint64_t start, now, cycles;
839 
840 	GUEST_ASSERT(guest_tsc_khz);
841 	cycles = guest_tsc_khz / 1000 * usec;
842 
843 	/*
844 	 * Deliberately don't PAUSE, a.k.a. cpu_relax(), so that the delay is
845 	 * as accurate as possible, e.g. doesn't trigger PAUSE-Loop VM-Exits.
846 	 */
847 	start = rdtsc();
848 	do {
849 		now = rdtsc();
850 	} while (now - start < cycles);
851 }
852 
853 #define ud2()			\
854 	__asm__ __volatile__(	\
855 		"ud2\n"	\
856 		)
857 
858 #define hlt()			\
859 	__asm__ __volatile__(	\
860 		"hlt\n"	\
861 		)
862 
863 struct kvm_x86_state *vcpu_save_state(struct kvm_vcpu *vcpu);
864 void vcpu_load_state(struct kvm_vcpu *vcpu, struct kvm_x86_state *state);
865 void kvm_x86_state_cleanup(struct kvm_x86_state *state);
866 
867 const struct kvm_msr_list *kvm_get_msr_index_list(void);
868 const struct kvm_msr_list *kvm_get_feature_msr_index_list(void);
869 bool kvm_msr_is_in_save_restore_list(uint32_t msr_index);
870 uint64_t kvm_get_feature_msr(uint64_t msr_index);
871 
872 static inline void vcpu_msrs_get(struct kvm_vcpu *vcpu,
873 				 struct kvm_msrs *msrs)
874 {
875 	int r = __vcpu_ioctl(vcpu, KVM_GET_MSRS, msrs);
876 
877 	TEST_ASSERT(r == msrs->nmsrs,
878 		    "KVM_GET_MSRS failed, r: %i (failed on MSR %x)",
879 		    r, r < 0 || r >= msrs->nmsrs ? -1 : msrs->entries[r].index);
880 }
881 static inline void vcpu_msrs_set(struct kvm_vcpu *vcpu, struct kvm_msrs *msrs)
882 {
883 	int r = __vcpu_ioctl(vcpu, KVM_SET_MSRS, msrs);
884 
885 	TEST_ASSERT(r == msrs->nmsrs,
886 		    "KVM_SET_MSRS failed, r: %i (failed on MSR %x)",
887 		    r, r < 0 || r >= msrs->nmsrs ? -1 : msrs->entries[r].index);
888 }
889 static inline void vcpu_debugregs_get(struct kvm_vcpu *vcpu,
890 				      struct kvm_debugregs *debugregs)
891 {
892 	vcpu_ioctl(vcpu, KVM_GET_DEBUGREGS, debugregs);
893 }
894 static inline void vcpu_debugregs_set(struct kvm_vcpu *vcpu,
895 				      struct kvm_debugregs *debugregs)
896 {
897 	vcpu_ioctl(vcpu, KVM_SET_DEBUGREGS, debugregs);
898 }
899 static inline void vcpu_xsave_get(struct kvm_vcpu *vcpu,
900 				  struct kvm_xsave *xsave)
901 {
902 	vcpu_ioctl(vcpu, KVM_GET_XSAVE, xsave);
903 }
904 static inline void vcpu_xsave2_get(struct kvm_vcpu *vcpu,
905 				   struct kvm_xsave *xsave)
906 {
907 	vcpu_ioctl(vcpu, KVM_GET_XSAVE2, xsave);
908 }
909 static inline void vcpu_xsave_set(struct kvm_vcpu *vcpu,
910 				  struct kvm_xsave *xsave)
911 {
912 	vcpu_ioctl(vcpu, KVM_SET_XSAVE, xsave);
913 }
914 static inline void vcpu_xcrs_get(struct kvm_vcpu *vcpu,
915 				 struct kvm_xcrs *xcrs)
916 {
917 	vcpu_ioctl(vcpu, KVM_GET_XCRS, xcrs);
918 }
919 static inline void vcpu_xcrs_set(struct kvm_vcpu *vcpu, struct kvm_xcrs *xcrs)
920 {
921 	vcpu_ioctl(vcpu, KVM_SET_XCRS, xcrs);
922 }
923 
924 const struct kvm_cpuid_entry2 *get_cpuid_entry(const struct kvm_cpuid2 *cpuid,
925 					       uint32_t function, uint32_t index);
926 const struct kvm_cpuid2 *kvm_get_supported_cpuid(void);
927 
928 static inline uint32_t kvm_cpu_fms(void)
929 {
930 	return get_cpuid_entry(kvm_get_supported_cpuid(), 0x1, 0)->eax;
931 }
932 
933 static inline uint32_t kvm_cpu_family(void)
934 {
935 	return x86_family(kvm_cpu_fms());
936 }
937 
938 static inline uint32_t kvm_cpu_model(void)
939 {
940 	return x86_model(kvm_cpu_fms());
941 }
942 
943 bool kvm_cpuid_has(const struct kvm_cpuid2 *cpuid,
944 		   struct kvm_x86_cpu_feature feature);
945 
946 static inline bool kvm_cpu_has(struct kvm_x86_cpu_feature feature)
947 {
948 	return kvm_cpuid_has(kvm_get_supported_cpuid(), feature);
949 }
950 
951 uint32_t kvm_cpuid_property(const struct kvm_cpuid2 *cpuid,
952 			    struct kvm_x86_cpu_property property);
953 
954 static inline uint32_t kvm_cpu_property(struct kvm_x86_cpu_property property)
955 {
956 	return kvm_cpuid_property(kvm_get_supported_cpuid(), property);
957 }
958 
959 static __always_inline bool kvm_cpu_has_p(struct kvm_x86_cpu_property property)
960 {
961 	uint32_t max_leaf;
962 
963 	switch (property.function & 0xc0000000) {
964 	case 0:
965 		max_leaf = kvm_cpu_property(X86_PROPERTY_MAX_BASIC_LEAF);
966 		break;
967 	case 0x40000000:
968 		max_leaf = kvm_cpu_property(X86_PROPERTY_MAX_KVM_LEAF);
969 		break;
970 	case 0x80000000:
971 		max_leaf = kvm_cpu_property(X86_PROPERTY_MAX_EXT_LEAF);
972 		break;
973 	case 0xc0000000:
974 		max_leaf = kvm_cpu_property(X86_PROPERTY_MAX_CENTAUR_LEAF);
975 	}
976 	return max_leaf >= property.function;
977 }
978 
979 static inline bool kvm_pmu_has(struct kvm_x86_pmu_feature feature)
980 {
981 	uint32_t nr_bits;
982 
983 	if (feature.f.reg == KVM_CPUID_EBX) {
984 		nr_bits = kvm_cpu_property(X86_PROPERTY_PMU_EBX_BIT_VECTOR_LENGTH);
985 		return nr_bits > feature.f.bit && !kvm_cpu_has(feature.f);
986 	}
987 
988 	TEST_ASSERT_EQ(feature.f.reg, KVM_CPUID_ECX);
989 	nr_bits = kvm_cpu_property(X86_PROPERTY_PMU_NR_FIXED_COUNTERS);
990 	return nr_bits > feature.f.bit || kvm_cpu_has(feature.f);
991 }
992 
993 static __always_inline uint64_t kvm_cpu_supported_xcr0(void)
994 {
995 	if (!kvm_cpu_has_p(X86_PROPERTY_SUPPORTED_XCR0_LO))
996 		return 0;
997 
998 	return kvm_cpu_property(X86_PROPERTY_SUPPORTED_XCR0_LO) |
999 	       ((uint64_t)kvm_cpu_property(X86_PROPERTY_SUPPORTED_XCR0_HI) << 32);
1000 }
1001 
1002 static inline size_t kvm_cpuid2_size(int nr_entries)
1003 {
1004 	return sizeof(struct kvm_cpuid2) +
1005 	       sizeof(struct kvm_cpuid_entry2) * nr_entries;
1006 }
1007 
1008 /*
1009  * Allocate a "struct kvm_cpuid2* instance, with the 0-length arrary of
1010  * entries sized to hold @nr_entries.  The caller is responsible for freeing
1011  * the struct.
1012  */
1013 static inline struct kvm_cpuid2 *allocate_kvm_cpuid2(int nr_entries)
1014 {
1015 	struct kvm_cpuid2 *cpuid;
1016 
1017 	cpuid = malloc(kvm_cpuid2_size(nr_entries));
1018 	TEST_ASSERT(cpuid, "-ENOMEM when allocating kvm_cpuid2");
1019 
1020 	cpuid->nent = nr_entries;
1021 
1022 	return cpuid;
1023 }
1024 
1025 void vcpu_init_cpuid(struct kvm_vcpu *vcpu, const struct kvm_cpuid2 *cpuid);
1026 
1027 static inline void vcpu_get_cpuid(struct kvm_vcpu *vcpu)
1028 {
1029 	vcpu_ioctl(vcpu, KVM_GET_CPUID2, vcpu->cpuid);
1030 }
1031 
1032 static inline struct kvm_cpuid_entry2 *__vcpu_get_cpuid_entry(struct kvm_vcpu *vcpu,
1033 							      uint32_t function,
1034 							      uint32_t index)
1035 {
1036 	TEST_ASSERT(vcpu->cpuid, "Must do vcpu_init_cpuid() first (or equivalent)");
1037 
1038 	vcpu_get_cpuid(vcpu);
1039 
1040 	return (struct kvm_cpuid_entry2 *)get_cpuid_entry(vcpu->cpuid,
1041 							  function, index);
1042 }
1043 
1044 static inline struct kvm_cpuid_entry2 *vcpu_get_cpuid_entry(struct kvm_vcpu *vcpu,
1045 							    uint32_t function)
1046 {
1047 	return __vcpu_get_cpuid_entry(vcpu, function, 0);
1048 }
1049 
1050 static inline int __vcpu_set_cpuid(struct kvm_vcpu *vcpu)
1051 {
1052 	int r;
1053 
1054 	TEST_ASSERT(vcpu->cpuid, "Must do vcpu_init_cpuid() first");
1055 	r = __vcpu_ioctl(vcpu, KVM_SET_CPUID2, vcpu->cpuid);
1056 	if (r)
1057 		return r;
1058 
1059 	/* On success, refresh the cache to pick up adjustments made by KVM. */
1060 	vcpu_get_cpuid(vcpu);
1061 	return 0;
1062 }
1063 
1064 static inline void vcpu_set_cpuid(struct kvm_vcpu *vcpu)
1065 {
1066 	TEST_ASSERT(vcpu->cpuid, "Must do vcpu_init_cpuid() first");
1067 	vcpu_ioctl(vcpu, KVM_SET_CPUID2, vcpu->cpuid);
1068 
1069 	/* Refresh the cache to pick up adjustments made by KVM. */
1070 	vcpu_get_cpuid(vcpu);
1071 }
1072 
1073 void vcpu_set_cpuid_property(struct kvm_vcpu *vcpu,
1074 			     struct kvm_x86_cpu_property property,
1075 			     uint32_t value);
1076 void vcpu_set_cpuid_maxphyaddr(struct kvm_vcpu *vcpu, uint8_t maxphyaddr);
1077 
1078 void vcpu_clear_cpuid_entry(struct kvm_vcpu *vcpu, uint32_t function);
1079 
1080 static inline bool vcpu_cpuid_has(struct kvm_vcpu *vcpu,
1081 				  struct kvm_x86_cpu_feature feature)
1082 {
1083 	struct kvm_cpuid_entry2 *entry;
1084 
1085 	entry = __vcpu_get_cpuid_entry(vcpu, feature.function, feature.index);
1086 	return *((&entry->eax) + feature.reg) & BIT(feature.bit);
1087 }
1088 
1089 void vcpu_set_or_clear_cpuid_feature(struct kvm_vcpu *vcpu,
1090 				     struct kvm_x86_cpu_feature feature,
1091 				     bool set);
1092 
1093 static inline void vcpu_set_cpuid_feature(struct kvm_vcpu *vcpu,
1094 					  struct kvm_x86_cpu_feature feature)
1095 {
1096 	vcpu_set_or_clear_cpuid_feature(vcpu, feature, true);
1097 
1098 }
1099 
1100 static inline void vcpu_clear_cpuid_feature(struct kvm_vcpu *vcpu,
1101 					    struct kvm_x86_cpu_feature feature)
1102 {
1103 	vcpu_set_or_clear_cpuid_feature(vcpu, feature, false);
1104 }
1105 
1106 uint64_t vcpu_get_msr(struct kvm_vcpu *vcpu, uint64_t msr_index);
1107 int _vcpu_set_msr(struct kvm_vcpu *vcpu, uint64_t msr_index, uint64_t msr_value);
1108 
1109 /*
1110  * Assert on an MSR access(es) and pretty print the MSR name when possible.
1111  * Note, the caller provides the stringified name so that the name of macro is
1112  * printed, not the value the macro resolves to (due to macro expansion).
1113  */
1114 #define TEST_ASSERT_MSR(cond, fmt, msr, str, args...)				\
1115 do {										\
1116 	if (__builtin_constant_p(msr)) {					\
1117 		TEST_ASSERT(cond, fmt, str, args);				\
1118 	} else if (!(cond)) {							\
1119 		char buf[16];							\
1120 										\
1121 		snprintf(buf, sizeof(buf), "MSR 0x%x", msr);			\
1122 		TEST_ASSERT(cond, fmt, buf, args);				\
1123 	}									\
1124 } while (0)
1125 
1126 /*
1127  * Returns true if KVM should return the last written value when reading an MSR
1128  * from userspace, e.g. the MSR isn't a command MSR, doesn't emulate state that
1129  * is changing, etc.  This is NOT an exhaustive list!  The intent is to filter
1130  * out MSRs that are not durable _and_ that a selftest wants to write.
1131  */
1132 static inline bool is_durable_msr(uint32_t msr)
1133 {
1134 	return msr != MSR_IA32_TSC;
1135 }
1136 
1137 #define vcpu_set_msr(vcpu, msr, val)							\
1138 do {											\
1139 	uint64_t r, v = val;								\
1140 											\
1141 	TEST_ASSERT_MSR(_vcpu_set_msr(vcpu, msr, v) == 1,				\
1142 			"KVM_SET_MSRS failed on %s, value = 0x%lx", msr, #msr, v);	\
1143 	if (!is_durable_msr(msr))							\
1144 		break;									\
1145 	r = vcpu_get_msr(vcpu, msr);							\
1146 	TEST_ASSERT_MSR(r == v, "Set %s to '0x%lx', got back '0x%lx'", msr, #msr, v, r);\
1147 } while (0)
1148 
1149 void kvm_get_cpu_address_width(unsigned int *pa_bits, unsigned int *va_bits);
1150 void kvm_init_vm_address_properties(struct kvm_vm *vm);
1151 bool vm_is_unrestricted_guest(struct kvm_vm *vm);
1152 
1153 struct ex_regs {
1154 	uint64_t rax, rcx, rdx, rbx;
1155 	uint64_t rbp, rsi, rdi;
1156 	uint64_t r8, r9, r10, r11;
1157 	uint64_t r12, r13, r14, r15;
1158 	uint64_t vector;
1159 	uint64_t error_code;
1160 	uint64_t rip;
1161 	uint64_t cs;
1162 	uint64_t rflags;
1163 };
1164 
1165 struct idt_entry {
1166 	uint16_t offset0;
1167 	uint16_t selector;
1168 	uint16_t ist : 3;
1169 	uint16_t : 5;
1170 	uint16_t type : 4;
1171 	uint16_t : 1;
1172 	uint16_t dpl : 2;
1173 	uint16_t p : 1;
1174 	uint16_t offset1;
1175 	uint32_t offset2; uint32_t reserved;
1176 };
1177 
1178 void vm_install_exception_handler(struct kvm_vm *vm, int vector,
1179 			void (*handler)(struct ex_regs *));
1180 
1181 /* If a toddler were to say "abracadabra". */
1182 #define KVM_EXCEPTION_MAGIC 0xabacadabaULL
1183 
1184 /*
1185  * KVM selftest exception fixup uses registers to coordinate with the exception
1186  * handler, versus the kernel's in-memory tables and KVM-Unit-Tests's in-memory
1187  * per-CPU data.  Using only registers avoids having to map memory into the
1188  * guest, doesn't require a valid, stable GS.base, and reduces the risk of
1189  * for recursive faults when accessing memory in the handler.  The downside to
1190  * using registers is that it restricts what registers can be used by the actual
1191  * instruction.  But, selftests are 64-bit only, making register* pressure a
1192  * minor concern.  Use r9-r11 as they are volatile, i.e. don't need to be saved
1193  * by the callee, and except for r11 are not implicit parameters to any
1194  * instructions.  Ideally, fixup would use r8-r10 and thus avoid implicit
1195  * parameters entirely, but Hyper-V's hypercall ABI uses r8 and testing Hyper-V
1196  * is higher priority than testing non-faulting SYSCALL/SYSRET.
1197  *
1198  * Note, the fixup handler deliberately does not handle #DE, i.e. the vector
1199  * is guaranteed to be non-zero on fault.
1200  *
1201  * REGISTER INPUTS:
1202  * r9  = MAGIC
1203  * r10 = RIP
1204  * r11 = new RIP on fault
1205  *
1206  * REGISTER OUTPUTS:
1207  * r9  = exception vector (non-zero)
1208  * r10 = error code
1209  */
1210 #define __KVM_ASM_SAFE(insn, fep)				\
1211 	"mov $" __stringify(KVM_EXCEPTION_MAGIC) ", %%r9\n\t"	\
1212 	"lea 1f(%%rip), %%r10\n\t"				\
1213 	"lea 2f(%%rip), %%r11\n\t"				\
1214 	fep "1: " insn "\n\t"					\
1215 	"xor %%r9, %%r9\n\t"					\
1216 	"2:\n\t"						\
1217 	"mov  %%r9b, %[vector]\n\t"				\
1218 	"mov  %%r10, %[error_code]\n\t"
1219 
1220 #define KVM_ASM_SAFE(insn) __KVM_ASM_SAFE(insn, "")
1221 #define KVM_ASM_SAFE_FEP(insn) __KVM_ASM_SAFE(insn, KVM_FEP)
1222 
1223 #define KVM_ASM_SAFE_OUTPUTS(v, ec)	[vector] "=qm"(v), [error_code] "=rm"(ec)
1224 #define KVM_ASM_SAFE_CLOBBERS	"r9", "r10", "r11"
1225 
1226 #define kvm_asm_safe(insn, inputs...)					\
1227 ({									\
1228 	uint64_t ign_error_code;					\
1229 	uint8_t vector;							\
1230 									\
1231 	asm volatile(KVM_ASM_SAFE(insn)					\
1232 		     : KVM_ASM_SAFE_OUTPUTS(vector, ign_error_code)	\
1233 		     : inputs						\
1234 		     : KVM_ASM_SAFE_CLOBBERS);				\
1235 	vector;								\
1236 })
1237 
1238 #define kvm_asm_safe_ec(insn, error_code, inputs...)			\
1239 ({									\
1240 	uint8_t vector;							\
1241 									\
1242 	asm volatile(KVM_ASM_SAFE(insn)					\
1243 		     : KVM_ASM_SAFE_OUTPUTS(vector, error_code)		\
1244 		     : inputs						\
1245 		     : KVM_ASM_SAFE_CLOBBERS);				\
1246 	vector;								\
1247 })
1248 
1249 #define kvm_asm_safe_fep(insn, inputs...)				\
1250 ({									\
1251 	uint64_t ign_error_code;					\
1252 	uint8_t vector;							\
1253 									\
1254 	asm volatile(KVM_ASM_SAFE(insn)					\
1255 		     : KVM_ASM_SAFE_OUTPUTS(vector, ign_error_code)	\
1256 		     : inputs						\
1257 		     : KVM_ASM_SAFE_CLOBBERS);				\
1258 	vector;								\
1259 })
1260 
1261 #define kvm_asm_safe_ec_fep(insn, error_code, inputs...)		\
1262 ({									\
1263 	uint8_t vector;							\
1264 									\
1265 	asm volatile(KVM_ASM_SAFE_FEP(insn)				\
1266 		     : KVM_ASM_SAFE_OUTPUTS(vector, error_code)		\
1267 		     : inputs						\
1268 		     : KVM_ASM_SAFE_CLOBBERS);				\
1269 	vector;								\
1270 })
1271 
1272 #define BUILD_READ_U64_SAFE_HELPER(insn, _fep, _FEP)			\
1273 static inline uint8_t insn##_safe ##_fep(uint32_t idx, uint64_t *val)	\
1274 {									\
1275 	uint64_t error_code;						\
1276 	uint8_t vector;							\
1277 	uint32_t a, d;							\
1278 									\
1279 	asm volatile(KVM_ASM_SAFE##_FEP(#insn)				\
1280 		     : "=a"(a), "=d"(d),				\
1281 		       KVM_ASM_SAFE_OUTPUTS(vector, error_code)		\
1282 		     : "c"(idx)						\
1283 		     : KVM_ASM_SAFE_CLOBBERS);				\
1284 									\
1285 	*val = (uint64_t)a | ((uint64_t)d << 32);			\
1286 	return vector;							\
1287 }
1288 
1289 /*
1290  * Generate {insn}_safe() and {insn}_safe_fep() helpers for instructions that
1291  * use ECX as in input index, and EDX:EAX as a 64-bit output.
1292  */
1293 #define BUILD_READ_U64_SAFE_HELPERS(insn)				\
1294 	BUILD_READ_U64_SAFE_HELPER(insn, , )				\
1295 	BUILD_READ_U64_SAFE_HELPER(insn, _fep, _FEP)			\
1296 
1297 BUILD_READ_U64_SAFE_HELPERS(rdmsr)
1298 BUILD_READ_U64_SAFE_HELPERS(rdpmc)
1299 BUILD_READ_U64_SAFE_HELPERS(xgetbv)
1300 
1301 static inline uint8_t wrmsr_safe(uint32_t msr, uint64_t val)
1302 {
1303 	return kvm_asm_safe("wrmsr", "a"(val & -1u), "d"(val >> 32), "c"(msr));
1304 }
1305 
1306 static inline uint8_t xsetbv_safe(uint32_t index, uint64_t value)
1307 {
1308 	u32 eax = value;
1309 	u32 edx = value >> 32;
1310 
1311 	return kvm_asm_safe("xsetbv", "a" (eax), "d" (edx), "c" (index));
1312 }
1313 
1314 bool kvm_is_tdp_enabled(void);
1315 
1316 static inline bool kvm_is_pmu_enabled(void)
1317 {
1318 	return get_kvm_param_bool("enable_pmu");
1319 }
1320 
1321 static inline bool kvm_is_forced_emulation_enabled(void)
1322 {
1323 	return !!get_kvm_param_integer("force_emulation_prefix");
1324 }
1325 
1326 uint64_t *__vm_get_page_table_entry(struct kvm_vm *vm, uint64_t vaddr,
1327 				    int *level);
1328 uint64_t *vm_get_page_table_entry(struct kvm_vm *vm, uint64_t vaddr);
1329 
1330 uint64_t kvm_hypercall(uint64_t nr, uint64_t a0, uint64_t a1, uint64_t a2,
1331 		       uint64_t a3);
1332 uint64_t __xen_hypercall(uint64_t nr, uint64_t a0, void *a1);
1333 void xen_hypercall(uint64_t nr, uint64_t a0, void *a1);
1334 
1335 static inline uint64_t __kvm_hypercall_map_gpa_range(uint64_t gpa,
1336 						     uint64_t size, uint64_t flags)
1337 {
1338 	return kvm_hypercall(KVM_HC_MAP_GPA_RANGE, gpa, size >> PAGE_SHIFT, flags, 0);
1339 }
1340 
1341 static inline void kvm_hypercall_map_gpa_range(uint64_t gpa, uint64_t size,
1342 					       uint64_t flags)
1343 {
1344 	uint64_t ret = __kvm_hypercall_map_gpa_range(gpa, size, flags);
1345 
1346 	GUEST_ASSERT(!ret);
1347 }
1348 
1349 /*
1350  * Execute HLT in an STI interrupt shadow to ensure that a pending IRQ that's
1351  * intended to be a wake event arrives *after* HLT is executed.  Modern CPUs,
1352  * except for a few oddballs that KVM is unlikely to run on, block IRQs for one
1353  * instruction after STI, *if* RFLAGS.IF=0 before STI.  Note, Intel CPUs may
1354  * block other events beyond regular IRQs, e.g. may block NMIs and SMIs too.
1355  */
1356 static inline void safe_halt(void)
1357 {
1358 	asm volatile("sti; hlt");
1359 }
1360 
1361 /*
1362  * Enable interrupts and ensure that interrupts are evaluated upon return from
1363  * this function, i.e. execute a nop to consume the STi interrupt shadow.
1364  */
1365 static inline void sti_nop(void)
1366 {
1367 	asm volatile ("sti; nop");
1368 }
1369 
1370 /*
1371  * Enable interrupts for one instruction (nop), to allow the CPU to process all
1372  * interrupts that are already pending.
1373  */
1374 static inline void sti_nop_cli(void)
1375 {
1376 	asm volatile ("sti; nop; cli");
1377 }
1378 
1379 static inline void sti(void)
1380 {
1381 	asm volatile("sti");
1382 }
1383 
1384 static inline void cli(void)
1385 {
1386 	asm volatile ("cli");
1387 }
1388 
1389 void __vm_xsave_require_permission(uint64_t xfeature, const char *name);
1390 
1391 #define vm_xsave_require_permission(xfeature)	\
1392 	__vm_xsave_require_permission(xfeature, #xfeature)
1393 
1394 enum pg_level {
1395 	PG_LEVEL_NONE,
1396 	PG_LEVEL_4K,
1397 	PG_LEVEL_2M,
1398 	PG_LEVEL_1G,
1399 	PG_LEVEL_512G,
1400 	PG_LEVEL_NUM
1401 };
1402 
1403 #define PG_LEVEL_SHIFT(_level) ((_level - 1) * 9 + 12)
1404 #define PG_LEVEL_SIZE(_level) (1ull << PG_LEVEL_SHIFT(_level))
1405 
1406 #define PG_SIZE_4K PG_LEVEL_SIZE(PG_LEVEL_4K)
1407 #define PG_SIZE_2M PG_LEVEL_SIZE(PG_LEVEL_2M)
1408 #define PG_SIZE_1G PG_LEVEL_SIZE(PG_LEVEL_1G)
1409 
1410 void __virt_pg_map(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr, int level);
1411 void virt_map_level(struct kvm_vm *vm, uint64_t vaddr, uint64_t paddr,
1412 		    uint64_t nr_bytes, int level);
1413 
1414 /*
1415  * Basic CPU control in CR0
1416  */
1417 #define X86_CR0_PE          (1UL<<0) /* Protection Enable */
1418 #define X86_CR0_MP          (1UL<<1) /* Monitor Coprocessor */
1419 #define X86_CR0_EM          (1UL<<2) /* Emulation */
1420 #define X86_CR0_TS          (1UL<<3) /* Task Switched */
1421 #define X86_CR0_ET          (1UL<<4) /* Extension Type */
1422 #define X86_CR0_NE          (1UL<<5) /* Numeric Error */
1423 #define X86_CR0_WP          (1UL<<16) /* Write Protect */
1424 #define X86_CR0_AM          (1UL<<18) /* Alignment Mask */
1425 #define X86_CR0_NW          (1UL<<29) /* Not Write-through */
1426 #define X86_CR0_CD          (1UL<<30) /* Cache Disable */
1427 #define X86_CR0_PG          (1UL<<31) /* Paging */
1428 
1429 #define PFERR_PRESENT_BIT 0
1430 #define PFERR_WRITE_BIT 1
1431 #define PFERR_USER_BIT 2
1432 #define PFERR_RSVD_BIT 3
1433 #define PFERR_FETCH_BIT 4
1434 #define PFERR_PK_BIT 5
1435 #define PFERR_SGX_BIT 15
1436 #define PFERR_GUEST_FINAL_BIT 32
1437 #define PFERR_GUEST_PAGE_BIT 33
1438 #define PFERR_IMPLICIT_ACCESS_BIT 48
1439 
1440 #define PFERR_PRESENT_MASK	BIT(PFERR_PRESENT_BIT)
1441 #define PFERR_WRITE_MASK	BIT(PFERR_WRITE_BIT)
1442 #define PFERR_USER_MASK		BIT(PFERR_USER_BIT)
1443 #define PFERR_RSVD_MASK		BIT(PFERR_RSVD_BIT)
1444 #define PFERR_FETCH_MASK	BIT(PFERR_FETCH_BIT)
1445 #define PFERR_PK_MASK		BIT(PFERR_PK_BIT)
1446 #define PFERR_SGX_MASK		BIT(PFERR_SGX_BIT)
1447 #define PFERR_GUEST_FINAL_MASK	BIT_ULL(PFERR_GUEST_FINAL_BIT)
1448 #define PFERR_GUEST_PAGE_MASK	BIT_ULL(PFERR_GUEST_PAGE_BIT)
1449 #define PFERR_IMPLICIT_ACCESS	BIT_ULL(PFERR_IMPLICIT_ACCESS_BIT)
1450 
1451 bool sys_clocksource_is_based_on_tsc(void);
1452 
1453 #endif /* SELFTEST_KVM_PROCESSOR_H */
1454