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