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