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