xref: /kvm-unit-tests/x86/vmx.c (revision 4363f1d9a646a5c7ea673bee8fc33ca6f2cddbd8)
1 /*
2  * x86/vmx.c : Framework for testing nested virtualization
3  *	This is a framework to test nested VMX for KVM, which
4  * 	started as a project of GSoC 2013. All test cases should
5  *	be located in x86/vmx_tests.c and framework related
6  *	functions should be in this file.
7  *
8  * How to write test cases?
9  *	Add callbacks of test suite in variant "vmx_tests". You can
10  *	write:
11  *		1. init function used for initializing test suite
12  *		2. main function for codes running in L2 guest,
13  *		3. exit_handler to handle vmexit of L2 to L1
14  *		4. syscall handler to handle L2 syscall vmexit
15  *		5. vmenter fail handler to handle direct failure of vmenter
16  *		6. guest_regs is loaded when vmenter and saved when
17  *			vmexit, you can read and set it in exit_handler
18  *	If no special function is needed for a test suite, use
19  *	coressponding basic_* functions as callback. More handlers
20  *	can be added to "vmx_tests", see details of "struct vmx_test"
21  *	and function test_run().
22  *
23  * Currently, vmx test framework only set up one VCPU and one
24  * concurrent guest test environment with same paging for L2 and
25  * L1. For usage of EPT, only 1:1 mapped paging is used from VFN
26  * to PFN.
27  *
28  * Author : Arthur Chunqi Li <yzt356@gmail.com>
29  */
30 
31 #include "libcflat.h"
32 #include "processor.h"
33 #include "alloc_page.h"
34 #include "vm.h"
35 #include "desc.h"
36 #include "vmx.h"
37 #include "msr.h"
38 #include "smp.h"
39 
40 u64 *vmxon_region;
41 struct vmcs *vmcs_root;
42 u32 vpid_cnt;
43 void *guest_stack, *guest_syscall_stack;
44 u32 ctrl_pin, ctrl_enter, ctrl_exit, ctrl_cpu[2];
45 struct regs regs;
46 
47 struct vmx_test *current;
48 
49 #define MAX_TEST_TEARDOWN_STEPS 10
50 
51 struct test_teardown_step {
52 	test_teardown_func func;
53 	void *data;
54 };
55 
56 static int teardown_count;
57 static struct test_teardown_step teardown_steps[MAX_TEST_TEARDOWN_STEPS];
58 
59 static test_guest_func v2_guest_main;
60 
61 u64 hypercall_field;
62 bool launched;
63 static int matched;
64 static int guest_finished;
65 static int in_guest;
66 
67 union vmx_basic basic;
68 union vmx_ctrl_msr ctrl_pin_rev;
69 union vmx_ctrl_msr ctrl_cpu_rev[2];
70 union vmx_ctrl_msr ctrl_exit_rev;
71 union vmx_ctrl_msr ctrl_enter_rev;
72 union vmx_ept_vpid  ept_vpid;
73 
74 extern struct descriptor_table_ptr gdt64_desc;
75 extern struct descriptor_table_ptr idt_descr;
76 extern struct descriptor_table_ptr tss_descr;
77 extern void *vmx_return;
78 extern void *entry_sysenter;
79 extern void *guest_entry;
80 
81 static volatile u32 stage;
82 
83 static jmp_buf abort_target;
84 
85 struct vmcs_field {
86 	u64 mask;
87 	u64 encoding;
88 };
89 
90 #define MASK(_bits) GENMASK_ULL((_bits) - 1, 0)
91 #define MASK_NATURAL MASK(sizeof(unsigned long) * 8)
92 
93 static struct vmcs_field vmcs_fields[] = {
94 	{ MASK(16), VPID },
95 	{ MASK(16), PINV },
96 	{ MASK(16), EPTP_IDX },
97 
98 	{ MASK(16), GUEST_SEL_ES },
99 	{ MASK(16), GUEST_SEL_CS },
100 	{ MASK(16), GUEST_SEL_SS },
101 	{ MASK(16), GUEST_SEL_DS },
102 	{ MASK(16), GUEST_SEL_FS },
103 	{ MASK(16), GUEST_SEL_GS },
104 	{ MASK(16), GUEST_SEL_LDTR },
105 	{ MASK(16), GUEST_SEL_TR },
106 	{ MASK(16), GUEST_INT_STATUS },
107 
108 	{ MASK(16), HOST_SEL_ES },
109 	{ MASK(16), HOST_SEL_CS },
110 	{ MASK(16), HOST_SEL_SS },
111 	{ MASK(16), HOST_SEL_DS },
112 	{ MASK(16), HOST_SEL_FS },
113 	{ MASK(16), HOST_SEL_GS },
114 	{ MASK(16), HOST_SEL_TR },
115 
116 	{ MASK(64), IO_BITMAP_A },
117 	{ MASK(64), IO_BITMAP_B },
118 	{ MASK(64), MSR_BITMAP },
119 	{ MASK(64), EXIT_MSR_ST_ADDR },
120 	{ MASK(64), EXIT_MSR_LD_ADDR },
121 	{ MASK(64), ENTER_MSR_LD_ADDR },
122 	{ MASK(64), VMCS_EXEC_PTR },
123 	{ MASK(64), TSC_OFFSET },
124 	{ MASK(64), APIC_VIRT_ADDR },
125 	{ MASK(64), APIC_ACCS_ADDR },
126 	{ MASK(64), EPTP },
127 
128 	{ 0 /* read-only */, INFO_PHYS_ADDR },
129 
130 	{ MASK(64), VMCS_LINK_PTR },
131 	{ MASK(64), GUEST_DEBUGCTL },
132 	{ MASK(64), GUEST_EFER },
133 	{ MASK(64), GUEST_PAT },
134 	{ MASK(64), GUEST_PERF_GLOBAL_CTRL },
135 	{ MASK(64), GUEST_PDPTE },
136 
137 	{ MASK(64), HOST_PAT },
138 	{ MASK(64), HOST_EFER },
139 	{ MASK(64), HOST_PERF_GLOBAL_CTRL },
140 
141 	{ MASK(32), PIN_CONTROLS },
142 	{ MASK(32), CPU_EXEC_CTRL0 },
143 	{ MASK(32), EXC_BITMAP },
144 	{ MASK(32), PF_ERROR_MASK },
145 	{ MASK(32), PF_ERROR_MATCH },
146 	{ MASK(32), CR3_TARGET_COUNT },
147 	{ MASK(32), EXI_CONTROLS },
148 	{ MASK(32), EXI_MSR_ST_CNT },
149 	{ MASK(32), EXI_MSR_LD_CNT },
150 	{ MASK(32), ENT_CONTROLS },
151 	{ MASK(32), ENT_MSR_LD_CNT },
152 	{ MASK(32), ENT_INTR_INFO },
153 	{ MASK(32), ENT_INTR_ERROR },
154 	{ MASK(32), ENT_INST_LEN },
155 	{ MASK(32), TPR_THRESHOLD },
156 	{ MASK(32), CPU_EXEC_CTRL1 },
157 
158 	{ 0 /* read-only */, VMX_INST_ERROR },
159 	{ 0 /* read-only */, EXI_REASON },
160 	{ 0 /* read-only */, EXI_INTR_INFO },
161 	{ 0 /* read-only */, EXI_INTR_ERROR },
162 	{ 0 /* read-only */, IDT_VECT_INFO },
163 	{ 0 /* read-only */, IDT_VECT_ERROR },
164 	{ 0 /* read-only */, EXI_INST_LEN },
165 	{ 0 /* read-only */, EXI_INST_INFO },
166 
167 	{ MASK(32), GUEST_LIMIT_ES },
168 	{ MASK(32), GUEST_LIMIT_CS },
169 	{ MASK(32), GUEST_LIMIT_SS },
170 	{ MASK(32), GUEST_LIMIT_DS },
171 	{ MASK(32), GUEST_LIMIT_FS },
172 	{ MASK(32), GUEST_LIMIT_GS },
173 	{ MASK(32), GUEST_LIMIT_LDTR },
174 	{ MASK(32), GUEST_LIMIT_TR },
175 	{ MASK(32), GUEST_LIMIT_GDTR },
176 	{ MASK(32), GUEST_LIMIT_IDTR },
177 	{ 0x1d0ff, GUEST_AR_ES },
178 	{ 0x1f0ff, GUEST_AR_CS },
179 	{ 0x1d0ff, GUEST_AR_SS },
180 	{ 0x1d0ff, GUEST_AR_DS },
181 	{ 0x1d0ff, GUEST_AR_FS },
182 	{ 0x1d0ff, GUEST_AR_GS },
183 	{ 0x1d0ff, GUEST_AR_LDTR },
184 	{ 0x1d0ff, GUEST_AR_TR },
185 	{ MASK(32), GUEST_INTR_STATE },
186 	{ MASK(32), GUEST_ACTV_STATE },
187 	{ MASK(32), GUEST_SMBASE },
188 	{ MASK(32), GUEST_SYSENTER_CS },
189 	{ MASK(32), PREEMPT_TIMER_VALUE },
190 
191 	{ MASK(32), HOST_SYSENTER_CS },
192 
193 	{ MASK_NATURAL, CR0_MASK },
194 	{ MASK_NATURAL, CR4_MASK },
195 	{ MASK_NATURAL, CR0_READ_SHADOW },
196 	{ MASK_NATURAL, CR4_READ_SHADOW },
197 	{ MASK_NATURAL, CR3_TARGET_0 },
198 	{ MASK_NATURAL, CR3_TARGET_1 },
199 	{ MASK_NATURAL, CR3_TARGET_2 },
200 	{ MASK_NATURAL, CR3_TARGET_3 },
201 
202 	{ 0 /* read-only */, EXI_QUALIFICATION },
203 	{ 0 /* read-only */, IO_RCX },
204 	{ 0 /* read-only */, IO_RSI },
205 	{ 0 /* read-only */, IO_RDI },
206 	{ 0 /* read-only */, IO_RIP },
207 	{ 0 /* read-only */, GUEST_LINEAR_ADDRESS },
208 
209 	{ MASK_NATURAL, GUEST_CR0 },
210 	{ MASK_NATURAL, GUEST_CR3 },
211 	{ MASK_NATURAL, GUEST_CR4 },
212 	{ MASK_NATURAL, GUEST_BASE_ES },
213 	{ MASK_NATURAL, GUEST_BASE_CS },
214 	{ MASK_NATURAL, GUEST_BASE_SS },
215 	{ MASK_NATURAL, GUEST_BASE_DS },
216 	{ MASK_NATURAL, GUEST_BASE_FS },
217 	{ MASK_NATURAL, GUEST_BASE_GS },
218 	{ MASK_NATURAL, GUEST_BASE_LDTR },
219 	{ MASK_NATURAL, GUEST_BASE_TR },
220 	{ MASK_NATURAL, GUEST_BASE_GDTR },
221 	{ MASK_NATURAL, GUEST_BASE_IDTR },
222 	{ MASK_NATURAL, GUEST_DR7 },
223 	{ MASK_NATURAL, GUEST_RSP },
224 	{ MASK_NATURAL, GUEST_RIP },
225 	{ MASK_NATURAL, GUEST_RFLAGS },
226 	{ MASK_NATURAL, GUEST_PENDING_DEBUG },
227 	{ MASK_NATURAL, GUEST_SYSENTER_ESP },
228 	{ MASK_NATURAL, GUEST_SYSENTER_EIP },
229 
230 	{ MASK_NATURAL, HOST_CR0 },
231 	{ MASK_NATURAL, HOST_CR3 },
232 	{ MASK_NATURAL, HOST_CR4 },
233 	{ MASK_NATURAL, HOST_BASE_FS },
234 	{ MASK_NATURAL, HOST_BASE_GS },
235 	{ MASK_NATURAL, HOST_BASE_TR },
236 	{ MASK_NATURAL, HOST_BASE_GDTR },
237 	{ MASK_NATURAL, HOST_BASE_IDTR },
238 	{ MASK_NATURAL, HOST_SYSENTER_ESP },
239 	{ MASK_NATURAL, HOST_SYSENTER_EIP },
240 	{ MASK_NATURAL, HOST_RSP },
241 	{ MASK_NATURAL, HOST_RIP },
242 };
243 
244 static inline u64 vmcs_field_value(struct vmcs_field *f, u8 cookie)
245 {
246 	u64 value;
247 
248 	/* Incorporate the cookie and the field encoding into the value. */
249 	value = cookie;
250 	value |= (f->encoding << 8);
251 	value |= 0xdeadbeefull << 32;
252 
253 	return value & f->mask;
254 }
255 
256 static void set_vmcs_field(struct vmcs_field *f, u8 cookie)
257 {
258 	vmcs_write(f->encoding, vmcs_field_value(f, cookie));
259 }
260 
261 static bool check_vmcs_field(struct vmcs_field *f, u8 cookie)
262 {
263 	u64 expected;
264 	u64 actual;
265 	int ret;
266 
267 	ret = vmcs_read_checking(f->encoding, &actual);
268 	assert(!(ret & X86_EFLAGS_CF));
269 	/* Skip VMCS fields that aren't recognized by the CPU */
270 	if (ret & X86_EFLAGS_ZF)
271 		return true;
272 
273 	expected = vmcs_field_value(f, cookie);
274 	actual &= f->mask;
275 
276 	if (expected == actual)
277 		return true;
278 
279 	printf("FAIL: VMWRITE/VMREAD %lx (expected: %lx, actual: %lx)\n",
280 	       f->encoding, (unsigned long) expected, (unsigned long) actual);
281 
282 	return false;
283 }
284 
285 static void set_all_vmcs_fields(u8 cookie)
286 {
287 	int i;
288 
289 	for (i = 0; i < ARRAY_SIZE(vmcs_fields); i++)
290 		set_vmcs_field(&vmcs_fields[i], cookie);
291 }
292 
293 static bool check_all_vmcs_fields(u8 cookie)
294 {
295 	bool pass = true;
296 	int i;
297 
298 	for (i = 0; i < ARRAY_SIZE(vmcs_fields); i++) {
299 		if (!check_vmcs_field(&vmcs_fields[i], cookie))
300 			pass = false;
301 	}
302 
303 	return pass;
304 }
305 
306 void test_vmwrite_vmread(void)
307 {
308 	struct vmcs *vmcs = alloc_page();
309 
310 	memset(vmcs, 0, PAGE_SIZE);
311 	vmcs->revision_id = basic.revision;
312 	assert(!vmcs_clear(vmcs));
313 	assert(!make_vmcs_current(vmcs));
314 
315 	set_all_vmcs_fields(0x42);
316 	report("VMWRITE/VMREAD", check_all_vmcs_fields(0x42));
317 
318 	assert(!vmcs_clear(vmcs));
319 	free_page(vmcs);
320 }
321 
322 void test_vmcs_high(void)
323 {
324 	struct vmcs *vmcs = alloc_page();
325 
326 	memset(vmcs, 0, PAGE_SIZE);
327 	vmcs->revision_id = basic.revision;
328 	assert(!vmcs_clear(vmcs));
329 	assert(!make_vmcs_current(vmcs));
330 
331 	vmcs_write(TSC_OFFSET, 0x0123456789ABCDEFull);
332 	report("VMREAD TSC_OFFSET after VMWRITE TSC_OFFSET",
333 	       vmcs_read(TSC_OFFSET) == 0x0123456789ABCDEFull);
334 	report("VMREAD TSC_OFFSET_HI after VMWRITE TSC_OFFSET",
335 	       vmcs_read(TSC_OFFSET_HI) == 0x01234567ull);
336 	vmcs_write(TSC_OFFSET_HI, 0x76543210ul);
337 	report("VMREAD TSC_OFFSET_HI after VMWRITE TSC_OFFSET_HI",
338 	       vmcs_read(TSC_OFFSET_HI) == 0x76543210ul);
339 	report("VMREAD TSC_OFFSET after VMWRITE TSC_OFFSET_HI",
340 	       vmcs_read(TSC_OFFSET) == 0x7654321089ABCDEFull);
341 
342 	assert(!vmcs_clear(vmcs));
343 	free_page(vmcs);
344 }
345 
346 void test_vmcs_lifecycle(void)
347 {
348 	struct vmcs *vmcs[2] = {};
349 	int i;
350 
351 	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
352 		vmcs[i] = alloc_page();
353 		memset(vmcs[i], 0, PAGE_SIZE);
354 		vmcs[i]->revision_id = basic.revision;
355 	}
356 
357 #define VMPTRLD(_i) do { \
358 	assert(_i < ARRAY_SIZE(vmcs)); \
359 	assert(!make_vmcs_current(vmcs[_i])); \
360 	printf("VMPTRLD VMCS%d\n", (_i)); \
361 } while (0)
362 
363 #define VMCLEAR(_i) do { \
364 	assert(_i < ARRAY_SIZE(vmcs)); \
365 	assert(!vmcs_clear(vmcs[_i])); \
366 	printf("VMCLEAR VMCS%d\n", (_i)); \
367 } while (0)
368 
369 	VMCLEAR(0);
370 	VMPTRLD(0);
371 	set_all_vmcs_fields(0);
372 	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));
373 
374 	VMCLEAR(0);
375 	VMPTRLD(0);
376 	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));
377 
378 	VMCLEAR(1);
379 	report("current:VMCS0 active:[VMCS0]", check_all_vmcs_fields(0));
380 
381 	VMPTRLD(1);
382 	set_all_vmcs_fields(1);
383 	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));
384 
385 	VMPTRLD(0);
386 	report("current:VMCS0 active:[VMCS0,VCMS1]", check_all_vmcs_fields(0));
387 	VMPTRLD(1);
388 	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));
389 	VMPTRLD(1);
390 	report("current:VMCS1 active:[VMCS0,VCMS1]", check_all_vmcs_fields(1));
391 
392 	VMCLEAR(0);
393 	report("current:VMCS1 active:[VCMS1]", check_all_vmcs_fields(1));
394 
395 	/* VMPTRLD should not erase VMWRITEs to the current VMCS */
396 	set_all_vmcs_fields(2);
397 	VMPTRLD(1);
398 	report("current:VMCS1 active:[VCMS1]", check_all_vmcs_fields(2));
399 
400 	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
401 		VMCLEAR(i);
402 		free_page(vmcs[i]);
403 	}
404 
405 #undef VMPTRLD
406 #undef VMCLEAR
407 }
408 
409 void vmx_set_test_stage(u32 s)
410 {
411 	barrier();
412 	stage = s;
413 	barrier();
414 }
415 
416 u32 vmx_get_test_stage(void)
417 {
418 	u32 s;
419 
420 	barrier();
421 	s = stage;
422 	barrier();
423 	return s;
424 }
425 
426 void vmx_inc_test_stage(void)
427 {
428 	barrier();
429 	stage++;
430 	barrier();
431 }
432 
433 /* entry_sysenter */
434 asm(
435 	".align	4, 0x90\n\t"
436 	".globl	entry_sysenter\n\t"
437 	"entry_sysenter:\n\t"
438 	SAVE_GPR
439 	"	and	$0xf, %rax\n\t"
440 	"	mov	%rax, %rdi\n\t"
441 	"	call	syscall_handler\n\t"
442 	LOAD_GPR
443 	"	vmresume\n\t"
444 );
445 
446 static void __attribute__((__used__)) syscall_handler(u64 syscall_no)
447 {
448 	if (current->syscall_handler)
449 		current->syscall_handler(syscall_no);
450 }
451 
452 static const char * const exit_reason_descriptions[] = {
453 	[VMX_EXC_NMI]		= "VMX_EXC_NMI",
454 	[VMX_EXTINT]		= "VMX_EXTINT",
455 	[VMX_TRIPLE_FAULT]	= "VMX_TRIPLE_FAULT",
456 	[VMX_INIT]		= "VMX_INIT",
457 	[VMX_SIPI]		= "VMX_SIPI",
458 	[VMX_SMI_IO]		= "VMX_SMI_IO",
459 	[VMX_SMI_OTHER]		= "VMX_SMI_OTHER",
460 	[VMX_INTR_WINDOW]	= "VMX_INTR_WINDOW",
461 	[VMX_NMI_WINDOW]	= "VMX_NMI_WINDOW",
462 	[VMX_TASK_SWITCH]	= "VMX_TASK_SWITCH",
463 	[VMX_CPUID]		= "VMX_CPUID",
464 	[VMX_GETSEC]		= "VMX_GETSEC",
465 	[VMX_HLT]		= "VMX_HLT",
466 	[VMX_INVD]		= "VMX_INVD",
467 	[VMX_INVLPG]		= "VMX_INVLPG",
468 	[VMX_RDPMC]		= "VMX_RDPMC",
469 	[VMX_RDTSC]		= "VMX_RDTSC",
470 	[VMX_RSM]		= "VMX_RSM",
471 	[VMX_VMCALL]		= "VMX_VMCALL",
472 	[VMX_VMCLEAR]		= "VMX_VMCLEAR",
473 	[VMX_VMLAUNCH]		= "VMX_VMLAUNCH",
474 	[VMX_VMPTRLD]		= "VMX_VMPTRLD",
475 	[VMX_VMPTRST]		= "VMX_VMPTRST",
476 	[VMX_VMREAD]		= "VMX_VMREAD",
477 	[VMX_VMRESUME]		= "VMX_VMRESUME",
478 	[VMX_VMWRITE]		= "VMX_VMWRITE",
479 	[VMX_VMXOFF]		= "VMX_VMXOFF",
480 	[VMX_VMXON]		= "VMX_VMXON",
481 	[VMX_CR]		= "VMX_CR",
482 	[VMX_DR]		= "VMX_DR",
483 	[VMX_IO]		= "VMX_IO",
484 	[VMX_RDMSR]		= "VMX_RDMSR",
485 	[VMX_WRMSR]		= "VMX_WRMSR",
486 	[VMX_FAIL_STATE]	= "VMX_FAIL_STATE",
487 	[VMX_FAIL_MSR]		= "VMX_FAIL_MSR",
488 	[VMX_MWAIT]		= "VMX_MWAIT",
489 	[VMX_MTF]		= "VMX_MTF",
490 	[VMX_MONITOR]		= "VMX_MONITOR",
491 	[VMX_PAUSE]		= "VMX_PAUSE",
492 	[VMX_FAIL_MCHECK]	= "VMX_FAIL_MCHECK",
493 	[VMX_TPR_THRESHOLD]	= "VMX_TPR_THRESHOLD",
494 	[VMX_APIC_ACCESS]	= "VMX_APIC_ACCESS",
495 	[VMX_GDTR_IDTR]		= "VMX_GDTR_IDTR",
496 	[VMX_LDTR_TR]		= "VMX_LDTR_TR",
497 	[VMX_EPT_VIOLATION]	= "VMX_EPT_VIOLATION",
498 	[VMX_EPT_MISCONFIG]	= "VMX_EPT_MISCONFIG",
499 	[VMX_INVEPT]		= "VMX_INVEPT",
500 	[VMX_PREEMPT]		= "VMX_PREEMPT",
501 	[VMX_INVVPID]		= "VMX_INVVPID",
502 	[VMX_WBINVD]		= "VMX_WBINVD",
503 	[VMX_XSETBV]		= "VMX_XSETBV",
504 	[VMX_APIC_WRITE]	= "VMX_APIC_WRITE",
505 	[VMX_RDRAND]		= "VMX_RDRAND",
506 	[VMX_INVPCID]		= "VMX_INVPCID",
507 	[VMX_VMFUNC]		= "VMX_VMFUNC",
508 	[VMX_RDSEED]		= "VMX_RDSEED",
509 	[VMX_PML_FULL]		= "VMX_PML_FULL",
510 	[VMX_XSAVES]		= "VMX_XSAVES",
511 	[VMX_XRSTORS]		= "VMX_XRSTORS",
512 };
513 
514 const char *exit_reason_description(u64 reason)
515 {
516 	if (reason >= ARRAY_SIZE(exit_reason_descriptions))
517 		return "(unknown)";
518 	return exit_reason_descriptions[reason] ? : "(unused)";
519 }
520 
521 void print_vmexit_info()
522 {
523 	u64 guest_rip, guest_rsp;
524 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
525 	ulong exit_qual = vmcs_read(EXI_QUALIFICATION);
526 	guest_rip = vmcs_read(GUEST_RIP);
527 	guest_rsp = vmcs_read(GUEST_RSP);
528 	printf("VMEXIT info:\n");
529 	printf("\tvmexit reason = %ld\n", reason);
530 	printf("\texit qualification = %#lx\n", exit_qual);
531 	printf("\tBit 31 of reason = %lx\n", (vmcs_read(EXI_REASON) >> 31) & 1);
532 	printf("\tguest_rip = %#lx\n", guest_rip);
533 	printf("\tRAX=%#lx    RBX=%#lx    RCX=%#lx    RDX=%#lx\n",
534 		regs.rax, regs.rbx, regs.rcx, regs.rdx);
535 	printf("\tRSP=%#lx    RBP=%#lx    RSI=%#lx    RDI=%#lx\n",
536 		guest_rsp, regs.rbp, regs.rsi, regs.rdi);
537 	printf("\tR8 =%#lx    R9 =%#lx    R10=%#lx    R11=%#lx\n",
538 		regs.r8, regs.r9, regs.r10, regs.r11);
539 	printf("\tR12=%#lx    R13=%#lx    R14=%#lx    R15=%#lx\n",
540 		regs.r12, regs.r13, regs.r14, regs.r15);
541 }
542 
543 void
544 print_vmentry_failure_info(struct vmentry_failure *failure) {
545 	if (failure->early) {
546 		printf("Early %s failure: ", failure->instr);
547 		switch (failure->flags & VMX_ENTRY_FLAGS) {
548 		case X86_EFLAGS_CF:
549 			printf("current-VMCS pointer is not valid.\n");
550 			break;
551 		case X86_EFLAGS_ZF:
552 			printf("error number is %ld. See Intel 30.4.\n",
553 			       vmcs_read(VMX_INST_ERROR));
554 			break;
555 		default:
556 			printf("unexpected flags %lx!\n", failure->flags);
557 		}
558 	} else {
559 		u64 reason = vmcs_read(EXI_REASON);
560 		u64 qual = vmcs_read(EXI_QUALIFICATION);
561 
562 		printf("Non-early %s failure (reason=%#lx, qual=%#lx): ",
563 			failure->instr, reason, qual);
564 
565 		switch (reason & 0xff) {
566 		case VMX_FAIL_STATE:
567 			printf("invalid guest state\n");
568 			break;
569 		case VMX_FAIL_MSR:
570 			printf("MSR loading\n");
571 			break;
572 		case VMX_FAIL_MCHECK:
573 			printf("machine-check event\n");
574 			break;
575 		default:
576 			printf("unexpected basic exit reason %ld\n",
577 			       reason & 0xff);
578 		}
579 
580 		if (!(reason & VMX_ENTRY_FAILURE))
581 			printf("\tVMX_ENTRY_FAILURE BIT NOT SET!\n");
582 
583 		if (reason & 0x7fff0000)
584 			printf("\tRESERVED BITS SET!\n");
585 	}
586 }
587 
588 /*
589  * VMCLEAR should ensures all VMCS state is flushed to the VMCS
590  * region in memory.
591  */
592 static void test_vmclear_flushing(void)
593 {
594 	struct vmcs *vmcs[3] = {};
595 	int i;
596 
597 	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
598 		vmcs[i] = alloc_page();
599 		memset(vmcs[i], 0, PAGE_SIZE);
600 	}
601 
602 	vmcs[0]->revision_id = basic.revision;
603 	assert(!vmcs_clear(vmcs[0]));
604 	assert(!make_vmcs_current(vmcs[0]));
605 	set_all_vmcs_fields(0x86);
606 
607 	assert(!vmcs_clear(vmcs[0]));
608 	memcpy(vmcs[1], vmcs[0], basic.size);
609 	assert(!make_vmcs_current(vmcs[1]));
610 	report("test vmclear flush (current VMCS)", check_all_vmcs_fields(0x86));
611 
612 	set_all_vmcs_fields(0x87);
613 	assert(!make_vmcs_current(vmcs[0]));
614 	assert(!vmcs_clear(vmcs[1]));
615 	memcpy(vmcs[2], vmcs[1], basic.size);
616 	assert(!make_vmcs_current(vmcs[2]));
617 	report("test vmclear flush (!current VMCS)", check_all_vmcs_fields(0x87));
618 
619 	for (i = 0; i < ARRAY_SIZE(vmcs); i++) {
620 		assert(!vmcs_clear(vmcs[i]));
621 		free_page(vmcs[i]);
622 	}
623 }
624 
625 static void test_vmclear(void)
626 {
627 	struct vmcs *tmp_root;
628 	int width = cpuid_maxphyaddr();
629 
630 	/*
631 	 * Note- The tests below do not necessarily have a
632 	 * valid VMCS, but that's ok since the invalid vmcs
633 	 * is only used for a specific test and is discarded
634 	 * without touching its contents
635 	 */
636 
637 	/* Unaligned page access */
638 	tmp_root = (struct vmcs *)((intptr_t)vmcs_root + 1);
639 	report("test vmclear with unaligned vmcs",
640 	       vmcs_clear(tmp_root) == 1);
641 
642 	/* gpa bits beyond physical address width are set*/
643 	tmp_root = (struct vmcs *)((intptr_t)vmcs_root |
644 				   ((u64)1 << (width+1)));
645 	report("test vmclear with vmcs address bits set beyond physical address width",
646 	       vmcs_clear(tmp_root) == 1);
647 
648 	/* Pass VMXON region */
649 	tmp_root = (struct vmcs *)vmxon_region;
650 	report("test vmclear with vmxon region",
651 	       vmcs_clear(tmp_root) == 1);
652 
653 	/* Valid VMCS */
654 	report("test vmclear with valid vmcs region", vmcs_clear(vmcs_root) == 0);
655 
656 	test_vmclear_flushing();
657 }
658 
659 static void __attribute__((__used__)) guest_main(void)
660 {
661 	if (current->v2)
662 		v2_guest_main();
663 	else
664 		current->guest_main();
665 }
666 
667 /* guest_entry */
668 asm(
669 	".align	4, 0x90\n\t"
670 	".globl	entry_guest\n\t"
671 	"guest_entry:\n\t"
672 	"	call guest_main\n\t"
673 	"	mov $1, %edi\n\t"
674 	"	call hypercall\n\t"
675 );
676 
677 /* EPT paging structure related functions */
678 /* split_large_ept_entry: Split a 2M/1G large page into 512 smaller PTEs.
679 		@ptep : large page table entry to split
680 		@level : level of ptep (2 or 3)
681  */
682 static void split_large_ept_entry(unsigned long *ptep, int level)
683 {
684 	unsigned long *new_pt;
685 	unsigned long gpa;
686 	unsigned long pte;
687 	unsigned long prototype;
688 	int i;
689 
690 	pte = *ptep;
691 	assert(pte & EPT_PRESENT);
692 	assert(pte & EPT_LARGE_PAGE);
693 	assert(level == 2 || level == 3);
694 
695 	new_pt = alloc_page();
696 	assert(new_pt);
697 	memset(new_pt, 0, PAGE_SIZE);
698 
699 	prototype = pte & ~EPT_ADDR_MASK;
700 	if (level == 2)
701 		prototype &= ~EPT_LARGE_PAGE;
702 
703 	gpa = pte & EPT_ADDR_MASK;
704 	for (i = 0; i < EPT_PGDIR_ENTRIES; i++) {
705 		new_pt[i] = prototype | gpa;
706 		gpa += 1ul << EPT_LEVEL_SHIFT(level - 1);
707 	}
708 
709 	pte &= ~EPT_LARGE_PAGE;
710 	pte &= ~EPT_ADDR_MASK;
711 	pte |= virt_to_phys(new_pt);
712 
713 	*ptep = pte;
714 }
715 
716 /* install_ept_entry : Install a page to a given level in EPT
717 		@pml4 : addr of pml4 table
718 		@pte_level : level of PTE to set
719 		@guest_addr : physical address of guest
720 		@pte : pte value to set
721 		@pt_page : address of page table, NULL for a new page
722  */
723 void install_ept_entry(unsigned long *pml4,
724 		int pte_level,
725 		unsigned long guest_addr,
726 		unsigned long pte,
727 		unsigned long *pt_page)
728 {
729 	int level;
730 	unsigned long *pt = pml4;
731 	unsigned offset;
732 
733 	/* EPT only uses 48 bits of GPA. */
734 	assert(guest_addr < (1ul << 48));
735 
736 	for (level = EPT_PAGE_LEVEL; level > pte_level; --level) {
737 		offset = (guest_addr >> EPT_LEVEL_SHIFT(level))
738 				& EPT_PGDIR_MASK;
739 		if (!(pt[offset] & (EPT_PRESENT))) {
740 			unsigned long *new_pt = pt_page;
741 			if (!new_pt)
742 				new_pt = alloc_page();
743 			else
744 				pt_page = 0;
745 			memset(new_pt, 0, PAGE_SIZE);
746 			pt[offset] = virt_to_phys(new_pt)
747 					| EPT_RA | EPT_WA | EPT_EA;
748 		} else if (pt[offset] & EPT_LARGE_PAGE)
749 			split_large_ept_entry(&pt[offset], level);
750 		pt = phys_to_virt(pt[offset] & EPT_ADDR_MASK);
751 	}
752 	offset = (guest_addr >> EPT_LEVEL_SHIFT(level)) & EPT_PGDIR_MASK;
753 	pt[offset] = pte;
754 }
755 
756 /* Map a page, @perm is the permission of the page */
757 void install_ept(unsigned long *pml4,
758 		unsigned long phys,
759 		unsigned long guest_addr,
760 		u64 perm)
761 {
762 	install_ept_entry(pml4, 1, guest_addr, (phys & PAGE_MASK) | perm, 0);
763 }
764 
765 /* Map a 1G-size page */
766 void install_1g_ept(unsigned long *pml4,
767 		unsigned long phys,
768 		unsigned long guest_addr,
769 		u64 perm)
770 {
771 	install_ept_entry(pml4, 3, guest_addr,
772 			(phys & PAGE_MASK) | perm | EPT_LARGE_PAGE, 0);
773 }
774 
775 /* Map a 2M-size page */
776 void install_2m_ept(unsigned long *pml4,
777 		unsigned long phys,
778 		unsigned long guest_addr,
779 		u64 perm)
780 {
781 	install_ept_entry(pml4, 2, guest_addr,
782 			(phys & PAGE_MASK) | perm | EPT_LARGE_PAGE, 0);
783 }
784 
785 /* setup_ept_range : Setup a range of 1:1 mapped page to EPT paging structure.
786 		@start : start address of guest page
787 		@len : length of address to be mapped
788 		@map_1g : whether 1G page map is used
789 		@map_2m : whether 2M page map is used
790 		@perm : permission for every page
791  */
792 void setup_ept_range(unsigned long *pml4, unsigned long start,
793 		     unsigned long len, int map_1g, int map_2m, u64 perm)
794 {
795 	u64 phys = start;
796 	u64 max = (u64)len + (u64)start;
797 
798 	if (map_1g) {
799 		while (phys + PAGE_SIZE_1G <= max) {
800 			install_1g_ept(pml4, phys, phys, perm);
801 			phys += PAGE_SIZE_1G;
802 		}
803 	}
804 	if (map_2m) {
805 		while (phys + PAGE_SIZE_2M <= max) {
806 			install_2m_ept(pml4, phys, phys, perm);
807 			phys += PAGE_SIZE_2M;
808 		}
809 	}
810 	while (phys + PAGE_SIZE <= max) {
811 		install_ept(pml4, phys, phys, perm);
812 		phys += PAGE_SIZE;
813 	}
814 }
815 
816 /* get_ept_pte : Get the PTE of a given level in EPT,
817     @level == 1 means get the latest level*/
818 bool get_ept_pte(unsigned long *pml4, unsigned long guest_addr, int level,
819 		unsigned long *pte)
820 {
821 	int l;
822 	unsigned long *pt = pml4, iter_pte;
823 	unsigned offset;
824 
825 	assert(level >= 1 && level <= 4);
826 
827 	for (l = EPT_PAGE_LEVEL; ; --l) {
828 		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
829 		iter_pte = pt[offset];
830 		if (l == level)
831 			break;
832 		if (l < 4 && (iter_pte & EPT_LARGE_PAGE))
833 			return false;
834 		if (!(iter_pte & (EPT_PRESENT)))
835 			return false;
836 		pt = (unsigned long *)(iter_pte & EPT_ADDR_MASK);
837 	}
838 	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
839 	if (pte)
840 		*pte = pt[offset];
841 	return true;
842 }
843 
844 static void clear_ept_ad_pte(unsigned long *pml4, unsigned long guest_addr)
845 {
846 	int l;
847 	unsigned long *pt = pml4;
848 	u64 pte;
849 	unsigned offset;
850 
851 	for (l = EPT_PAGE_LEVEL; ; --l) {
852 		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
853 		pt[offset] &= ~(EPT_ACCESS_FLAG|EPT_DIRTY_FLAG);
854 		pte = pt[offset];
855 		if (l == 1 || (l < 4 && (pte & EPT_LARGE_PAGE)))
856 			break;
857 		pt = (unsigned long *)(pte & EPT_ADDR_MASK);
858 	}
859 }
860 
861 /* clear_ept_ad : Clear EPT A/D bits for the page table walk and the
862    final GPA of a guest address.  */
863 void clear_ept_ad(unsigned long *pml4, u64 guest_cr3,
864 		  unsigned long guest_addr)
865 {
866 	int l;
867 	unsigned long *pt = (unsigned long *)guest_cr3, gpa;
868 	u64 pte, offset_in_page;
869 	unsigned offset;
870 
871 	for (l = EPT_PAGE_LEVEL; ; --l) {
872 		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
873 
874 		clear_ept_ad_pte(pml4, (u64) &pt[offset]);
875 		pte = pt[offset];
876 		if (l == 1 || (l < 4 && (pte & PT_PAGE_SIZE_MASK)))
877 			break;
878 		if (!(pte & PT_PRESENT_MASK))
879 			return;
880 		pt = (unsigned long *)(pte & PT_ADDR_MASK);
881 	}
882 
883 	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
884 	offset_in_page = guest_addr & ((1 << EPT_LEVEL_SHIFT(l)) - 1);
885 	gpa = (pt[offset] & PT_ADDR_MASK) | (guest_addr & offset_in_page);
886 	clear_ept_ad_pte(pml4, gpa);
887 }
888 
889 /* check_ept_ad : Check the content of EPT A/D bits for the page table
890    walk and the final GPA of a guest address.  */
891 void check_ept_ad(unsigned long *pml4, u64 guest_cr3,
892 		  unsigned long guest_addr, int expected_gpa_ad,
893 		  int expected_pt_ad)
894 {
895 	int l;
896 	unsigned long *pt = (unsigned long *)guest_cr3, gpa;
897 	u64 ept_pte, pte, offset_in_page;
898 	unsigned offset;
899 	bool bad_pt_ad = false;
900 
901 	for (l = EPT_PAGE_LEVEL; ; --l) {
902 		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
903 
904 		if (!get_ept_pte(pml4, (u64) &pt[offset], 1, &ept_pte)) {
905 			printf("EPT - guest level %d page table is not mapped.\n", l);
906 			return;
907 		}
908 
909 		if (!bad_pt_ad) {
910 			bad_pt_ad |= (ept_pte & (EPT_ACCESS_FLAG|EPT_DIRTY_FLAG)) != expected_pt_ad;
911 			if (bad_pt_ad)
912 				report("EPT - guest level %d page table A=%d/D=%d",
913 				       false, l,
914 				       !!(expected_pt_ad & EPT_ACCESS_FLAG),
915 				       !!(expected_pt_ad & EPT_DIRTY_FLAG));
916 		}
917 
918 		pte = pt[offset];
919 		if (l == 1 || (l < 4 && (pte & PT_PAGE_SIZE_MASK)))
920 			break;
921 		if (!(pte & PT_PRESENT_MASK))
922 			return;
923 		pt = (unsigned long *)(pte & PT_ADDR_MASK);
924 	}
925 
926 	if (!bad_pt_ad)
927 		report("EPT - guest page table structures A=%d/D=%d",
928 		       true,
929 		       !!(expected_pt_ad & EPT_ACCESS_FLAG),
930 		       !!(expected_pt_ad & EPT_DIRTY_FLAG));
931 
932 	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
933 	offset_in_page = guest_addr & ((1 << EPT_LEVEL_SHIFT(l)) - 1);
934 	gpa = (pt[offset] & PT_ADDR_MASK) | (guest_addr & offset_in_page);
935 
936 	if (!get_ept_pte(pml4, gpa, 1, &ept_pte)) {
937 		report("EPT - guest physical address is not mapped", false);
938 		return;
939 	}
940 	report("EPT - guest physical address A=%d/D=%d",
941 	       (ept_pte & (EPT_ACCESS_FLAG|EPT_DIRTY_FLAG)) == expected_gpa_ad,
942 	       !!(expected_gpa_ad & EPT_ACCESS_FLAG),
943 	       !!(expected_gpa_ad & EPT_DIRTY_FLAG));
944 }
945 
946 
947 void ept_sync(int type, u64 eptp)
948 {
949 	switch (type) {
950 	case INVEPT_SINGLE:
951 		if (ept_vpid.val & EPT_CAP_INVEPT_SINGLE) {
952 			invept(INVEPT_SINGLE, eptp);
953 			break;
954 		}
955 		/* else fall through */
956 	case INVEPT_GLOBAL:
957 		if (ept_vpid.val & EPT_CAP_INVEPT_ALL) {
958 			invept(INVEPT_GLOBAL, eptp);
959 			break;
960 		}
961 		/* else fall through */
962 	default:
963 		printf("WARNING: invept is not supported!\n");
964 	}
965 }
966 
967 void set_ept_pte(unsigned long *pml4, unsigned long guest_addr,
968 		 int level, u64 pte_val)
969 {
970 	int l;
971 	unsigned long *pt = pml4;
972 	unsigned offset;
973 
974 	assert(level >= 1 && level <= 4);
975 
976 	for (l = EPT_PAGE_LEVEL; ; --l) {
977 		offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
978 		if (l == level)
979 			break;
980 		assert(pt[offset] & EPT_PRESENT);
981 		pt = (unsigned long *)(pt[offset] & EPT_ADDR_MASK);
982 	}
983 	offset = (guest_addr >> EPT_LEVEL_SHIFT(l)) & EPT_PGDIR_MASK;
984 	pt[offset] = pte_val;
985 }
986 
987 bool ept_2m_supported(void)
988 {
989 	return ept_vpid.val & EPT_CAP_2M_PAGE;
990 }
991 
992 bool ept_1g_supported(void)
993 {
994 	return ept_vpid.val & EPT_CAP_1G_PAGE;
995 }
996 
997 bool ept_huge_pages_supported(int level)
998 {
999 	if (level == 2)
1000 		return ept_2m_supported();
1001 	else if (level == 3)
1002 		return ept_1g_supported();
1003 	else
1004 		return false;
1005 }
1006 
1007 bool ept_execute_only_supported(void)
1008 {
1009 	return ept_vpid.val & EPT_CAP_WT;
1010 }
1011 
1012 bool ept_ad_bits_supported(void)
1013 {
1014 	return ept_vpid.val & EPT_CAP_AD_FLAG;
1015 }
1016 
1017 void vpid_sync(int type, u16 vpid)
1018 {
1019 	switch(type) {
1020 	case INVVPID_CONTEXT_GLOBAL:
1021 		if (ept_vpid.val & VPID_CAP_INVVPID_CXTGLB) {
1022 			invvpid(INVVPID_CONTEXT_GLOBAL, vpid, 0);
1023 			break;
1024 		}
1025 	case INVVPID_ALL:
1026 		if (ept_vpid.val & VPID_CAP_INVVPID_ALL) {
1027 			invvpid(INVVPID_ALL, vpid, 0);
1028 			break;
1029 		}
1030 	default:
1031 		printf("WARNING: invvpid is not supported\n");
1032 	}
1033 }
1034 
1035 static void init_vmcs_ctrl(void)
1036 {
1037 	/* 26.2 CHECKS ON VMX CONTROLS AND HOST-STATE AREA */
1038 	/* 26.2.1.1 */
1039 	vmcs_write(PIN_CONTROLS, ctrl_pin);
1040 	/* Disable VMEXIT of IO instruction */
1041 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu[0]);
1042 	if (ctrl_cpu_rev[0].set & CPU_SECONDARY) {
1043 		ctrl_cpu[1] = (ctrl_cpu[1] | ctrl_cpu_rev[1].set) &
1044 			ctrl_cpu_rev[1].clr;
1045 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu[1]);
1046 	}
1047 	vmcs_write(CR3_TARGET_COUNT, 0);
1048 	vmcs_write(VPID, ++vpid_cnt);
1049 }
1050 
1051 static void init_vmcs_host(void)
1052 {
1053 	/* 26.2 CHECKS ON VMX CONTROLS AND HOST-STATE AREA */
1054 	/* 26.2.1.2 */
1055 	vmcs_write(HOST_EFER, rdmsr(MSR_EFER));
1056 
1057 	/* 26.2.1.3 */
1058 	vmcs_write(ENT_CONTROLS, ctrl_enter);
1059 	vmcs_write(EXI_CONTROLS, ctrl_exit);
1060 
1061 	/* 26.2.2 */
1062 	vmcs_write(HOST_CR0, read_cr0());
1063 	vmcs_write(HOST_CR3, read_cr3());
1064 	vmcs_write(HOST_CR4, read_cr4());
1065 	vmcs_write(HOST_SYSENTER_EIP, (u64)(&entry_sysenter));
1066 	vmcs_write(HOST_SYSENTER_CS,  KERNEL_CS);
1067 
1068 	/* 26.2.3 */
1069 	vmcs_write(HOST_SEL_CS, KERNEL_CS);
1070 	vmcs_write(HOST_SEL_SS, KERNEL_DS);
1071 	vmcs_write(HOST_SEL_DS, KERNEL_DS);
1072 	vmcs_write(HOST_SEL_ES, KERNEL_DS);
1073 	vmcs_write(HOST_SEL_FS, KERNEL_DS);
1074 	vmcs_write(HOST_SEL_GS, KERNEL_DS);
1075 	vmcs_write(HOST_SEL_TR, TSS_MAIN);
1076 	vmcs_write(HOST_BASE_TR, tss_descr.base);
1077 	vmcs_write(HOST_BASE_GDTR, gdt64_desc.base);
1078 	vmcs_write(HOST_BASE_IDTR, idt_descr.base);
1079 	vmcs_write(HOST_BASE_FS, 0);
1080 	vmcs_write(HOST_BASE_GS, 0);
1081 
1082 	/* Set other vmcs area */
1083 	vmcs_write(PF_ERROR_MASK, 0);
1084 	vmcs_write(PF_ERROR_MATCH, 0);
1085 	vmcs_write(VMCS_LINK_PTR, ~0ul);
1086 	vmcs_write(VMCS_LINK_PTR_HI, ~0ul);
1087 	vmcs_write(HOST_RIP, (u64)(&vmx_return));
1088 }
1089 
1090 static void init_vmcs_guest(void)
1091 {
1092 	/* 26.3 CHECKING AND LOADING GUEST STATE */
1093 	ulong guest_cr0, guest_cr4, guest_cr3;
1094 	/* 26.3.1.1 */
1095 	guest_cr0 = read_cr0();
1096 	guest_cr4 = read_cr4();
1097 	guest_cr3 = read_cr3();
1098 	if (ctrl_enter & ENT_GUEST_64) {
1099 		guest_cr0 |= X86_CR0_PG;
1100 		guest_cr4 |= X86_CR4_PAE;
1101 	}
1102 	if ((ctrl_enter & ENT_GUEST_64) == 0)
1103 		guest_cr4 &= (~X86_CR4_PCIDE);
1104 	if (guest_cr0 & X86_CR0_PG)
1105 		guest_cr0 |= X86_CR0_PE;
1106 	vmcs_write(GUEST_CR0, guest_cr0);
1107 	vmcs_write(GUEST_CR3, guest_cr3);
1108 	vmcs_write(GUEST_CR4, guest_cr4);
1109 	vmcs_write(GUEST_SYSENTER_CS,  KERNEL_CS);
1110 	vmcs_write(GUEST_SYSENTER_ESP,
1111 		(u64)(guest_syscall_stack + PAGE_SIZE - 1));
1112 	vmcs_write(GUEST_SYSENTER_EIP, (u64)(&entry_sysenter));
1113 	vmcs_write(GUEST_DR7, 0);
1114 	vmcs_write(GUEST_EFER, rdmsr(MSR_EFER));
1115 
1116 	/* 26.3.1.2 */
1117 	vmcs_write(GUEST_SEL_CS, KERNEL_CS);
1118 	vmcs_write(GUEST_SEL_SS, KERNEL_DS);
1119 	vmcs_write(GUEST_SEL_DS, KERNEL_DS);
1120 	vmcs_write(GUEST_SEL_ES, KERNEL_DS);
1121 	vmcs_write(GUEST_SEL_FS, KERNEL_DS);
1122 	vmcs_write(GUEST_SEL_GS, KERNEL_DS);
1123 	vmcs_write(GUEST_SEL_TR, TSS_MAIN);
1124 	vmcs_write(GUEST_SEL_LDTR, 0);
1125 
1126 	vmcs_write(GUEST_BASE_CS, 0);
1127 	vmcs_write(GUEST_BASE_ES, 0);
1128 	vmcs_write(GUEST_BASE_SS, 0);
1129 	vmcs_write(GUEST_BASE_DS, 0);
1130 	vmcs_write(GUEST_BASE_FS, 0);
1131 	vmcs_write(GUEST_BASE_GS, 0);
1132 	vmcs_write(GUEST_BASE_TR, tss_descr.base);
1133 	vmcs_write(GUEST_BASE_LDTR, 0);
1134 
1135 	vmcs_write(GUEST_LIMIT_CS, 0xFFFFFFFF);
1136 	vmcs_write(GUEST_LIMIT_DS, 0xFFFFFFFF);
1137 	vmcs_write(GUEST_LIMIT_ES, 0xFFFFFFFF);
1138 	vmcs_write(GUEST_LIMIT_SS, 0xFFFFFFFF);
1139 	vmcs_write(GUEST_LIMIT_FS, 0xFFFFFFFF);
1140 	vmcs_write(GUEST_LIMIT_GS, 0xFFFFFFFF);
1141 	vmcs_write(GUEST_LIMIT_LDTR, 0xffff);
1142 	vmcs_write(GUEST_LIMIT_TR, tss_descr.limit);
1143 
1144 	vmcs_write(GUEST_AR_CS, 0xa09b);
1145 	vmcs_write(GUEST_AR_DS, 0xc093);
1146 	vmcs_write(GUEST_AR_ES, 0xc093);
1147 	vmcs_write(GUEST_AR_FS, 0xc093);
1148 	vmcs_write(GUEST_AR_GS, 0xc093);
1149 	vmcs_write(GUEST_AR_SS, 0xc093);
1150 	vmcs_write(GUEST_AR_LDTR, 0x82);
1151 	vmcs_write(GUEST_AR_TR, 0x8b);
1152 
1153 	/* 26.3.1.3 */
1154 	vmcs_write(GUEST_BASE_GDTR, gdt64_desc.base);
1155 	vmcs_write(GUEST_BASE_IDTR, idt_descr.base);
1156 	vmcs_write(GUEST_LIMIT_GDTR, gdt64_desc.limit);
1157 	vmcs_write(GUEST_LIMIT_IDTR, idt_descr.limit);
1158 
1159 	/* 26.3.1.4 */
1160 	vmcs_write(GUEST_RIP, (u64)(&guest_entry));
1161 	vmcs_write(GUEST_RSP, (u64)(guest_stack + PAGE_SIZE - 1));
1162 	vmcs_write(GUEST_RFLAGS, 0x2);
1163 
1164 	/* 26.3.1.5 */
1165 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1166 	vmcs_write(GUEST_INTR_STATE, 0);
1167 }
1168 
1169 static int init_vmcs(struct vmcs **vmcs)
1170 {
1171 	*vmcs = alloc_page();
1172 	memset(*vmcs, 0, PAGE_SIZE);
1173 	(*vmcs)->revision_id = basic.revision;
1174 	/* vmclear first to init vmcs */
1175 	if (vmcs_clear(*vmcs)) {
1176 		printf("%s : vmcs_clear error\n", __func__);
1177 		return 1;
1178 	}
1179 
1180 	if (make_vmcs_current(*vmcs)) {
1181 		printf("%s : make_vmcs_current error\n", __func__);
1182 		return 1;
1183 	}
1184 
1185 	/* All settings to pin/exit/enter/cpu
1186 	   control fields should be placed here */
1187 	ctrl_pin |= PIN_EXTINT | PIN_NMI | PIN_VIRT_NMI;
1188 	ctrl_exit = EXI_LOAD_EFER | EXI_HOST_64;
1189 	ctrl_enter = (ENT_LOAD_EFER | ENT_GUEST_64);
1190 	/* DIsable IO instruction VMEXIT now */
1191 	ctrl_cpu[0] &= (~(CPU_IO | CPU_IO_BITMAP));
1192 	ctrl_cpu[1] = 0;
1193 
1194 	ctrl_pin = (ctrl_pin | ctrl_pin_rev.set) & ctrl_pin_rev.clr;
1195 	ctrl_enter = (ctrl_enter | ctrl_enter_rev.set) & ctrl_enter_rev.clr;
1196 	ctrl_exit = (ctrl_exit | ctrl_exit_rev.set) & ctrl_exit_rev.clr;
1197 	ctrl_cpu[0] = (ctrl_cpu[0] | ctrl_cpu_rev[0].set) & ctrl_cpu_rev[0].clr;
1198 
1199 	init_vmcs_ctrl();
1200 	init_vmcs_host();
1201 	init_vmcs_guest();
1202 	return 0;
1203 }
1204 
1205 static void init_vmx(void)
1206 {
1207 	ulong fix_cr0_set, fix_cr0_clr;
1208 	ulong fix_cr4_set, fix_cr4_clr;
1209 
1210 	vmxon_region = alloc_page();
1211 	memset(vmxon_region, 0, PAGE_SIZE);
1212 
1213 	fix_cr0_set =  rdmsr(MSR_IA32_VMX_CR0_FIXED0);
1214 	fix_cr0_clr =  rdmsr(MSR_IA32_VMX_CR0_FIXED1);
1215 	fix_cr4_set =  rdmsr(MSR_IA32_VMX_CR4_FIXED0);
1216 	fix_cr4_clr = rdmsr(MSR_IA32_VMX_CR4_FIXED1);
1217 	basic.val = rdmsr(MSR_IA32_VMX_BASIC);
1218 	ctrl_pin_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_PIN
1219 			: MSR_IA32_VMX_PINBASED_CTLS);
1220 	ctrl_exit_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_EXIT
1221 			: MSR_IA32_VMX_EXIT_CTLS);
1222 	ctrl_enter_rev.val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_ENTRY
1223 			: MSR_IA32_VMX_ENTRY_CTLS);
1224 	ctrl_cpu_rev[0].val = rdmsr(basic.ctrl ? MSR_IA32_VMX_TRUE_PROC
1225 			: MSR_IA32_VMX_PROCBASED_CTLS);
1226 	if ((ctrl_cpu_rev[0].clr & CPU_SECONDARY) != 0)
1227 		ctrl_cpu_rev[1].val = rdmsr(MSR_IA32_VMX_PROCBASED_CTLS2);
1228 	else
1229 		ctrl_cpu_rev[1].val = 0;
1230 	if ((ctrl_cpu_rev[1].clr & (CPU_EPT | CPU_VPID)) != 0)
1231 		ept_vpid.val = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
1232 	else
1233 		ept_vpid.val = 0;
1234 
1235 	write_cr0((read_cr0() & fix_cr0_clr) | fix_cr0_set);
1236 	write_cr4((read_cr4() & fix_cr4_clr) | fix_cr4_set | X86_CR4_VMXE);
1237 
1238 	*vmxon_region = basic.revision;
1239 
1240 	guest_stack = alloc_page();
1241 	memset(guest_stack, 0, PAGE_SIZE);
1242 	guest_syscall_stack = alloc_page();
1243 	memset(guest_syscall_stack, 0, PAGE_SIZE);
1244 }
1245 
1246 static void do_vmxon_off(void *data)
1247 {
1248 	vmx_on();
1249 	vmx_off();
1250 }
1251 
1252 static void do_write_feature_control(void *data)
1253 {
1254 	wrmsr(MSR_IA32_FEATURE_CONTROL, 0);
1255 }
1256 
1257 static int test_vmx_feature_control(void)
1258 {
1259 	u64 ia32_feature_control;
1260 	bool vmx_enabled;
1261 
1262 	ia32_feature_control = rdmsr(MSR_IA32_FEATURE_CONTROL);
1263 	vmx_enabled = ((ia32_feature_control & 0x5) == 0x5);
1264 	if ((ia32_feature_control & 0x5) == 0x5) {
1265 		printf("VMX enabled and locked by BIOS\n");
1266 		return 0;
1267 	} else if (ia32_feature_control & 0x1) {
1268 		printf("ERROR: VMX locked out by BIOS!?\n");
1269 		return 1;
1270 	}
1271 
1272 	wrmsr(MSR_IA32_FEATURE_CONTROL, 0);
1273 	report("test vmxon with FEATURE_CONTROL cleared",
1274 	       test_for_exception(GP_VECTOR, &do_vmxon_off, NULL));
1275 
1276 	wrmsr(MSR_IA32_FEATURE_CONTROL, 0x4);
1277 	report("test vmxon without FEATURE_CONTROL lock",
1278 	       test_for_exception(GP_VECTOR, &do_vmxon_off, NULL));
1279 
1280 	wrmsr(MSR_IA32_FEATURE_CONTROL, 0x5);
1281 	vmx_enabled = ((rdmsr(MSR_IA32_FEATURE_CONTROL) & 0x5) == 0x5);
1282 	report("test enable VMX in FEATURE_CONTROL", vmx_enabled);
1283 
1284 	report("test FEATURE_CONTROL lock bit",
1285 	       test_for_exception(GP_VECTOR, &do_write_feature_control, NULL));
1286 
1287 	return !vmx_enabled;
1288 }
1289 
1290 static int test_vmxon(void)
1291 {
1292 	int ret, ret1;
1293 	u64 *tmp_region = vmxon_region;
1294 	int width = cpuid_maxphyaddr();
1295 
1296 	/* Unaligned page access */
1297 	vmxon_region = (u64 *)((intptr_t)vmxon_region + 1);
1298 	ret1 = vmx_on();
1299 	report("test vmxon with unaligned vmxon region", ret1);
1300 	if (!ret1) {
1301 		ret = 1;
1302 		goto out;
1303 	}
1304 
1305 	/* gpa bits beyond physical address width are set*/
1306 	vmxon_region = (u64 *)((intptr_t)tmp_region | ((u64)1 << (width+1)));
1307 	ret1 = vmx_on();
1308 	report("test vmxon with bits set beyond physical address width", ret1);
1309 	if (!ret1) {
1310 		ret = 1;
1311 		goto out;
1312 	}
1313 
1314 	/* invalid revision indentifier */
1315 	vmxon_region = tmp_region;
1316 	*vmxon_region = 0xba9da9;
1317 	ret1 = vmx_on();
1318 	report("test vmxon with invalid revision identifier", ret1);
1319 	if (!ret1) {
1320 		ret = 1;
1321 		goto out;
1322 	}
1323 
1324 	/* and finally a valid region */
1325 	*vmxon_region = basic.revision;
1326 	ret = vmx_on();
1327 	report("test vmxon with valid vmxon region", !ret);
1328 
1329 out:
1330 	return ret;
1331 }
1332 
1333 static void test_vmptrld(void)
1334 {
1335 	struct vmcs *vmcs, *tmp_root;
1336 	int width = cpuid_maxphyaddr();
1337 
1338 	vmcs = alloc_page();
1339 	vmcs->revision_id = basic.revision;
1340 
1341 	/* Unaligned page access */
1342 	tmp_root = (struct vmcs *)((intptr_t)vmcs + 1);
1343 	report("test vmptrld with unaligned vmcs",
1344 	       make_vmcs_current(tmp_root) == 1);
1345 
1346 	/* gpa bits beyond physical address width are set*/
1347 	tmp_root = (struct vmcs *)((intptr_t)vmcs |
1348 				   ((u64)1 << (width+1)));
1349 	report("test vmptrld with vmcs address bits set beyond physical address width",
1350 	       make_vmcs_current(tmp_root) == 1);
1351 
1352 	/* Pass VMXON region */
1353 	make_vmcs_current(vmcs);
1354 	tmp_root = (struct vmcs *)vmxon_region;
1355 	report("test vmptrld with vmxon region",
1356 	       make_vmcs_current(tmp_root) == 1);
1357 	report("test vmptrld with vmxon region vm-instruction error",
1358 	       vmcs_read(VMX_INST_ERROR) == VMXERR_VMPTRLD_VMXON_POINTER);
1359 
1360 	report("test vmptrld with valid vmcs region", make_vmcs_current(vmcs) == 0);
1361 }
1362 
1363 static void test_vmptrst(void)
1364 {
1365 	int ret;
1366 	struct vmcs *vmcs1, *vmcs2;
1367 
1368 	vmcs1 = alloc_page();
1369 	memset(vmcs1, 0, PAGE_SIZE);
1370 	init_vmcs(&vmcs1);
1371 	ret = vmcs_save(&vmcs2);
1372 	report("test vmptrst", (!ret) && (vmcs1 == vmcs2));
1373 }
1374 
1375 struct vmx_ctl_msr {
1376 	const char *name;
1377 	u32 index, true_index;
1378 	u32 default1;
1379 } vmx_ctl_msr[] = {
1380 	{ "MSR_IA32_VMX_PINBASED_CTLS", MSR_IA32_VMX_PINBASED_CTLS,
1381 	  MSR_IA32_VMX_TRUE_PIN, 0x16 },
1382 	{ "MSR_IA32_VMX_PROCBASED_CTLS", MSR_IA32_VMX_PROCBASED_CTLS,
1383 	  MSR_IA32_VMX_TRUE_PROC, 0x401e172 },
1384 	{ "MSR_IA32_VMX_PROCBASED_CTLS2", MSR_IA32_VMX_PROCBASED_CTLS2,
1385 	  MSR_IA32_VMX_PROCBASED_CTLS2, 0 },
1386 	{ "MSR_IA32_VMX_EXIT_CTLS", MSR_IA32_VMX_EXIT_CTLS,
1387 	  MSR_IA32_VMX_TRUE_EXIT, 0x36dff },
1388 	{ "MSR_IA32_VMX_ENTRY_CTLS", MSR_IA32_VMX_ENTRY_CTLS,
1389 	  MSR_IA32_VMX_TRUE_ENTRY, 0x11ff },
1390 };
1391 
1392 static void test_vmx_caps(void)
1393 {
1394 	u64 val, default1, fixed0, fixed1;
1395 	union vmx_ctrl_msr ctrl, true_ctrl;
1396 	unsigned int n;
1397 	bool ok;
1398 
1399 	printf("\nTest suite: VMX capability reporting\n");
1400 
1401 	report("MSR_IA32_VMX_BASIC",
1402 	       (basic.revision & (1ul << 31)) == 0 &&
1403 	       basic.size > 0 && basic.size <= 4096 &&
1404 	       (basic.type == 0 || basic.type == 6) &&
1405 	       basic.reserved1 == 0 && basic.reserved2 == 0);
1406 
1407 	val = rdmsr(MSR_IA32_VMX_MISC);
1408 	report("MSR_IA32_VMX_MISC",
1409 	       (!(ctrl_cpu_rev[1].clr & CPU_URG) || val & (1ul << 5)) &&
1410 	       ((val >> 16) & 0x1ff) <= 256 &&
1411 	       (val & 0xc0007e00) == 0);
1412 
1413 	for (n = 0; n < ARRAY_SIZE(vmx_ctl_msr); n++) {
1414 		ctrl.val = rdmsr(vmx_ctl_msr[n].index);
1415 		default1 = vmx_ctl_msr[n].default1;
1416 		ok = (ctrl.set & default1) == default1;
1417 		ok = ok && (ctrl.set & ~ctrl.clr) == 0;
1418 		if (ok && basic.ctrl) {
1419 			true_ctrl.val = rdmsr(vmx_ctl_msr[n].true_index);
1420 			ok = ctrl.clr == true_ctrl.clr;
1421 			ok = ok && ctrl.set == (true_ctrl.set | default1);
1422 		}
1423 		report("%s", ok, vmx_ctl_msr[n].name);
1424 	}
1425 
1426 	fixed0 = rdmsr(MSR_IA32_VMX_CR0_FIXED0);
1427 	fixed1 = rdmsr(MSR_IA32_VMX_CR0_FIXED1);
1428 	report("MSR_IA32_VMX_IA32_VMX_CR0_FIXED0/1",
1429 	       ((fixed0 ^ fixed1) & ~fixed1) == 0);
1430 
1431 	fixed0 = rdmsr(MSR_IA32_VMX_CR4_FIXED0);
1432 	fixed1 = rdmsr(MSR_IA32_VMX_CR4_FIXED1);
1433 	report("MSR_IA32_VMX_IA32_VMX_CR4_FIXED0/1",
1434 	       ((fixed0 ^ fixed1) & ~fixed1) == 0);
1435 
1436 	val = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
1437 	report("MSR_IA32_VMX_VMCS_ENUM",
1438 	       (val & 0x3e) >= 0x2a &&
1439 	       (val & 0xfffffffffffffc01Ull) == 0);
1440 
1441 	val = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
1442 	report("MSR_IA32_VMX_EPT_VPID_CAP",
1443 	       (val & 0xfffff07ef98cbebeUll) == 0);
1444 }
1445 
1446 /* This function can only be called in guest */
1447 static void __attribute__((__used__)) hypercall(u32 hypercall_no)
1448 {
1449 	u64 val = 0;
1450 	val = (hypercall_no & HYPERCALL_MASK) | HYPERCALL_BIT;
1451 	hypercall_field = val;
1452 	asm volatile("vmcall\n\t");
1453 }
1454 
1455 static bool is_hypercall()
1456 {
1457 	ulong reason, hyper_bit;
1458 
1459 	reason = vmcs_read(EXI_REASON) & 0xff;
1460 	hyper_bit = hypercall_field & HYPERCALL_BIT;
1461 	if (reason == VMX_VMCALL && hyper_bit)
1462 		return true;
1463 	return false;
1464 }
1465 
1466 static int handle_hypercall()
1467 {
1468 	ulong hypercall_no;
1469 
1470 	hypercall_no = hypercall_field & HYPERCALL_MASK;
1471 	hypercall_field = 0;
1472 	switch (hypercall_no) {
1473 	case HYPERCALL_VMEXIT:
1474 		return VMX_TEST_VMEXIT;
1475 	case HYPERCALL_VMABORT:
1476 		return VMX_TEST_VMABORT;
1477 	case HYPERCALL_VMSKIP:
1478 		return VMX_TEST_VMSKIP;
1479 	default:
1480 		printf("ERROR : Invalid hypercall number : %ld\n", hypercall_no);
1481 	}
1482 	return VMX_TEST_EXIT;
1483 }
1484 
1485 static void continue_abort(void)
1486 {
1487 	assert(!in_guest);
1488 	printf("Host was here when guest aborted:\n");
1489 	dump_stack();
1490 	longjmp(abort_target, 1);
1491 	abort();
1492 }
1493 
1494 void __abort_test(void)
1495 {
1496 	if (in_guest)
1497 		hypercall(HYPERCALL_VMABORT);
1498 	else
1499 		longjmp(abort_target, 1);
1500 	abort();
1501 }
1502 
1503 static void continue_skip(void)
1504 {
1505 	assert(!in_guest);
1506 	longjmp(abort_target, 1);
1507 	abort();
1508 }
1509 
1510 void test_skip(const char *msg)
1511 {
1512 	printf("%s skipping test: %s\n", in_guest ? "Guest" : "Host", msg);
1513 	if (in_guest)
1514 		hypercall(HYPERCALL_VMABORT);
1515 	else
1516 		longjmp(abort_target, 1);
1517 	abort();
1518 }
1519 
1520 static int exit_handler()
1521 {
1522 	int ret;
1523 
1524 	current->exits++;
1525 	regs.rflags = vmcs_read(GUEST_RFLAGS);
1526 	if (is_hypercall())
1527 		ret = handle_hypercall();
1528 	else
1529 		ret = current->exit_handler();
1530 	vmcs_write(GUEST_RFLAGS, regs.rflags);
1531 
1532 	return ret;
1533 }
1534 
1535 /*
1536  * Called if vmlaunch or vmresume fails.
1537  *	@early    - failure due to "VMX controls and host-state area" (26.2)
1538  *	@vmlaunch - was this a vmlaunch or vmresume
1539  *	@rflags   - host rflags
1540  */
1541 static int
1542 entry_failure_handler(struct vmentry_failure *failure)
1543 {
1544 	if (current->entry_failure_handler)
1545 		return current->entry_failure_handler(failure);
1546 	else
1547 		return VMX_TEST_EXIT;
1548 }
1549 
1550 /*
1551  * Tries to enter the guest. Returns true iff entry succeeded. Otherwise,
1552  * populates @failure.
1553  */
1554 static bool vmx_enter_guest(struct vmentry_failure *failure)
1555 {
1556 	failure->early = 0;
1557 
1558 	in_guest = 1;
1559 	asm volatile (
1560 		"mov %[HOST_RSP], %%rdi\n\t"
1561 		"vmwrite %%rsp, %%rdi\n\t"
1562 		LOAD_GPR_C
1563 		"cmpb $0, %[launched]\n\t"
1564 		"jne 1f\n\t"
1565 		"vmlaunch\n\t"
1566 		"jmp 2f\n\t"
1567 		"1: "
1568 		"vmresume\n\t"
1569 		"2: "
1570 		SAVE_GPR_C
1571 		"pushf\n\t"
1572 		"pop %%rdi\n\t"
1573 		"mov %%rdi, %[failure_flags]\n\t"
1574 		"movl $1, %[failure_flags]\n\t"
1575 		"jmp 3f\n\t"
1576 		"vmx_return:\n\t"
1577 		SAVE_GPR_C
1578 		"3: \n\t"
1579 		: [failure_early]"+m"(failure->early),
1580 		  [failure_flags]"=m"(failure->flags)
1581 		: [launched]"m"(launched), [HOST_RSP]"i"(HOST_RSP)
1582 		: "rdi", "memory", "cc"
1583 	);
1584 	in_guest = 0;
1585 
1586 	failure->vmlaunch = !launched;
1587 	failure->instr = launched ? "vmresume" : "vmlaunch";
1588 
1589 	return !failure->early && !(vmcs_read(EXI_REASON) & VMX_ENTRY_FAILURE);
1590 }
1591 
1592 static int vmx_run()
1593 {
1594 	while (1) {
1595 		u32 ret;
1596 		bool entered;
1597 		struct vmentry_failure failure;
1598 
1599 		entered = vmx_enter_guest(&failure);
1600 
1601 		if (entered) {
1602 			/*
1603 			 * VMCS isn't in "launched" state if there's been any
1604 			 * entry failure (early or otherwise).
1605 			 */
1606 			launched = 1;
1607 			ret = exit_handler();
1608 		} else {
1609 			ret = entry_failure_handler(&failure);
1610 		}
1611 
1612 		switch (ret) {
1613 		case VMX_TEST_RESUME:
1614 			continue;
1615 		case VMX_TEST_VMEXIT:
1616 			guest_finished = 1;
1617 			return 0;
1618 		case VMX_TEST_EXIT:
1619 			break;
1620 		default:
1621 			printf("ERROR : Invalid %s_handler return val %d.\n",
1622 			       entered ? "exit" : "entry_failure",
1623 			       ret);
1624 			break;
1625 		}
1626 
1627 		if (entered)
1628 			print_vmexit_info();
1629 		else
1630 			print_vmentry_failure_info(&failure);
1631 		abort();
1632 	}
1633 }
1634 
1635 static void run_teardown_step(struct test_teardown_step *step)
1636 {
1637 	step->func(step->data);
1638 }
1639 
1640 static int test_run(struct vmx_test *test)
1641 {
1642 	int r;
1643 
1644 	/* Validate V2 interface. */
1645 	if (test->v2) {
1646 		int ret = 0;
1647 		if (test->init || test->guest_main || test->exit_handler ||
1648 		    test->syscall_handler) {
1649 			report("V2 test cannot specify V1 callbacks.", 0);
1650 			ret = 1;
1651 		}
1652 		if (ret)
1653 			return ret;
1654 	}
1655 
1656 	if (test->name == NULL)
1657 		test->name = "(no name)";
1658 	if (vmx_on()) {
1659 		printf("%s : vmxon failed.\n", __func__);
1660 		return 1;
1661 	}
1662 
1663 	init_vmcs(&(test->vmcs));
1664 	/* Directly call test->init is ok here, init_vmcs has done
1665 	   vmcs init, vmclear and vmptrld*/
1666 	if (test->init && test->init(test->vmcs) != VMX_TEST_START)
1667 		goto out;
1668 	teardown_count = 0;
1669 	v2_guest_main = NULL;
1670 	test->exits = 0;
1671 	current = test;
1672 	regs = test->guest_regs;
1673 	vmcs_write(GUEST_RFLAGS, regs.rflags | 0x2);
1674 	launched = 0;
1675 	guest_finished = 0;
1676 	printf("\nTest suite: %s\n", test->name);
1677 
1678 	r = setjmp(abort_target);
1679 	if (r) {
1680 		assert(!in_guest);
1681 		goto out;
1682 	}
1683 
1684 
1685 	if (test->v2)
1686 		test->v2();
1687 	else
1688 		vmx_run();
1689 
1690 	while (teardown_count > 0)
1691 		run_teardown_step(&teardown_steps[--teardown_count]);
1692 
1693 	if (launched && !guest_finished)
1694 		report("Guest didn't run to completion.", 0);
1695 
1696 out:
1697 	if (vmx_off()) {
1698 		printf("%s : vmxoff failed.\n", __func__);
1699 		return 1;
1700 	}
1701 	return 0;
1702 }
1703 
1704 /*
1705  * Add a teardown step. Executed after the test's main function returns.
1706  * Teardown steps executed in reverse order.
1707  */
1708 void test_add_teardown(test_teardown_func func, void *data)
1709 {
1710 	struct test_teardown_step *step;
1711 
1712 	TEST_ASSERT_MSG(teardown_count < MAX_TEST_TEARDOWN_STEPS,
1713 			"There are already %d teardown steps.",
1714 			teardown_count);
1715 	step = &teardown_steps[teardown_count++];
1716 	step->func = func;
1717 	step->data = data;
1718 }
1719 
1720 /*
1721  * Set the target of the first enter_guest call. Can only be called once per
1722  * test. Must be called before first enter_guest call.
1723  */
1724 void test_set_guest(test_guest_func func)
1725 {
1726 	assert(current->v2);
1727 	TEST_ASSERT_MSG(!v2_guest_main, "Already set guest func.");
1728 	v2_guest_main = func;
1729 }
1730 
1731 /*
1732  * Enters the guest (or launches it for the first time). Error to call once the
1733  * guest has returned (i.e., run past the end of its guest() function). Also
1734  * aborts if guest entry fails.
1735  */
1736 void enter_guest(void)
1737 {
1738 	struct vmentry_failure failure;
1739 
1740 	TEST_ASSERT_MSG(v2_guest_main,
1741 			"Never called test_set_guest_func!");
1742 
1743 	TEST_ASSERT_MSG(!guest_finished,
1744 			"Called enter_guest() after guest returned.");
1745 
1746 	if (!vmx_enter_guest(&failure)) {
1747 		print_vmentry_failure_info(&failure);
1748 		abort();
1749 	}
1750 
1751 	launched = 1;
1752 
1753 	if (is_hypercall()) {
1754 		int ret;
1755 
1756 		ret = handle_hypercall();
1757 		switch (ret) {
1758 		case VMX_TEST_VMEXIT:
1759 			guest_finished = 1;
1760 			break;
1761 		case VMX_TEST_VMABORT:
1762 			continue_abort();
1763 			break;
1764 		case VMX_TEST_VMSKIP:
1765 			continue_skip();
1766 			break;
1767 		default:
1768 			printf("ERROR : Invalid handle_hypercall return %d.\n",
1769 			       ret);
1770 			abort();
1771 		}
1772 	}
1773 }
1774 
1775 extern struct vmx_test vmx_tests[];
1776 
1777 static bool
1778 test_wanted(const char *name, const char *filters[], int filter_count)
1779 {
1780 	int i;
1781 	bool positive = false;
1782 	bool match = false;
1783 	char clean_name[strlen(name) + 1];
1784 	char *c;
1785 	const char *n;
1786 
1787 	/* Replace spaces with underscores. */
1788 	n = name;
1789 	c = &clean_name[0];
1790 	do *c++ = (*n == ' ') ? '_' : *n;
1791 	while (*n++);
1792 
1793 	for (i = 0; i < filter_count; i++) {
1794 		const char *filter = filters[i];
1795 
1796 		if (filter[0] == '-') {
1797 			if (simple_glob(clean_name, filter + 1))
1798 				return false;
1799 		} else {
1800 			positive = true;
1801 			match |= simple_glob(clean_name, filter);
1802 		}
1803 	}
1804 
1805 	if (!positive || match) {
1806 		matched++;
1807 		return true;
1808 	} else {
1809 		return false;
1810 	}
1811 }
1812 
1813 int main(int argc, const char *argv[])
1814 {
1815 	int i = 0;
1816 
1817 	setup_vm();
1818 	setup_idt();
1819 	hypercall_field = 0;
1820 
1821 	argv++;
1822 	argc--;
1823 
1824 	if (!(cpuid(1).c & (1 << 5))) {
1825 		printf("WARNING: vmx not supported, add '-cpu host'\n");
1826 		goto exit;
1827 	}
1828 	init_vmx();
1829 	if (test_wanted("test_vmx_feature_control", argv, argc)) {
1830 		/* Sets MSR_IA32_FEATURE_CONTROL to 0x5 */
1831 		if (test_vmx_feature_control() != 0)
1832 			goto exit;
1833 	} else {
1834 		if ((rdmsr(MSR_IA32_FEATURE_CONTROL) & 0x5) != 0x5)
1835 			wrmsr(MSR_IA32_FEATURE_CONTROL, 0x5);
1836 	}
1837 
1838 	if (test_wanted("test_vmxon", argv, argc)) {
1839 		/* Enables VMX */
1840 		if (test_vmxon() != 0)
1841 			goto exit;
1842 	} else {
1843 		if (vmx_on()) {
1844 			report("vmxon", 0);
1845 			goto exit;
1846 		}
1847 	}
1848 
1849 	if (test_wanted("test_vmptrld", argv, argc))
1850 		test_vmptrld();
1851 	if (test_wanted("test_vmclear", argv, argc))
1852 		test_vmclear();
1853 	if (test_wanted("test_vmptrst", argv, argc))
1854 		test_vmptrst();
1855 	if (test_wanted("test_vmwrite_vmread", argv, argc))
1856 		test_vmwrite_vmread();
1857 	if (test_wanted("test_vmcs_high", argv, argc))
1858 		test_vmcs_high();
1859 	if (test_wanted("test_vmcs_lifecycle", argv, argc))
1860 		test_vmcs_lifecycle();
1861 	if (test_wanted("test_vmx_caps", argv, argc))
1862 		test_vmx_caps();
1863 
1864 	/* Balance vmxon from test_vmxon. */
1865 	vmx_off();
1866 
1867 	for (; vmx_tests[i].name != NULL; i++) {
1868 		if (!test_wanted(vmx_tests[i].name, argv, argc))
1869 			continue;
1870 		if (test_run(&vmx_tests[i]))
1871 			goto exit;
1872 	}
1873 
1874 	if (!matched)
1875 		report("command line didn't match any tests!", matched);
1876 
1877 exit:
1878 	return report_summary();
1879 }
1880