xref: /kvm-unit-tests/x86/vmx_tests.c (revision 91713f393551e7c42367d1c2022ca2182d8e5b6f)
1 /*
2  * All test cases of nested virtualization should be in this file
3  *
4  * Author : Arthur Chunqi Li <yzt356@gmail.com>
5  */
6 #include "vmx.h"
7 #include "msr.h"
8 #include "processor.h"
9 #include "vm.h"
10 #include "pci.h"
11 #include "fwcfg.h"
12 #include "isr.h"
13 #include "desc.h"
14 #include "apic.h"
15 #include "types.h"
16 #include "vmalloc.h"
17 #include "alloc_page.h"
18 #include "smp.h"
19 #include "delay.h"
20 
21 #define NONCANONICAL            0xaaaaaaaaaaaaaaaaull
22 
23 #define VPID_CAP_INVVPID_TYPES_SHIFT 40
24 
25 u64 ia32_pat;
26 u64 ia32_efer;
27 void *io_bitmap_a, *io_bitmap_b;
28 u16 ioport;
29 
30 unsigned long *pml4;
31 u64 eptp;
32 void *data_page1, *data_page2;
33 
34 phys_addr_t pci_physaddr;
35 
36 void *pml_log;
37 #define PML_INDEX 512
38 
39 static inline unsigned ffs(unsigned x)
40 {
41 	int pos = -1;
42 
43 	__asm__ __volatile__("bsf %1, %%eax; cmovnz %%eax, %0"
44 			     : "+r"(pos) : "rm"(x) : "eax");
45 	return pos + 1;
46 }
47 
48 static inline void vmcall(void)
49 {
50 	asm volatile("vmcall");
51 }
52 
53 static void basic_guest_main(void)
54 {
55 	report("Basic VMX test", 1);
56 }
57 
58 static int basic_exit_handler(void)
59 {
60 	report("Basic VMX test", 0);
61 	print_vmexit_info();
62 	return VMX_TEST_EXIT;
63 }
64 
65 static void vmenter_main(void)
66 {
67 	u64 rax;
68 	u64 rsp, resume_rsp;
69 
70 	report("test vmlaunch", 1);
71 
72 	asm volatile(
73 		"mov %%rsp, %0\n\t"
74 		"mov %3, %%rax\n\t"
75 		"vmcall\n\t"
76 		"mov %%rax, %1\n\t"
77 		"mov %%rsp, %2\n\t"
78 		: "=r"(rsp), "=r"(rax), "=r"(resume_rsp)
79 		: "g"(0xABCD));
80 	report("test vmresume", (rax == 0xFFFF) && (rsp == resume_rsp));
81 }
82 
83 static int vmenter_exit_handler(void)
84 {
85 	u64 guest_rip;
86 	ulong reason;
87 
88 	guest_rip = vmcs_read(GUEST_RIP);
89 	reason = vmcs_read(EXI_REASON) & 0xff;
90 	switch (reason) {
91 	case VMX_VMCALL:
92 		if (regs.rax != 0xABCD) {
93 			report("test vmresume", 0);
94 			return VMX_TEST_VMEXIT;
95 		}
96 		regs.rax = 0xFFFF;
97 		vmcs_write(GUEST_RIP, guest_rip + 3);
98 		return VMX_TEST_RESUME;
99 	default:
100 		report("test vmresume", 0);
101 		print_vmexit_info();
102 	}
103 	return VMX_TEST_VMEXIT;
104 }
105 
106 u32 preempt_scale;
107 volatile unsigned long long tsc_val;
108 volatile u32 preempt_val;
109 u64 saved_rip;
110 
111 static int preemption_timer_init(struct vmcs *vmcs)
112 {
113 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
114 		printf("\tPreemption timer is not supported\n");
115 		return VMX_TEST_EXIT;
116 	}
117 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
118 	preempt_val = 10000000;
119 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
120 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
121 
122 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
123 		printf("\tSave preemption value is not supported\n");
124 
125 	return VMX_TEST_START;
126 }
127 
128 static void preemption_timer_main(void)
129 {
130 	tsc_val = rdtsc();
131 	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
132 		vmx_set_test_stage(0);
133 		vmcall();
134 		if (vmx_get_test_stage() == 1)
135 			vmcall();
136 	}
137 	vmx_set_test_stage(1);
138 	while (vmx_get_test_stage() == 1) {
139 		if (((rdtsc() - tsc_val) >> preempt_scale)
140 				> 10 * preempt_val) {
141 			vmx_set_test_stage(2);
142 			vmcall();
143 		}
144 	}
145 	tsc_val = rdtsc();
146 	asm volatile ("hlt");
147 	vmcall();
148 	vmx_set_test_stage(5);
149 	vmcall();
150 }
151 
152 static int preemption_timer_exit_handler(void)
153 {
154 	bool guest_halted;
155 	u64 guest_rip;
156 	ulong reason;
157 	u32 insn_len;
158 	u32 ctrl_exit;
159 
160 	guest_rip = vmcs_read(GUEST_RIP);
161 	reason = vmcs_read(EXI_REASON) & 0xff;
162 	insn_len = vmcs_read(EXI_INST_LEN);
163 	switch (reason) {
164 	case VMX_PREEMPT:
165 		switch (vmx_get_test_stage()) {
166 		case 1:
167 		case 2:
168 			report("busy-wait for preemption timer",
169 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
170 			       preempt_val);
171 			vmx_set_test_stage(3);
172 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
173 			return VMX_TEST_RESUME;
174 		case 3:
175 			guest_halted =
176 				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
177 			report("preemption timer during hlt",
178 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
179 			       preempt_val && guest_halted);
180 			vmx_set_test_stage(4);
181 			vmcs_write(PIN_CONTROLS,
182 				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
183 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
184 			return VMX_TEST_RESUME;
185 		case 4:
186 			report("preemption timer with 0 value",
187 			       saved_rip == guest_rip);
188 			break;
189 		default:
190 			report("Invalid stage.", false);
191 			print_vmexit_info();
192 			break;
193 		}
194 		break;
195 	case VMX_VMCALL:
196 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
197 		switch (vmx_get_test_stage()) {
198 		case 0:
199 			report("Keep preemption value",
200 			       vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val);
201 			vmx_set_test_stage(1);
202 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
203 			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
204 				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
205 			vmcs_write(EXI_CONTROLS, ctrl_exit);
206 			return VMX_TEST_RESUME;
207 		case 1:
208 			report("Save preemption value",
209 			       vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val);
210 			return VMX_TEST_RESUME;
211 		case 2:
212 			report("busy-wait for preemption timer", 0);
213 			vmx_set_test_stage(3);
214 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
215 			return VMX_TEST_RESUME;
216 		case 3:
217 			report("preemption timer during hlt", 0);
218 			vmx_set_test_stage(4);
219 			/* fall through */
220 		case 4:
221 			vmcs_write(PIN_CONTROLS,
222 				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
223 			vmcs_write(PREEMPT_TIMER_VALUE, 0);
224 			saved_rip = guest_rip + insn_len;
225 			return VMX_TEST_RESUME;
226 		case 5:
227 			report("preemption timer with 0 value (vmcall stage 5)", 0);
228 			break;
229 		default:
230 			// Should not reach here
231 			report("unexpected stage, %d", false,
232 			       vmx_get_test_stage());
233 			print_vmexit_info();
234 			return VMX_TEST_VMEXIT;
235 		}
236 		break;
237 	default:
238 		report("Unknown exit reason, %ld", false, reason);
239 		print_vmexit_info();
240 	}
241 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
242 	return VMX_TEST_VMEXIT;
243 }
244 
245 static void msr_bmp_init(void)
246 {
247 	void *msr_bitmap;
248 	u32 ctrl_cpu0;
249 
250 	msr_bitmap = alloc_page();
251 	memset(msr_bitmap, 0x0, PAGE_SIZE);
252 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
253 	ctrl_cpu0 |= CPU_MSR_BITMAP;
254 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
255 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
256 }
257 
258 static int test_ctrl_pat_init(struct vmcs *vmcs)
259 {
260 	u64 ctrl_ent;
261 	u64 ctrl_exi;
262 
263 	msr_bmp_init();
264 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
265 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
266 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
267 		printf("\tSave/load PAT is not supported\n");
268 		return 1;
269 	}
270 
271 	ctrl_ent = vmcs_read(ENT_CONTROLS);
272 	ctrl_exi = vmcs_read(EXI_CONTROLS);
273 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
274 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
275 	vmcs_write(ENT_CONTROLS, ctrl_ent);
276 	vmcs_write(EXI_CONTROLS, ctrl_exi);
277 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
278 	vmcs_write(GUEST_PAT, 0x0);
279 	vmcs_write(HOST_PAT, ia32_pat);
280 	return VMX_TEST_START;
281 }
282 
283 static void test_ctrl_pat_main(void)
284 {
285 	u64 guest_ia32_pat;
286 
287 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
288 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
289 		printf("\tENT_LOAD_PAT is not supported.\n");
290 	else {
291 		if (guest_ia32_pat != 0) {
292 			report("Entry load PAT", 0);
293 			return;
294 		}
295 	}
296 	wrmsr(MSR_IA32_CR_PAT, 0x6);
297 	vmcall();
298 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
299 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
300 		report("Entry load PAT", guest_ia32_pat == ia32_pat);
301 }
302 
303 static int test_ctrl_pat_exit_handler(void)
304 {
305 	u64 guest_rip;
306 	ulong reason;
307 	u64 guest_pat;
308 
309 	guest_rip = vmcs_read(GUEST_RIP);
310 	reason = vmcs_read(EXI_REASON) & 0xff;
311 	switch (reason) {
312 	case VMX_VMCALL:
313 		guest_pat = vmcs_read(GUEST_PAT);
314 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
315 			printf("\tEXI_SAVE_PAT is not supported\n");
316 			vmcs_write(GUEST_PAT, 0x6);
317 		} else {
318 			report("Exit save PAT", guest_pat == 0x6);
319 		}
320 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
321 			printf("\tEXI_LOAD_PAT is not supported\n");
322 		else
323 			report("Exit load PAT", rdmsr(MSR_IA32_CR_PAT) == ia32_pat);
324 		vmcs_write(GUEST_PAT, ia32_pat);
325 		vmcs_write(GUEST_RIP, guest_rip + 3);
326 		return VMX_TEST_RESUME;
327 	default:
328 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
329 		break;
330 	}
331 	return VMX_TEST_VMEXIT;
332 }
333 
334 static int test_ctrl_efer_init(struct vmcs *vmcs)
335 {
336 	u64 ctrl_ent;
337 	u64 ctrl_exi;
338 
339 	msr_bmp_init();
340 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
341 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
342 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
343 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
344 	ia32_efer = rdmsr(MSR_EFER);
345 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
346 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
347 	return VMX_TEST_START;
348 }
349 
350 static void test_ctrl_efer_main(void)
351 {
352 	u64 guest_ia32_efer;
353 
354 	guest_ia32_efer = rdmsr(MSR_EFER);
355 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
356 		printf("\tENT_LOAD_EFER is not supported.\n");
357 	else {
358 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
359 			report("Entry load EFER", 0);
360 			return;
361 		}
362 	}
363 	wrmsr(MSR_EFER, ia32_efer);
364 	vmcall();
365 	guest_ia32_efer = rdmsr(MSR_EFER);
366 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
367 		report("Entry load EFER", guest_ia32_efer == ia32_efer);
368 }
369 
370 static int test_ctrl_efer_exit_handler(void)
371 {
372 	u64 guest_rip;
373 	ulong reason;
374 	u64 guest_efer;
375 
376 	guest_rip = vmcs_read(GUEST_RIP);
377 	reason = vmcs_read(EXI_REASON) & 0xff;
378 	switch (reason) {
379 	case VMX_VMCALL:
380 		guest_efer = vmcs_read(GUEST_EFER);
381 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
382 			printf("\tEXI_SAVE_EFER is not supported\n");
383 			vmcs_write(GUEST_EFER, ia32_efer);
384 		} else {
385 			report("Exit save EFER", guest_efer == ia32_efer);
386 		}
387 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
388 			printf("\tEXI_LOAD_EFER is not supported\n");
389 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
390 		} else {
391 			report("Exit load EFER", rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX));
392 		}
393 		vmcs_write(GUEST_PAT, ia32_efer);
394 		vmcs_write(GUEST_RIP, guest_rip + 3);
395 		return VMX_TEST_RESUME;
396 	default:
397 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
398 		break;
399 	}
400 	return VMX_TEST_VMEXIT;
401 }
402 
403 u32 guest_cr0, guest_cr4;
404 
405 static void cr_shadowing_main(void)
406 {
407 	u32 cr0, cr4, tmp;
408 
409 	// Test read through
410 	vmx_set_test_stage(0);
411 	guest_cr0 = read_cr0();
412 	if (vmx_get_test_stage() == 1)
413 		report("Read through CR0", 0);
414 	else
415 		vmcall();
416 	vmx_set_test_stage(1);
417 	guest_cr4 = read_cr4();
418 	if (vmx_get_test_stage() == 2)
419 		report("Read through CR4", 0);
420 	else
421 		vmcall();
422 	// Test write through
423 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
424 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
425 	vmx_set_test_stage(2);
426 	write_cr0(guest_cr0);
427 	if (vmx_get_test_stage() == 3)
428 		report("Write throuth CR0", 0);
429 	else
430 		vmcall();
431 	vmx_set_test_stage(3);
432 	write_cr4(guest_cr4);
433 	if (vmx_get_test_stage() == 4)
434 		report("Write through CR4", 0);
435 	else
436 		vmcall();
437 	// Test read shadow
438 	vmx_set_test_stage(4);
439 	vmcall();
440 	cr0 = read_cr0();
441 	if (vmx_get_test_stage() != 5)
442 		report("Read shadowing CR0", cr0 == guest_cr0);
443 	vmx_set_test_stage(5);
444 	cr4 = read_cr4();
445 	if (vmx_get_test_stage() != 6)
446 		report("Read shadowing CR4", cr4 == guest_cr4);
447 	// Test write shadow (same value with shadow)
448 	vmx_set_test_stage(6);
449 	write_cr0(guest_cr0);
450 	if (vmx_get_test_stage() == 7)
451 		report("Write shadowing CR0 (same value with shadow)", 0);
452 	else
453 		vmcall();
454 	vmx_set_test_stage(7);
455 	write_cr4(guest_cr4);
456 	if (vmx_get_test_stage() == 8)
457 		report("Write shadowing CR4 (same value with shadow)", 0);
458 	else
459 		vmcall();
460 	// Test write shadow (different value)
461 	vmx_set_test_stage(8);
462 	tmp = guest_cr0 ^ X86_CR0_TS;
463 	asm volatile("mov %0, %%rsi\n\t"
464 		"mov %%rsi, %%cr0\n\t"
465 		::"m"(tmp)
466 		:"rsi", "memory", "cc");
467 	report("Write shadowing different X86_CR0_TS", vmx_get_test_stage() == 9);
468 	vmx_set_test_stage(9);
469 	tmp = guest_cr0 ^ X86_CR0_MP;
470 	asm volatile("mov %0, %%rsi\n\t"
471 		"mov %%rsi, %%cr0\n\t"
472 		::"m"(tmp)
473 		:"rsi", "memory", "cc");
474 	report("Write shadowing different X86_CR0_MP", vmx_get_test_stage() == 10);
475 	vmx_set_test_stage(10);
476 	tmp = guest_cr4 ^ X86_CR4_TSD;
477 	asm volatile("mov %0, %%rsi\n\t"
478 		"mov %%rsi, %%cr4\n\t"
479 		::"m"(tmp)
480 		:"rsi", "memory", "cc");
481 	report("Write shadowing different X86_CR4_TSD", vmx_get_test_stage() == 11);
482 	vmx_set_test_stage(11);
483 	tmp = guest_cr4 ^ X86_CR4_DE;
484 	asm volatile("mov %0, %%rsi\n\t"
485 		"mov %%rsi, %%cr4\n\t"
486 		::"m"(tmp)
487 		:"rsi", "memory", "cc");
488 	report("Write shadowing different X86_CR4_DE", vmx_get_test_stage() == 12);
489 }
490 
491 static int cr_shadowing_exit_handler(void)
492 {
493 	u64 guest_rip;
494 	ulong reason;
495 	u32 insn_len;
496 	u32 exit_qual;
497 
498 	guest_rip = vmcs_read(GUEST_RIP);
499 	reason = vmcs_read(EXI_REASON) & 0xff;
500 	insn_len = vmcs_read(EXI_INST_LEN);
501 	exit_qual = vmcs_read(EXI_QUALIFICATION);
502 	switch (reason) {
503 	case VMX_VMCALL:
504 		switch (vmx_get_test_stage()) {
505 		case 0:
506 			report("Read through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
507 			break;
508 		case 1:
509 			report("Read through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
510 			break;
511 		case 2:
512 			report("Write through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
513 			break;
514 		case 3:
515 			report("Write through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
516 			break;
517 		case 4:
518 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
519 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
520 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
521 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
522 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
523 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
524 			break;
525 		case 6:
526 			report("Write shadowing CR0 (same value)",
527 					guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)));
528 			break;
529 		case 7:
530 			report("Write shadowing CR4 (same value)",
531 					guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)));
532 			break;
533 		default:
534 			// Should not reach here
535 			report("unexpected stage, %d", false,
536 			       vmx_get_test_stage());
537 			print_vmexit_info();
538 			return VMX_TEST_VMEXIT;
539 		}
540 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
541 		return VMX_TEST_RESUME;
542 	case VMX_CR:
543 		switch (vmx_get_test_stage()) {
544 		case 4:
545 			report("Read shadowing CR0", 0);
546 			vmx_inc_test_stage();
547 			break;
548 		case 5:
549 			report("Read shadowing CR4", 0);
550 			vmx_inc_test_stage();
551 			break;
552 		case 6:
553 			report("Write shadowing CR0 (same value)", 0);
554 			vmx_inc_test_stage();
555 			break;
556 		case 7:
557 			report("Write shadowing CR4 (same value)", 0);
558 			vmx_inc_test_stage();
559 			break;
560 		case 8:
561 		case 9:
562 			// 0x600 encodes "mov %esi, %cr0"
563 			if (exit_qual == 0x600)
564 				vmx_inc_test_stage();
565 			break;
566 		case 10:
567 		case 11:
568 			// 0x604 encodes "mov %esi, %cr4"
569 			if (exit_qual == 0x604)
570 				vmx_inc_test_stage();
571 			break;
572 		default:
573 			// Should not reach here
574 			report("unexpected stage, %d", false,
575 			       vmx_get_test_stage());
576 			print_vmexit_info();
577 			return VMX_TEST_VMEXIT;
578 		}
579 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
580 		return VMX_TEST_RESUME;
581 	default:
582 		report("Unknown exit reason, %ld", false, reason);
583 		print_vmexit_info();
584 	}
585 	return VMX_TEST_VMEXIT;
586 }
587 
588 static int iobmp_init(struct vmcs *vmcs)
589 {
590 	u32 ctrl_cpu0;
591 
592 	io_bitmap_a = alloc_page();
593 	io_bitmap_b = alloc_page();
594 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
595 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
596 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
597 	ctrl_cpu0 |= CPU_IO_BITMAP;
598 	ctrl_cpu0 &= (~CPU_IO);
599 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
600 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
601 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
602 	return VMX_TEST_START;
603 }
604 
605 static void iobmp_main(void)
606 {
607 	// stage 0, test IO pass
608 	vmx_set_test_stage(0);
609 	inb(0x5000);
610 	outb(0x0, 0x5000);
611 	report("I/O bitmap - I/O pass", vmx_get_test_stage() == 0);
612 	// test IO width, in/out
613 	((u8 *)io_bitmap_a)[0] = 0xFF;
614 	vmx_set_test_stage(2);
615 	inb(0x0);
616 	report("I/O bitmap - trap in", vmx_get_test_stage() == 3);
617 	vmx_set_test_stage(3);
618 	outw(0x0, 0x0);
619 	report("I/O bitmap - trap out", vmx_get_test_stage() == 4);
620 	vmx_set_test_stage(4);
621 	inl(0x0);
622 	report("I/O bitmap - I/O width, long", vmx_get_test_stage() == 5);
623 	// test low/high IO port
624 	vmx_set_test_stage(5);
625 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
626 	inb(0x5000);
627 	report("I/O bitmap - I/O port, low part", vmx_get_test_stage() == 6);
628 	vmx_set_test_stage(6);
629 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
630 	inb(0x9000);
631 	report("I/O bitmap - I/O port, high part", vmx_get_test_stage() == 7);
632 	// test partial pass
633 	vmx_set_test_stage(7);
634 	inl(0x4FFF);
635 	report("I/O bitmap - partial pass", vmx_get_test_stage() == 8);
636 	// test overrun
637 	vmx_set_test_stage(8);
638 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
639 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
640 	inl(0xFFFF);
641 	report("I/O bitmap - overrun", vmx_get_test_stage() == 9);
642 	vmx_set_test_stage(9);
643 	vmcall();
644 	outb(0x0, 0x0);
645 	report("I/O bitmap - ignore unconditional exiting",
646 	       vmx_get_test_stage() == 9);
647 	vmx_set_test_stage(10);
648 	vmcall();
649 	outb(0x0, 0x0);
650 	report("I/O bitmap - unconditional exiting",
651 	       vmx_get_test_stage() == 11);
652 }
653 
654 static int iobmp_exit_handler(void)
655 {
656 	u64 guest_rip;
657 	ulong reason, exit_qual;
658 	u32 insn_len, ctrl_cpu0;
659 
660 	guest_rip = vmcs_read(GUEST_RIP);
661 	reason = vmcs_read(EXI_REASON) & 0xff;
662 	exit_qual = vmcs_read(EXI_QUALIFICATION);
663 	insn_len = vmcs_read(EXI_INST_LEN);
664 	switch (reason) {
665 	case VMX_IO:
666 		switch (vmx_get_test_stage()) {
667 		case 0:
668 		case 1:
669 			vmx_inc_test_stage();
670 			break;
671 		case 2:
672 			report("I/O bitmap - I/O width, byte",
673 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE);
674 			report("I/O bitmap - I/O direction, in", exit_qual & VMX_IO_IN);
675 			vmx_inc_test_stage();
676 			break;
677 		case 3:
678 			report("I/O bitmap - I/O width, word",
679 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD);
680 			report("I/O bitmap - I/O direction, out",
681 					!(exit_qual & VMX_IO_IN));
682 			vmx_inc_test_stage();
683 			break;
684 		case 4:
685 			report("I/O bitmap - I/O width, long",
686 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG);
687 			vmx_inc_test_stage();
688 			break;
689 		case 5:
690 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
691 				vmx_inc_test_stage();
692 			break;
693 		case 6:
694 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
695 				vmx_inc_test_stage();
696 			break;
697 		case 7:
698 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
699 				vmx_inc_test_stage();
700 			break;
701 		case 8:
702 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
703 				vmx_inc_test_stage();
704 			break;
705 		case 9:
706 		case 10:
707 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
708 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
709 			vmx_inc_test_stage();
710 			break;
711 		default:
712 			// Should not reach here
713 			report("unexpected stage, %d", false,
714 			       vmx_get_test_stage());
715 			print_vmexit_info();
716 			return VMX_TEST_VMEXIT;
717 		}
718 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
719 		return VMX_TEST_RESUME;
720 	case VMX_VMCALL:
721 		switch (vmx_get_test_stage()) {
722 		case 9:
723 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
724 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
725 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
726 			break;
727 		case 10:
728 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
729 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
730 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
731 			break;
732 		default:
733 			// Should not reach here
734 			report("unexpected stage, %d", false,
735 			       vmx_get_test_stage());
736 			print_vmexit_info();
737 			return VMX_TEST_VMEXIT;
738 		}
739 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
740 		return VMX_TEST_RESUME;
741 	default:
742 		printf("guest_rip = %#lx\n", guest_rip);
743 		printf("\tERROR : Undefined exit reason, reason = %ld.\n", reason);
744 		break;
745 	}
746 	return VMX_TEST_VMEXIT;
747 }
748 
749 #define INSN_CPU0		0
750 #define INSN_CPU1		1
751 #define INSN_ALWAYS_TRAP	2
752 
753 #define FIELD_EXIT_QUAL		(1 << 0)
754 #define FIELD_INSN_INFO		(1 << 1)
755 
756 asm(
757 	"insn_hlt: hlt;ret\n\t"
758 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
759 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
760 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
761 	"insn_rdtsc: rdtsc;ret\n\t"
762 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
763 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
764 #ifdef __x86_64__
765 	"insn_cr8_load: xor %eax, %eax; mov %rax,%cr8;ret\n\t"
766 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
767 #endif
768 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
769 	"insn_pause: pause;ret\n\t"
770 	"insn_wbinvd: wbinvd;ret\n\t"
771 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
772 	"insn_invd: invd;ret\n\t"
773 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
774 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
775 	"insn_sidt: sidt idt_descr;ret\n\t"
776 	"insn_lidt: lidt idt_descr;ret\n\t"
777 	"insn_sldt: sldt %ax;ret\n\t"
778 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
779 	"insn_str: str %ax;ret\n\t"
780 	"insn_rdrand: rdrand %rax;ret\n\t"
781 	"insn_rdseed: rdseed %rax;ret\n\t"
782 );
783 extern void insn_hlt(void);
784 extern void insn_invlpg(void);
785 extern void insn_mwait(void);
786 extern void insn_rdpmc(void);
787 extern void insn_rdtsc(void);
788 extern void insn_cr3_load(void);
789 extern void insn_cr3_store(void);
790 #ifdef __x86_64__
791 extern void insn_cr8_load(void);
792 extern void insn_cr8_store(void);
793 #endif
794 extern void insn_monitor(void);
795 extern void insn_pause(void);
796 extern void insn_wbinvd(void);
797 extern void insn_sgdt(void);
798 extern void insn_lgdt(void);
799 extern void insn_sidt(void);
800 extern void insn_lidt(void);
801 extern void insn_sldt(void);
802 extern void insn_lldt(void);
803 extern void insn_str(void);
804 extern void insn_cpuid(void);
805 extern void insn_invd(void);
806 extern void insn_rdrand(void);
807 extern void insn_rdseed(void);
808 
809 u32 cur_insn;
810 u64 cr3;
811 
812 struct insn_table {
813 	const char *name;
814 	u32 flag;
815 	void (*insn_func)(void);
816 	u32 type;
817 	u32 reason;
818 	ulong exit_qual;
819 	u32 insn_info;
820 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
821 	// which field need to be tested, reason is always tested
822 	u32 test_field;
823 };
824 
825 /*
826  * Add more test cases of instruction intercept here. Elements in this
827  * table is:
828  *	name/control flag/insn function/type/exit reason/exit qulification/
829  *	instruction info/field to test
830  * The last field defines which fields (exit_qual and insn_info) need to be
831  * tested in exit handler. If set to 0, only "reason" is checked.
832  */
833 static struct insn_table insn_table[] = {
834 	// Flags for Primary Processor-Based VM-Execution Controls
835 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
836 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
837 		0x12345678, 0, FIELD_EXIT_QUAL},
838 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0},
839 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
840 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
841 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
842 		FIELD_EXIT_QUAL},
843 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
844 		FIELD_EXIT_QUAL},
845 #ifdef __x86_64__
846 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
847 		FIELD_EXIT_QUAL},
848 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
849 		FIELD_EXIT_QUAL},
850 #endif
851 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0},
852 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
853 	// Flags for Secondary Processor-Based VM-Execution Controls
854 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
855 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
856 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
857 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
858 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
859 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
860 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
861 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
862 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
863 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
864 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
865 	// Instructions always trap
866 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
867 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
868 	// Instructions never trap
869 	{NULL},
870 };
871 
872 static int insn_intercept_init(struct vmcs *vmcs)
873 {
874 	u32 ctrl_cpu;
875 
876 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
877 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
878 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
879 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
880 	cr3 = read_cr3();
881 	return VMX_TEST_START;
882 }
883 
884 static void insn_intercept_main(void)
885 {
886 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
887 		vmx_set_test_stage(cur_insn * 2);
888 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
889 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
890 		    (insn_table[cur_insn].type == INSN_CPU1 &&
891 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
892 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
893 			       insn_table[cur_insn].type - INSN_CPU0,
894 			       insn_table[cur_insn].name);
895 			continue;
896 		}
897 
898 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
899 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
900 		    (insn_table[cur_insn].type == INSN_CPU1 &&
901 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
902 			/* skip hlt, it stalls the guest and is tested below */
903 			if (insn_table[cur_insn].insn_func != insn_hlt)
904 				insn_table[cur_insn].insn_func();
905 			report("execute %s", vmx_get_test_stage() == cur_insn * 2,
906 					insn_table[cur_insn].name);
907 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
908 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
909 			       insn_table[cur_insn].type - INSN_CPU0,
910 			       insn_table[cur_insn].name);
911 
912 		vmcall();
913 
914 		insn_table[cur_insn].insn_func();
915 		report("intercept %s", vmx_get_test_stage() == cur_insn * 2 + 1,
916 				insn_table[cur_insn].name);
917 
918 		vmx_set_test_stage(cur_insn * 2 + 1);
919 		vmcall();
920 	}
921 }
922 
923 static int insn_intercept_exit_handler(void)
924 {
925 	u64 guest_rip;
926 	u32 reason;
927 	ulong exit_qual;
928 	u32 insn_len;
929 	u32 insn_info;
930 	bool pass;
931 
932 	guest_rip = vmcs_read(GUEST_RIP);
933 	reason = vmcs_read(EXI_REASON) & 0xff;
934 	exit_qual = vmcs_read(EXI_QUALIFICATION);
935 	insn_len = vmcs_read(EXI_INST_LEN);
936 	insn_info = vmcs_read(EXI_INST_INFO);
937 
938 	if (reason == VMX_VMCALL) {
939 		u32 val = 0;
940 
941 		if (insn_table[cur_insn].type == INSN_CPU0)
942 			val = vmcs_read(CPU_EXEC_CTRL0);
943 		else if (insn_table[cur_insn].type == INSN_CPU1)
944 			val = vmcs_read(CPU_EXEC_CTRL1);
945 
946 		if (vmx_get_test_stage() & 1)
947 			val &= ~insn_table[cur_insn].flag;
948 		else
949 			val |= insn_table[cur_insn].flag;
950 
951 		if (insn_table[cur_insn].type == INSN_CPU0)
952 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
953 		else if (insn_table[cur_insn].type == INSN_CPU1)
954 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
955 	} else {
956 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
957 			insn_table[cur_insn].reason == reason;
958 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
959 		    insn_table[cur_insn].exit_qual != exit_qual)
960 			pass = false;
961 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
962 		    insn_table[cur_insn].insn_info != insn_info)
963 			pass = false;
964 		if (pass)
965 			vmx_inc_test_stage();
966 	}
967 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
968 	return VMX_TEST_RESUME;
969 }
970 
971 
972 /* Enables EPT and sets up the identity map. */
973 static int setup_ept(bool enable_ad)
974 {
975 	unsigned long end_of_memory;
976 	u32 ctrl_cpu[2];
977 
978 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
979 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
980 		printf("\tEPT is not supported");
981 		return 1;
982 	}
983 
984 
985 	if (!(ept_vpid.val & EPT_CAP_UC) &&
986 			!(ept_vpid.val & EPT_CAP_WB)) {
987 		printf("\tEPT paging-structure memory type "
988 				"UC&WB are not supported\n");
989 		return 1;
990 	}
991 	if (ept_vpid.val & EPT_CAP_UC)
992 		eptp = EPT_MEM_TYPE_UC;
993 	else
994 		eptp = EPT_MEM_TYPE_WB;
995 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
996 		printf("\tPWL4 is not supported\n");
997 		return 1;
998 	}
999 	ctrl_cpu[0] = vmcs_read(CPU_EXEC_CTRL0);
1000 	ctrl_cpu[1] = vmcs_read(CPU_EXEC_CTRL1);
1001 	ctrl_cpu[0] = (ctrl_cpu[0] | CPU_SECONDARY)
1002 		& ctrl_cpu_rev[0].clr;
1003 	ctrl_cpu[1] = (ctrl_cpu[1] | CPU_EPT)
1004 		& ctrl_cpu_rev[1].clr;
1005 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu[0]);
1006 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu[1]);
1007 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1008 	pml4 = alloc_page();
1009 	memset(pml4, 0, PAGE_SIZE);
1010 	eptp |= virt_to_phys(pml4);
1011 	if (enable_ad)
1012 		eptp |= EPTP_AD_FLAG;
1013 	vmcs_write(EPTP, eptp);
1014 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1015 	if (end_of_memory < (1ul << 32))
1016 		end_of_memory = (1ul << 32);
1017 	/* Cannot use large EPT pages if we need to track EPT
1018 	 * accessed/dirty bits at 4K granularity.
1019 	 */
1020 	setup_ept_range(pml4, 0, end_of_memory, 0,
1021 			!enable_ad && ept_2m_supported(),
1022 			EPT_WA | EPT_RA | EPT_EA);
1023 	return 0;
1024 }
1025 
1026 static void ept_enable_ad_bits(void)
1027 {
1028 	eptp |= EPTP_AD_FLAG;
1029 	vmcs_write(EPTP, eptp);
1030 }
1031 
1032 static void ept_disable_ad_bits(void)
1033 {
1034 	eptp &= ~EPTP_AD_FLAG;
1035 	vmcs_write(EPTP, eptp);
1036 }
1037 
1038 static void ept_enable_ad_bits_or_skip_test(void)
1039 {
1040 	if (!ept_ad_bits_supported())
1041 		test_skip("EPT AD bits not supported.");
1042 	ept_enable_ad_bits();
1043 }
1044 
1045 static int apic_version;
1046 
1047 static int ept_init_common(bool have_ad)
1048 {
1049 	int ret;
1050 	struct pci_dev pcidev;
1051 
1052 	if (setup_ept(have_ad))
1053 		return VMX_TEST_EXIT;
1054 	data_page1 = alloc_page();
1055 	data_page2 = alloc_page();
1056 	memset(data_page1, 0x0, PAGE_SIZE);
1057 	memset(data_page2, 0x0, PAGE_SIZE);
1058 	*((u32 *)data_page1) = MAGIC_VAL_1;
1059 	*((u32 *)data_page2) = MAGIC_VAL_2;
1060 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1061 			EPT_RA | EPT_WA | EPT_EA);
1062 
1063 	apic_version = apic_read(APIC_LVR);
1064 
1065 	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
1066 	if (ret != PCIDEVADDR_INVALID) {
1067 		pci_dev_init(&pcidev, ret);
1068 		pci_physaddr = pcidev.resource[PCI_TESTDEV_BAR_MEM];
1069 	}
1070 
1071 	return VMX_TEST_START;
1072 }
1073 
1074 static int ept_init(struct vmcs *vmcs)
1075 {
1076 	return ept_init_common(false);
1077 }
1078 
1079 static void ept_common(void)
1080 {
1081 	vmx_set_test_stage(0);
1082 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1083 			*((u32 *)data_page1) != MAGIC_VAL_1)
1084 		report("EPT basic framework - read", 0);
1085 	else {
1086 		*((u32 *)data_page2) = MAGIC_VAL_3;
1087 		vmcall();
1088 		if (vmx_get_test_stage() == 1) {
1089 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1090 					*((u32 *)data_page2) == MAGIC_VAL_2)
1091 				report("EPT basic framework", 1);
1092 			else
1093 				report("EPT basic framework - remap", 1);
1094 		}
1095 	}
1096 	// Test EPT Misconfigurations
1097 	vmx_set_test_stage(1);
1098 	vmcall();
1099 	*((u32 *)data_page1) = MAGIC_VAL_1;
1100 	if (vmx_get_test_stage() != 2) {
1101 		report("EPT misconfigurations", 0);
1102 		goto t1;
1103 	}
1104 	vmx_set_test_stage(2);
1105 	vmcall();
1106 	*((u32 *)data_page1) = MAGIC_VAL_1;
1107 	report("EPT misconfigurations", vmx_get_test_stage() == 3);
1108 t1:
1109 	// Test EPT violation
1110 	vmx_set_test_stage(3);
1111 	vmcall();
1112 	*((u32 *)data_page1) = MAGIC_VAL_1;
1113 	report("EPT violation - page permission", vmx_get_test_stage() == 4);
1114 	// Violation caused by EPT paging structure
1115 	vmx_set_test_stage(4);
1116 	vmcall();
1117 	*((u32 *)data_page1) = MAGIC_VAL_2;
1118 	report("EPT violation - paging structure", vmx_get_test_stage() == 5);
1119 
1120 	// MMIO Read/Write
1121 	vmx_set_test_stage(5);
1122 	vmcall();
1123 
1124 	*(u32 volatile *)pci_physaddr;
1125 	report("MMIO EPT violation - read", vmx_get_test_stage() == 6);
1126 
1127 	*(u32 volatile *)pci_physaddr = MAGIC_VAL_1;
1128 	report("MMIO EPT violation - write", vmx_get_test_stage() == 7);
1129 }
1130 
1131 static void ept_main(void)
1132 {
1133 	ept_common();
1134 
1135 	// Test EPT access to L1 MMIO
1136 	vmx_set_test_stage(7);
1137 	report("EPT - MMIO access", *((u32 *)0xfee00030UL) == apic_version);
1138 
1139 	// Test invalid operand for INVEPT
1140 	vmcall();
1141 	report("EPT - unsupported INVEPT", vmx_get_test_stage() == 8);
1142 }
1143 
1144 static bool invept_test(int type, u64 eptp)
1145 {
1146 	bool ret, supported;
1147 
1148 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1149 	ret = invept(type, eptp);
1150 
1151 	if (ret == !supported)
1152 		return false;
1153 
1154 	if (!supported)
1155 		printf("WARNING: unsupported invept passed!\n");
1156 	else
1157 		printf("WARNING: invept failed!\n");
1158 
1159 	return true;
1160 }
1161 
1162 static int pml_exit_handler(void)
1163 {
1164 	u16 index, count;
1165 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1166 	u64 *pmlbuf = pml_log;
1167 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1168 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1169 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1170 
1171 	switch (reason) {
1172 	case VMX_VMCALL:
1173 		switch (vmx_get_test_stage()) {
1174 		case 0:
1175 			index = vmcs_read(GUEST_PML_INDEX);
1176 			for (count = index + 1; count < PML_INDEX; count++) {
1177 				if (pmlbuf[count] == (u64)data_page2) {
1178 					vmx_inc_test_stage();
1179 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1180 					break;
1181 				}
1182 			}
1183 			break;
1184 		case 1:
1185 			index = vmcs_read(GUEST_PML_INDEX);
1186 			/* Keep clearing the dirty bit till a overflow */
1187 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1188 			break;
1189 		default:
1190 			report("unexpected stage, %d.", false,
1191 			       vmx_get_test_stage());
1192 			print_vmexit_info();
1193 			return VMX_TEST_VMEXIT;
1194 		}
1195 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1196 		return VMX_TEST_RESUME;
1197 	case VMX_PML_FULL:
1198 		vmx_inc_test_stage();
1199 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1200 		return VMX_TEST_RESUME;
1201 	default:
1202 		report("Unknown exit reason, %ld", false, reason);
1203 		print_vmexit_info();
1204 	}
1205 	return VMX_TEST_VMEXIT;
1206 }
1207 
1208 static int ept_exit_handler_common(bool have_ad)
1209 {
1210 	u64 guest_rip;
1211 	u64 guest_cr3;
1212 	ulong reason;
1213 	u32 insn_len;
1214 	u32 exit_qual;
1215 	static unsigned long data_page1_pte, data_page1_pte_pte, memaddr_pte;
1216 
1217 	guest_rip = vmcs_read(GUEST_RIP);
1218 	guest_cr3 = vmcs_read(GUEST_CR3);
1219 	reason = vmcs_read(EXI_REASON) & 0xff;
1220 	insn_len = vmcs_read(EXI_INST_LEN);
1221 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1222 	switch (reason) {
1223 	case VMX_VMCALL:
1224 		switch (vmx_get_test_stage()) {
1225 		case 0:
1226 			check_ept_ad(pml4, guest_cr3,
1227 				     (unsigned long)data_page1,
1228 				     have_ad ? EPT_ACCESS_FLAG : 0,
1229 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1230 			check_ept_ad(pml4, guest_cr3,
1231 				     (unsigned long)data_page2,
1232 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1233 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1234 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1235 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1236 			if (have_ad)
1237 				ept_sync(INVEPT_SINGLE, eptp);;
1238 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1239 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1240 				vmx_inc_test_stage();
1241 				install_ept(pml4, (unsigned long)data_page2,
1242 						(unsigned long)data_page2,
1243 						EPT_RA | EPT_WA | EPT_EA);
1244 			} else
1245 				report("EPT basic framework - write", 0);
1246 			break;
1247 		case 1:
1248 			install_ept(pml4, (unsigned long)data_page1,
1249  				(unsigned long)data_page1, EPT_WA);
1250 			ept_sync(INVEPT_SINGLE, eptp);
1251 			break;
1252 		case 2:
1253 			install_ept(pml4, (unsigned long)data_page1,
1254  				(unsigned long)data_page1,
1255  				EPT_RA | EPT_WA | EPT_EA |
1256  				(2 << EPT_MEM_TYPE_SHIFT));
1257 			ept_sync(INVEPT_SINGLE, eptp);
1258 			break;
1259 		case 3:
1260 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1261 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1262 						1, &data_page1_pte));
1263 			set_ept_pte(pml4, (unsigned long)data_page1,
1264 				1, data_page1_pte & ~EPT_PRESENT);
1265 			ept_sync(INVEPT_SINGLE, eptp);
1266 			break;
1267 		case 4:
1268 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1269 						2, &data_page1_pte));
1270 			data_page1_pte &= PAGE_MASK;
1271 			TEST_ASSERT(get_ept_pte(pml4, data_page1_pte,
1272 						2, &data_page1_pte_pte));
1273 			set_ept_pte(pml4, data_page1_pte, 2,
1274 				data_page1_pte_pte & ~EPT_PRESENT);
1275 			ept_sync(INVEPT_SINGLE, eptp);
1276 			break;
1277 		case 5:
1278 			install_ept(pml4, (unsigned long)pci_physaddr,
1279 				(unsigned long)pci_physaddr, 0);
1280 			ept_sync(INVEPT_SINGLE, eptp);
1281 			break;
1282 		case 7:
1283 			if (!invept_test(0, eptp))
1284 				vmx_inc_test_stage();
1285 			break;
1286 		// Should not reach here
1287 		default:
1288 			report("ERROR - unexpected stage, %d.", false,
1289 			       vmx_get_test_stage());
1290 			print_vmexit_info();
1291 			return VMX_TEST_VMEXIT;
1292 		}
1293 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1294 		return VMX_TEST_RESUME;
1295 	case VMX_EPT_MISCONFIG:
1296 		switch (vmx_get_test_stage()) {
1297 		case 1:
1298 		case 2:
1299 			vmx_inc_test_stage();
1300 			install_ept(pml4, (unsigned long)data_page1,
1301  				(unsigned long)data_page1,
1302  				EPT_RA | EPT_WA | EPT_EA);
1303 			ept_sync(INVEPT_SINGLE, eptp);
1304 			break;
1305 		// Should not reach here
1306 		default:
1307 			report("ERROR - unexpected stage, %d.", false,
1308 			       vmx_get_test_stage());
1309 			print_vmexit_info();
1310 			return VMX_TEST_VMEXIT;
1311 		}
1312 		return VMX_TEST_RESUME;
1313 	case VMX_EPT_VIOLATION:
1314 		switch(vmx_get_test_stage()) {
1315 		case 3:
1316 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1317 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1318 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1319 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1320 					EPT_VLT_PADDR))
1321 				vmx_inc_test_stage();
1322 			set_ept_pte(pml4, (unsigned long)data_page1,
1323 				1, data_page1_pte | (EPT_PRESENT));
1324 			ept_sync(INVEPT_SINGLE, eptp);
1325 			break;
1326 		case 4:
1327 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1328 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1329 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1330 			if (exit_qual == (EPT_VLT_RD |
1331 					  (have_ad ? EPT_VLT_WR : 0) |
1332 					  EPT_VLT_LADDR_VLD))
1333 				vmx_inc_test_stage();
1334 			set_ept_pte(pml4, data_page1_pte, 2,
1335 				data_page1_pte_pte | (EPT_PRESENT));
1336 			ept_sync(INVEPT_SINGLE, eptp);
1337 			break;
1338 		case 5:
1339 			if (exit_qual & EPT_VLT_RD)
1340 				vmx_inc_test_stage();
1341 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1342 						1, &memaddr_pte));
1343 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA);
1344 			ept_sync(INVEPT_SINGLE, eptp);
1345 			break;
1346 		case 6:
1347 			if (exit_qual & EPT_VLT_WR)
1348 				vmx_inc_test_stage();
1349 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1350 						1, &memaddr_pte));
1351 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA | EPT_WA);
1352 			ept_sync(INVEPT_SINGLE, eptp);
1353 			break;
1354 		default:
1355 			// Should not reach here
1356 			report("ERROR : unexpected stage, %d", false,
1357 			       vmx_get_test_stage());
1358 			print_vmexit_info();
1359 			return VMX_TEST_VMEXIT;
1360 		}
1361 		return VMX_TEST_RESUME;
1362 	default:
1363 		report("Unknown exit reason, %ld", false, reason);
1364 		print_vmexit_info();
1365 	}
1366 	return VMX_TEST_VMEXIT;
1367 }
1368 
1369 static int ept_exit_handler(void)
1370 {
1371 	return ept_exit_handler_common(false);
1372 }
1373 
1374 static int eptad_init(struct vmcs *vmcs)
1375 {
1376 	int r = ept_init_common(true);
1377 
1378 	if (r == VMX_TEST_EXIT)
1379 		return r;
1380 
1381 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1382 		printf("\tEPT A/D bits are not supported");
1383 		return VMX_TEST_EXIT;
1384 	}
1385 
1386 	return r;
1387 }
1388 
1389 static int pml_init(struct vmcs *vmcs)
1390 {
1391 	u32 ctrl_cpu;
1392 	int r = eptad_init(vmcs);
1393 
1394 	if (r == VMX_TEST_EXIT)
1395 		return r;
1396 
1397 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1398 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1399 		printf("\tPML is not supported");
1400 		return VMX_TEST_EXIT;
1401 	}
1402 
1403 	pml_log = alloc_page();
1404 	memset(pml_log, 0x0, PAGE_SIZE);
1405 	vmcs_write(PMLADDR, (u64)pml_log);
1406 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1407 
1408 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1409 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1410 
1411 	return VMX_TEST_START;
1412 }
1413 
1414 static void pml_main(void)
1415 {
1416 	int count = 0;
1417 
1418 	vmx_set_test_stage(0);
1419 	*((u32 *)data_page2) = 0x1;
1420 	vmcall();
1421 	report("PML - Dirty GPA Logging", vmx_get_test_stage() == 1);
1422 
1423 	while (vmx_get_test_stage() == 1) {
1424 		vmcall();
1425 		*((u32 *)data_page2) = 0x1;
1426 		if (count++ > PML_INDEX)
1427 			break;
1428 	}
1429 	report("PML Full Event", vmx_get_test_stage() == 2);
1430 }
1431 
1432 static void eptad_main(void)
1433 {
1434 	ept_common();
1435 }
1436 
1437 static int eptad_exit_handler(void)
1438 {
1439 	return ept_exit_handler_common(true);
1440 }
1441 
1442 static bool invvpid_test(int type, u16 vpid)
1443 {
1444 	bool ret, supported;
1445 
1446 	supported = ept_vpid.val &
1447 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1448 	ret = invvpid(type, vpid, 0);
1449 
1450 	if (ret == !supported)
1451 		return false;
1452 
1453 	if (!supported)
1454 		printf("WARNING: unsupported invvpid passed!\n");
1455 	else
1456 		printf("WARNING: invvpid failed!\n");
1457 
1458 	return true;
1459 }
1460 
1461 static int vpid_init(struct vmcs *vmcs)
1462 {
1463 	u32 ctrl_cpu1;
1464 
1465 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1466 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1467 		printf("\tVPID is not supported");
1468 		return VMX_TEST_EXIT;
1469 	}
1470 
1471 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1472 	ctrl_cpu1 |= CPU_VPID;
1473 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1474 	return VMX_TEST_START;
1475 }
1476 
1477 static void vpid_main(void)
1478 {
1479 	vmx_set_test_stage(0);
1480 	vmcall();
1481 	report("INVVPID SINGLE ADDRESS", vmx_get_test_stage() == 1);
1482 	vmx_set_test_stage(2);
1483 	vmcall();
1484 	report("INVVPID SINGLE", vmx_get_test_stage() == 3);
1485 	vmx_set_test_stage(4);
1486 	vmcall();
1487 	report("INVVPID ALL", vmx_get_test_stage() == 5);
1488 }
1489 
1490 static int vpid_exit_handler(void)
1491 {
1492 	u64 guest_rip;
1493 	ulong reason;
1494 	u32 insn_len;
1495 
1496 	guest_rip = vmcs_read(GUEST_RIP);
1497 	reason = vmcs_read(EXI_REASON) & 0xff;
1498 	insn_len = vmcs_read(EXI_INST_LEN);
1499 
1500 	switch (reason) {
1501 	case VMX_VMCALL:
1502 		switch(vmx_get_test_stage()) {
1503 		case 0:
1504 			if (!invvpid_test(INVVPID_ADDR, 1))
1505 				vmx_inc_test_stage();
1506 			break;
1507 		case 2:
1508 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1509 				vmx_inc_test_stage();
1510 			break;
1511 		case 4:
1512 			if (!invvpid_test(INVVPID_ALL, 1))
1513 				vmx_inc_test_stage();
1514 			break;
1515 		default:
1516 			report("ERROR: unexpected stage, %d", false,
1517 					vmx_get_test_stage());
1518 			print_vmexit_info();
1519 			return VMX_TEST_VMEXIT;
1520 		}
1521 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1522 		return VMX_TEST_RESUME;
1523 	default:
1524 		report("Unknown exit reason, %ld", false, reason);
1525 		print_vmexit_info();
1526 	}
1527 	return VMX_TEST_VMEXIT;
1528 }
1529 
1530 #define TIMER_VECTOR	222
1531 
1532 static volatile bool timer_fired;
1533 
1534 static void timer_isr(isr_regs_t *regs)
1535 {
1536 	timer_fired = true;
1537 	apic_write(APIC_EOI, 0);
1538 }
1539 
1540 static int interrupt_init(struct vmcs *vmcs)
1541 {
1542 	msr_bmp_init();
1543 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1544 	handle_irq(TIMER_VECTOR, timer_isr);
1545 	return VMX_TEST_START;
1546 }
1547 
1548 static void interrupt_main(void)
1549 {
1550 	long long start, loops;
1551 
1552 	vmx_set_test_stage(0);
1553 
1554 	apic_write(APIC_LVTT, TIMER_VECTOR);
1555 	irq_enable();
1556 
1557 	apic_write(APIC_TMICT, 1);
1558 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1559 		asm volatile ("nop");
1560 	report("direct interrupt while running guest", timer_fired);
1561 
1562 	apic_write(APIC_TMICT, 0);
1563 	irq_disable();
1564 	vmcall();
1565 	timer_fired = false;
1566 	apic_write(APIC_TMICT, 1);
1567 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1568 		asm volatile ("nop");
1569 	report("intercepted interrupt while running guest", timer_fired);
1570 
1571 	irq_enable();
1572 	apic_write(APIC_TMICT, 0);
1573 	irq_disable();
1574 	vmcall();
1575 	timer_fired = false;
1576 	start = rdtsc();
1577 	apic_write(APIC_TMICT, 1000000);
1578 
1579 	asm volatile ("sti; hlt");
1580 
1581 	report("direct interrupt + hlt",
1582 	       rdtsc() - start > 1000000 && timer_fired);
1583 
1584 	apic_write(APIC_TMICT, 0);
1585 	irq_disable();
1586 	vmcall();
1587 	timer_fired = false;
1588 	start = rdtsc();
1589 	apic_write(APIC_TMICT, 1000000);
1590 
1591 	asm volatile ("sti; hlt");
1592 
1593 	report("intercepted interrupt + hlt",
1594 	       rdtsc() - start > 10000 && timer_fired);
1595 
1596 	apic_write(APIC_TMICT, 0);
1597 	irq_disable();
1598 	vmcall();
1599 	timer_fired = false;
1600 	start = rdtsc();
1601 	apic_write(APIC_TMICT, 1000000);
1602 
1603 	irq_enable();
1604 	asm volatile ("nop");
1605 	vmcall();
1606 
1607 	report("direct interrupt + activity state hlt",
1608 	       rdtsc() - start > 10000 && timer_fired);
1609 
1610 	apic_write(APIC_TMICT, 0);
1611 	irq_disable();
1612 	vmcall();
1613 	timer_fired = false;
1614 	start = rdtsc();
1615 	apic_write(APIC_TMICT, 1000000);
1616 
1617 	irq_enable();
1618 	asm volatile ("nop");
1619 	vmcall();
1620 
1621 	report("intercepted interrupt + activity state hlt",
1622 	       rdtsc() - start > 10000 && timer_fired);
1623 
1624 	apic_write(APIC_TMICT, 0);
1625 	irq_disable();
1626 	vmx_set_test_stage(7);
1627 	vmcall();
1628 	timer_fired = false;
1629 	apic_write(APIC_TMICT, 1);
1630 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1631 		asm volatile ("nop");
1632 	report("running a guest with interrupt acknowledgement set", timer_fired);
1633 
1634 	apic_write(APIC_TMICT, 0);
1635 	irq_enable();
1636 	timer_fired = false;
1637 	vmcall();
1638 	report("Inject an event to a halted guest", timer_fired);
1639 }
1640 
1641 static int interrupt_exit_handler(void)
1642 {
1643 	u64 guest_rip = vmcs_read(GUEST_RIP);
1644 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1645 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1646 
1647 	switch (reason) {
1648 	case VMX_VMCALL:
1649 		switch (vmx_get_test_stage()) {
1650 		case 0:
1651 		case 2:
1652 		case 5:
1653 			vmcs_write(PIN_CONTROLS,
1654 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1655 			break;
1656 		case 7:
1657 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1658 			vmcs_write(PIN_CONTROLS,
1659 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1660 			break;
1661 		case 1:
1662 		case 3:
1663 			vmcs_write(PIN_CONTROLS,
1664 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1665 			break;
1666 		case 4:
1667 		case 6:
1668 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1669 			break;
1670 
1671 		case 8:
1672 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1673 			vmcs_write(ENT_INTR_INFO,
1674 				   TIMER_VECTOR |
1675 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1676 				   INTR_INFO_VALID_MASK);
1677 			break;
1678 		}
1679 		vmx_inc_test_stage();
1680 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1681 		return VMX_TEST_RESUME;
1682 	case VMX_EXTINT:
1683 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1684 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1685 			handle_external_interrupt(vector);
1686 		} else {
1687 			irq_enable();
1688 			asm volatile ("nop");
1689 			irq_disable();
1690 		}
1691 		if (vmx_get_test_stage() >= 2)
1692 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1693 		return VMX_TEST_RESUME;
1694 	default:
1695 		report("Unknown exit reason, %ld", false, reason);
1696 		print_vmexit_info();
1697 	}
1698 
1699 	return VMX_TEST_VMEXIT;
1700 }
1701 
1702 static int dbgctls_init(struct vmcs *vmcs)
1703 {
1704 	u64 dr7 = 0x402;
1705 	u64 zero = 0;
1706 
1707 	msr_bmp_init();
1708 	asm volatile(
1709 		"mov %0,%%dr0\n\t"
1710 		"mov %0,%%dr1\n\t"
1711 		"mov %0,%%dr2\n\t"
1712 		"mov %1,%%dr7\n\t"
1713 		: : "r" (zero), "r" (dr7));
1714 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1715 	vmcs_write(GUEST_DR7, 0x404);
1716 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1717 
1718 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1719 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1720 
1721 	return VMX_TEST_START;
1722 }
1723 
1724 static void dbgctls_main(void)
1725 {
1726 	u64 dr7, debugctl;
1727 
1728 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1729 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1730 	/* Commented out: KVM does not support DEBUGCTL so far */
1731 	(void)debugctl;
1732 	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);
1733 
1734 	dr7 = 0x408;
1735 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1736 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1737 
1738 	vmx_set_test_stage(0);
1739 	vmcall();
1740 	report("Save debug controls", vmx_get_test_stage() == 1);
1741 
1742 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1743 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1744 		printf("\tDebug controls are always loaded/saved\n");
1745 		return;
1746 	}
1747 	vmx_set_test_stage(2);
1748 	vmcall();
1749 
1750 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1751 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1752 	/* Commented out: KVM does not support DEBUGCTL so far */
1753 	(void)debugctl;
1754 	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);
1755 
1756 	dr7 = 0x408;
1757 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1758 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1759 
1760 	vmx_set_test_stage(3);
1761 	vmcall();
1762 	report("Don't save debug controls", vmx_get_test_stage() == 4);
1763 }
1764 
1765 static int dbgctls_exit_handler(void)
1766 {
1767 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1768 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1769 	u64 guest_rip = vmcs_read(GUEST_RIP);
1770 	u64 dr7, debugctl;
1771 
1772 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1773 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1774 
1775 	switch (reason) {
1776 	case VMX_VMCALL:
1777 		switch (vmx_get_test_stage()) {
1778 		case 0:
1779 			if (dr7 == 0x400 && debugctl == 0 &&
1780 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1781 			    Commented out: KVM does not support DEBUGCTL so far
1782 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1783 				vmx_inc_test_stage();
1784 			break;
1785 		case 2:
1786 			dr7 = 0x402;
1787 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1788 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1789 			vmcs_write(GUEST_DR7, 0x404);
1790 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1791 
1792 			vmcs_write(ENT_CONTROLS,
1793 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1794 			vmcs_write(EXI_CONTROLS,
1795 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1796 			break;
1797 		case 3:
1798 			if (dr7 == 0x400 && debugctl == 0 &&
1799 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1800 			    Commented out: KVM does not support DEBUGCTL so far
1801 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1802 				vmx_inc_test_stage();
1803 			break;
1804 		}
1805 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1806 		return VMX_TEST_RESUME;
1807 	default:
1808 		report("Unknown exit reason, %d", false, reason);
1809 		print_vmexit_info();
1810 	}
1811 	return VMX_TEST_VMEXIT;
1812 }
1813 
1814 struct vmx_msr_entry {
1815 	u32 index;
1816 	u32 reserved;
1817 	u64 value;
1818 } __attribute__((packed));
1819 
1820 #define MSR_MAGIC 0x31415926
1821 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1822 
1823 static int msr_switch_init(struct vmcs *vmcs)
1824 {
1825 	msr_bmp_init();
1826 	exit_msr_store = alloc_page();
1827 	exit_msr_load = alloc_page();
1828 	entry_msr_load = alloc_page();
1829 	memset(exit_msr_store, 0, PAGE_SIZE);
1830 	memset(exit_msr_load, 0, PAGE_SIZE);
1831 	memset(entry_msr_load, 0, PAGE_SIZE);
1832 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1833 	entry_msr_load[0].value = MSR_MAGIC;
1834 
1835 	vmx_set_test_stage(1);
1836 	vmcs_write(ENT_MSR_LD_CNT, 1);
1837 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1838 	vmcs_write(EXI_MSR_ST_CNT, 1);
1839 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1840 	vmcs_write(EXI_MSR_LD_CNT, 1);
1841 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1842 	return VMX_TEST_START;
1843 }
1844 
1845 static void msr_switch_main(void)
1846 {
1847 	if (vmx_get_test_stage() == 1) {
1848 		report("VM entry MSR load",
1849 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
1850 		vmx_set_test_stage(2);
1851 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1852 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1853 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1854 		exit_msr_load[0].value = MSR_MAGIC + 2;
1855 	}
1856 	vmcall();
1857 }
1858 
1859 static int msr_switch_exit_handler(void)
1860 {
1861 	ulong reason;
1862 
1863 	reason = vmcs_read(EXI_REASON);
1864 	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
1865 		report("VM exit MSR store",
1866 			exit_msr_store[0].value == MSR_MAGIC + 1);
1867 		report("VM exit MSR load",
1868 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
1869 		vmx_set_test_stage(3);
1870 		entry_msr_load[0].index = MSR_FS_BASE;
1871 		return VMX_TEST_RESUME;
1872 	}
1873 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1874 		__func__, vmx_get_test_stage(), reason);
1875 	return VMX_TEST_EXIT;
1876 }
1877 
1878 static int msr_switch_entry_failure(struct vmentry_failure *failure)
1879 {
1880 	ulong reason;
1881 
1882 	if (failure->early) {
1883 		printf("ERROR %s: early exit\n", __func__);
1884 		return VMX_TEST_EXIT;
1885 	}
1886 
1887 	reason = vmcs_read(EXI_REASON);
1888 	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
1889 	    vmx_get_test_stage() == 3) {
1890 		report("VM entry MSR load: try to load FS_BASE",
1891 			vmcs_read(EXI_QUALIFICATION) == 1);
1892 		return VMX_TEST_VMEXIT;
1893 	}
1894 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1895 		__func__, vmx_get_test_stage(), reason);
1896 	return VMX_TEST_EXIT;
1897 }
1898 
1899 static int vmmcall_init(struct vmcs *vmcs)
1900 {
1901 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1902 	return VMX_TEST_START;
1903 }
1904 
1905 static void vmmcall_main(void)
1906 {
1907 	asm volatile(
1908 		"mov $0xABCD, %%rax\n\t"
1909 		"vmmcall\n\t"
1910 		::: "rax");
1911 
1912 	report("VMMCALL", 0);
1913 }
1914 
1915 static int vmmcall_exit_handler(void)
1916 {
1917 	ulong reason;
1918 
1919 	reason = vmcs_read(EXI_REASON);
1920 	switch (reason) {
1921 	case VMX_VMCALL:
1922 		printf("here\n");
1923 		report("VMMCALL triggers #UD", 0);
1924 		break;
1925 	case VMX_EXC_NMI:
1926 		report("VMMCALL triggers #UD",
1927 		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
1928 		break;
1929 	default:
1930 		report("Unknown exit reason, %ld", false, reason);
1931 		print_vmexit_info();
1932 	}
1933 
1934 	return VMX_TEST_VMEXIT;
1935 }
1936 
1937 static int disable_rdtscp_init(struct vmcs *vmcs)
1938 {
1939 	u32 ctrl_cpu1;
1940 
1941 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
1942 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1943 		ctrl_cpu1 &= ~CPU_RDTSCP;
1944 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1945 	}
1946 
1947 	return VMX_TEST_START;
1948 }
1949 
1950 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
1951 {
1952 	switch (vmx_get_test_stage()) {
1953 	case 0:
1954 		report("RDTSCP triggers #UD", true);
1955 		vmx_inc_test_stage();
1956 		regs->rip += 3;
1957 		break;
1958 	case 2:
1959 		report("RDPID triggers #UD", true);
1960 		vmx_inc_test_stage();
1961 		regs->rip += 4;
1962 		break;
1963 	}
1964 	return;
1965 
1966 }
1967 
1968 static void disable_rdtscp_main(void)
1969 {
1970 	/* Test that #UD is properly injected in L2.  */
1971 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
1972 
1973 	vmx_set_test_stage(0);
1974 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
1975 	vmcall();
1976 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
1977 
1978 	handle_exception(UD_VECTOR, 0);
1979 	vmcall();
1980 }
1981 
1982 static int disable_rdtscp_exit_handler(void)
1983 {
1984 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1985 
1986 	switch (reason) {
1987 	case VMX_VMCALL:
1988 		switch (vmx_get_test_stage()) {
1989 		case 0:
1990 			report("RDTSCP triggers #UD", false);
1991 			vmx_inc_test_stage();
1992 			/* fallthrough */
1993 		case 1:
1994 			vmx_inc_test_stage();
1995 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
1996 			return VMX_TEST_RESUME;
1997 		case 2:
1998 			report("RDPID triggers #UD", false);
1999 			break;
2000 		}
2001 		break;
2002 
2003 	default:
2004 		report("Unknown exit reason, %d", false, reason);
2005 		print_vmexit_info();
2006 	}
2007 	return VMX_TEST_VMEXIT;
2008 }
2009 
2010 static int int3_init(struct vmcs *vmcs)
2011 {
2012 	vmcs_write(EXC_BITMAP, ~0u);
2013 	return VMX_TEST_START;
2014 }
2015 
2016 static void int3_guest_main(void)
2017 {
2018 	asm volatile ("int3");
2019 }
2020 
2021 static int int3_exit_handler(void)
2022 {
2023 	u32 reason = vmcs_read(EXI_REASON);
2024 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2025 
2026 	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
2027 	       (intr_info & INTR_INFO_VALID_MASK) &&
2028 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
2029 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2030 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2031 
2032 	return VMX_TEST_VMEXIT;
2033 }
2034 
2035 static int into_init(struct vmcs *vmcs)
2036 {
2037 	vmcs_write(EXC_BITMAP, ~0u);
2038 	return VMX_TEST_START;
2039 }
2040 
2041 static void into_guest_main(void)
2042 {
2043 	struct far_pointer32 fp = {
2044 		.offset = (uintptr_t)&&into,
2045 		.selector = KERNEL_CS32,
2046 	};
2047 	register uintptr_t rsp asm("rsp");
2048 
2049 	if (fp.offset != (uintptr_t)&&into) {
2050 		printf("Code address too high.\n");
2051 		return;
2052 	}
2053 	if ((u32)rsp != rsp) {
2054 		printf("Stack address too high.\n");
2055 		return;
2056 	}
2057 
2058 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2059 	return;
2060 into:
2061 	asm volatile (".code32;"
2062 		      "movl $0x7fffffff, %eax;"
2063 		      "addl %eax, %eax;"
2064 		      "into;"
2065 		      "lret;"
2066 		      ".code64");
2067 	__builtin_unreachable();
2068 }
2069 
2070 static int into_exit_handler(void)
2071 {
2072 	u32 reason = vmcs_read(EXI_REASON);
2073 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2074 
2075 	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
2076 	       (intr_info & INTR_INFO_VALID_MASK) &&
2077 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2078 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2079 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2080 
2081 	return VMX_TEST_VMEXIT;
2082 }
2083 
2084 static void exit_monitor_from_l2_main(void)
2085 {
2086 	printf("Calling exit(0) from l2...\n");
2087 	exit(0);
2088 }
2089 
2090 static int exit_monitor_from_l2_handler(void)
2091 {
2092 	report("The guest should have killed the VMM", false);
2093 	return VMX_TEST_EXIT;
2094 }
2095 
2096 static void assert_exit_reason(u64 expected)
2097 {
2098 	u64 actual = vmcs_read(EXI_REASON);
2099 
2100 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2101 			   exit_reason_description(expected),
2102 			   exit_reason_description(actual));
2103 }
2104 
2105 static void skip_exit_vmcall(void)
2106 {
2107 	u64 guest_rip = vmcs_read(GUEST_RIP);
2108 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2109 
2110 	assert_exit_reason(VMX_VMCALL);
2111 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2112 }
2113 
2114 static void v2_null_test_guest(void)
2115 {
2116 }
2117 
2118 static void v2_null_test(void)
2119 {
2120 	test_set_guest(v2_null_test_guest);
2121 	enter_guest();
2122 	report(__func__, 1);
2123 }
2124 
2125 static void v2_multiple_entries_test_guest(void)
2126 {
2127 	vmx_set_test_stage(1);
2128 	vmcall();
2129 	vmx_set_test_stage(2);
2130 }
2131 
2132 static void v2_multiple_entries_test(void)
2133 {
2134 	test_set_guest(v2_multiple_entries_test_guest);
2135 	enter_guest();
2136 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2137 	skip_exit_vmcall();
2138 	enter_guest();
2139 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2140 	report(__func__, 1);
2141 }
2142 
2143 static int fixture_test_data = 1;
2144 
2145 static void fixture_test_teardown(void *data)
2146 {
2147 	*((int *) data) = 1;
2148 }
2149 
2150 static void fixture_test_guest(void)
2151 {
2152 	fixture_test_data++;
2153 }
2154 
2155 
2156 static void fixture_test_setup(void)
2157 {
2158 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2159 			   "fixture_test_teardown didn't run?!");
2160 	fixture_test_data = 2;
2161 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2162 	test_set_guest(fixture_test_guest);
2163 }
2164 
2165 static void fixture_test_case1(void)
2166 {
2167 	fixture_test_setup();
2168 	TEST_ASSERT_EQ(2, fixture_test_data);
2169 	enter_guest();
2170 	TEST_ASSERT_EQ(3, fixture_test_data);
2171 	report(__func__, 1);
2172 }
2173 
2174 static void fixture_test_case2(void)
2175 {
2176 	fixture_test_setup();
2177 	TEST_ASSERT_EQ(2, fixture_test_data);
2178 	enter_guest();
2179 	TEST_ASSERT_EQ(3, fixture_test_data);
2180 	report(__func__, 1);
2181 }
2182 
2183 enum ept_access_op {
2184 	OP_READ,
2185 	OP_WRITE,
2186 	OP_EXEC,
2187 	OP_FLUSH_TLB,
2188 	OP_EXIT,
2189 };
2190 
2191 static struct ept_access_test_data {
2192 	unsigned long gpa;
2193 	unsigned long *gva;
2194 	unsigned long hpa;
2195 	unsigned long *hva;
2196 	enum ept_access_op op;
2197 } ept_access_test_data;
2198 
2199 extern unsigned char ret42_start;
2200 extern unsigned char ret42_end;
2201 
2202 /* Returns 42. */
2203 asm(
2204 	".align 64\n"
2205 	"ret42_start:\n"
2206 	"mov $42, %eax\n"
2207 	"ret\n"
2208 	"ret42_end:\n"
2209 );
2210 
2211 static void
2212 diagnose_ept_violation_qual(u64 expected, u64 actual)
2213 {
2214 
2215 #define DIAGNOSE(flag)							\
2216 do {									\
2217 	if ((expected & flag) != (actual & flag))			\
2218 		printf(#flag " %sexpected\n",				\
2219 		       (expected & flag) ? "" : "un");			\
2220 } while (0)
2221 
2222 	DIAGNOSE(EPT_VLT_RD);
2223 	DIAGNOSE(EPT_VLT_WR);
2224 	DIAGNOSE(EPT_VLT_FETCH);
2225 	DIAGNOSE(EPT_VLT_PERM_RD);
2226 	DIAGNOSE(EPT_VLT_PERM_WR);
2227 	DIAGNOSE(EPT_VLT_PERM_EX);
2228 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2229 	DIAGNOSE(EPT_VLT_PADDR);
2230 
2231 #undef DIAGNOSE
2232 }
2233 
2234 static void do_ept_access_op(enum ept_access_op op)
2235 {
2236 	ept_access_test_data.op = op;
2237 	enter_guest();
2238 }
2239 
2240 /*
2241  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2242  * needed by tests that modify guest PTEs.
2243  */
2244 static void ept_access_test_guest_flush_tlb(void)
2245 {
2246 	do_ept_access_op(OP_FLUSH_TLB);
2247 	skip_exit_vmcall();
2248 }
2249 
2250 /*
2251  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2252  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2253  * a huge page.
2254  */
2255 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2256 				 unsigned long clear, unsigned long set)
2257 {
2258 	struct ept_access_test_data *data = &ept_access_test_data;
2259 	unsigned long orig_pte;
2260 	unsigned long pte;
2261 
2262 	/* Screw with the mapping at the requested level. */
2263 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2264 	pte = orig_pte;
2265 	if (mkhuge)
2266 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2267 	else
2268 		pte = orig_pte;
2269 	pte = (pte & ~clear) | set;
2270 	set_ept_pte(pml4, gpa, level, pte);
2271 	ept_sync(INVEPT_SINGLE, eptp);
2272 
2273 	return orig_pte;
2274 }
2275 
2276 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2277 {
2278 	set_ept_pte(pml4, gpa, level, orig_pte);
2279 }
2280 
2281 static void do_ept_violation(bool leaf, enum ept_access_op op,
2282 			     u64 expected_qual, u64 expected_paddr)
2283 {
2284 	u64 qual;
2285 
2286 	/* Try the access and observe the violation. */
2287 	do_ept_access_op(op);
2288 
2289 	assert_exit_reason(VMX_EPT_VIOLATION);
2290 
2291 	qual = vmcs_read(EXI_QUALIFICATION);
2292 
2293 	diagnose_ept_violation_qual(expected_qual, qual);
2294 	TEST_EXPECT_EQ(expected_qual, qual);
2295 
2296 	#if 0
2297 	/* Disable for now otherwise every test will fail */
2298 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2299 		       (unsigned long) (
2300 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2301 	#endif
2302 	/*
2303 	 * TODO: tests that probe expected_paddr in pages other than the one at
2304 	 * the beginning of the 1g region.
2305 	 */
2306 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2307 }
2308 
2309 static void
2310 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2311 			      unsigned long set, enum ept_access_op op,
2312 			      u64 expected_qual)
2313 {
2314 	struct ept_access_test_data *data = &ept_access_test_data;
2315 	unsigned long orig_pte;
2316 
2317 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2318 
2319 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2320 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2321 					 data->gpa);
2322 
2323 	/* Fix the violation and resume the op loop. */
2324 	ept_untwiddle(data->gpa, level, orig_pte);
2325 	enter_guest();
2326 	skip_exit_vmcall();
2327 }
2328 
2329 static void
2330 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2331 		       enum ept_access_op op, u64 expected_qual)
2332 {
2333 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2334 				      expected_qual);
2335 	if (ept_huge_pages_supported(level))
2336 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2337 					      expected_qual);
2338 }
2339 
2340 static void ept_violation(unsigned long clear, unsigned long set,
2341 			  enum ept_access_op op, u64 expected_qual)
2342 {
2343 	ept_violation_at_level(1, clear, set, op, expected_qual);
2344 	ept_violation_at_level(2, clear, set, op, expected_qual);
2345 	ept_violation_at_level(3, clear, set, op, expected_qual);
2346 	ept_violation_at_level(4, clear, set, op, expected_qual);
2347 }
2348 
2349 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2350 				       u64 expected_qual)
2351 {
2352 	ept_violation(EPT_PRESENT, access, op,
2353 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2354 }
2355 
2356 /*
2357  * For translations that don't involve a GVA, that is physical address (paddr)
2358  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2359  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2360  * translations don't involve GVAs, such as when the hardware does the guest
2361  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2362  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2363  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2364  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2365  *
2366  * Note that paddr violations can also be triggered by loading PAE page tables
2367  * with wonky addresses. We don't test that yet.
2368  *
2369  * This function modifies the EPT entry that maps the GPA that the guest page
2370  * table entry mapping ept_access_data.gva resides on.
2371  *
2372  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2373  *
2374  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2375  *
2376  *	@op		Guest operation to perform with ept_access_data.gva.
2377  *
2378  *	@expect_violation
2379  *			Is a violation expected during the paddr access?
2380  *
2381  *	@expected_qual	Expected qualification for the EPT violation.
2382  *			EPT_VLT_PADDR should be clear.
2383  */
2384 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2385 			     enum ept_access_op op, bool expect_violation,
2386 			     u64 expected_qual)
2387 {
2388 	struct ept_access_test_data *data = &ept_access_test_data;
2389 	unsigned long *ptep;
2390 	unsigned long gpa;
2391 	unsigned long orig_epte;
2392 
2393 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2394 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2395 	TEST_ASSERT(ptep);
2396 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2397 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2398 	ept_access_test_guest_flush_tlb();
2399 
2400 	/*
2401 	 * Now modify the access bits on the EPT entry for the GPA that the
2402 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2403 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2404 	 * constructed our test such that those other 511 PTEs aren't used by
2405 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2406 	 * PTE we're modifying is at the beginning of a 4K page and the
2407 	 * following 511 entires are also under our control (and not touched by
2408 	 * the guest).
2409 	 */
2410 	gpa = virt_to_phys(ptep);
2411 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2412 	/*
2413 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2414 	 * otherwise our level=1 twiddling below will fail. We use the
2415 	 * identity map (gpa = gpa) since page tables are shared with the host.
2416 	 */
2417 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2418 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2419 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2420 
2421 	if (expect_violation) {
2422 		do_ept_violation(/*leaf=*/true, op,
2423 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2424 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2425 		do_ept_access_op(op);
2426 	} else {
2427 		do_ept_access_op(op);
2428 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2429 	}
2430 
2431 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2432 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2433 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2434 
2435 	skip_exit_vmcall();
2436 }
2437 
2438 static void ept_access_allowed_paddr(unsigned long ept_access,
2439 				     unsigned long pte_ad,
2440 				     enum ept_access_op op)
2441 {
2442 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2443 			 /*expected_qual=*/-1);
2444 }
2445 
2446 static void ept_access_violation_paddr(unsigned long ept_access,
2447 				       unsigned long pte_ad,
2448 				       enum ept_access_op op,
2449 				       u64 expected_qual)
2450 {
2451 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2452 			 expected_qual);
2453 }
2454 
2455 
2456 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2457 					unsigned long clear,
2458 					unsigned long set,
2459 					enum ept_access_op op)
2460 {
2461 	struct ept_access_test_data *data = &ept_access_test_data;
2462 	unsigned long orig_pte;
2463 
2464 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2465 
2466 	/* No violation. Should proceed to vmcall. */
2467 	do_ept_access_op(op);
2468 	skip_exit_vmcall();
2469 
2470 	ept_untwiddle(data->gpa, level, orig_pte);
2471 }
2472 
2473 static void ept_allowed_at_level(int level, unsigned long clear,
2474 				 unsigned long set, enum ept_access_op op)
2475 {
2476 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2477 	if (ept_huge_pages_supported(level))
2478 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2479 }
2480 
2481 static void ept_allowed(unsigned long clear, unsigned long set,
2482 			enum ept_access_op op)
2483 {
2484 	ept_allowed_at_level(1, clear, set, op);
2485 	ept_allowed_at_level(2, clear, set, op);
2486 	ept_allowed_at_level(3, clear, set, op);
2487 	ept_allowed_at_level(4, clear, set, op);
2488 }
2489 
2490 static void ept_ignored_bit(int bit)
2491 {
2492 	/* Set the bit. */
2493 	ept_allowed(0, 1ul << bit, OP_READ);
2494 	ept_allowed(0, 1ul << bit, OP_WRITE);
2495 	ept_allowed(0, 1ul << bit, OP_EXEC);
2496 
2497 	/* Clear the bit. */
2498 	ept_allowed(1ul << bit, 0, OP_READ);
2499 	ept_allowed(1ul << bit, 0, OP_WRITE);
2500 	ept_allowed(1ul << bit, 0, OP_EXEC);
2501 }
2502 
2503 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2504 {
2505 	ept_allowed(EPT_PRESENT, access, op);
2506 }
2507 
2508 
2509 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2510 					     unsigned long clear,
2511 					     unsigned long set,
2512 					     enum ept_access_op op)
2513 {
2514 	struct ept_access_test_data *data = &ept_access_test_data;
2515 	unsigned long orig_pte;
2516 
2517 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2518 
2519 	do_ept_access_op(op);
2520 	assert_exit_reason(VMX_EPT_MISCONFIG);
2521 
2522 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2523 	#if 0
2524 	/* broken: */
2525 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2526 	#endif
2527 	#if 0
2528 	/*
2529 	 * broken:
2530 	 * According to description of exit qual for EPT violation,
2531 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2532 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2533 	 * to be set for msiconfig.
2534 	 */
2535 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2536 		       (unsigned long) (
2537 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2538 	#endif
2539 
2540 	/* Fix the violation and resume the op loop. */
2541 	ept_untwiddle(data->gpa, level, orig_pte);
2542 	enter_guest();
2543 	skip_exit_vmcall();
2544 }
2545 
2546 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2547 					  unsigned long clear,
2548 					  unsigned long set)
2549 {
2550 	/* The op shouldn't matter (read, write, exec), so try them all! */
2551 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2552 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2553 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2554 }
2555 
2556 static void ept_misconfig_at_level(int level, unsigned long clear,
2557 				   unsigned long set)
2558 {
2559 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2560 	if (ept_huge_pages_supported(level))
2561 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2562 }
2563 
2564 static void ept_misconfig(unsigned long clear, unsigned long set)
2565 {
2566 	ept_misconfig_at_level(1, clear, set);
2567 	ept_misconfig_at_level(2, clear, set);
2568 	ept_misconfig_at_level(3, clear, set);
2569 	ept_misconfig_at_level(4, clear, set);
2570 }
2571 
2572 static void ept_access_misconfig(unsigned long access)
2573 {
2574 	ept_misconfig(EPT_PRESENT, access);
2575 }
2576 
2577 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2578 {
2579 	/* Setting the bit causes a misconfig. */
2580 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2581 
2582 	/* Making the entry non-present turns reserved bits into ignored. */
2583 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2584 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2585 }
2586 
2587 static void ept_reserved_bit_at_level_huge(int level, int bit)
2588 {
2589 	/* Setting the bit causes a misconfig. */
2590 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2591 
2592 	/* Making the entry non-present turns reserved bits into ignored. */
2593 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2594 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2595 }
2596 
2597 static void ept_reserved_bit_at_level(int level, int bit)
2598 {
2599 	/* Setting the bit causes a misconfig. */
2600 	ept_misconfig_at_level(level, 0, 1ul << bit);
2601 
2602 	/* Making the entry non-present turns reserved bits into ignored. */
2603 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2604 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2605 }
2606 
2607 static void ept_reserved_bit(int bit)
2608 {
2609 	ept_reserved_bit_at_level(1, bit);
2610 	ept_reserved_bit_at_level(2, bit);
2611 	ept_reserved_bit_at_level(3, bit);
2612 	ept_reserved_bit_at_level(4, bit);
2613 }
2614 
2615 #define PAGE_2M_ORDER 9
2616 #define PAGE_1G_ORDER 18
2617 
2618 static void *get_1g_page(void)
2619 {
2620 	static void *alloc;
2621 
2622 	if (!alloc)
2623 		alloc = alloc_pages(PAGE_1G_ORDER);
2624 	return alloc;
2625 }
2626 
2627 static void ept_access_test_teardown(void *unused)
2628 {
2629 	/* Exit the guest cleanly. */
2630 	do_ept_access_op(OP_EXIT);
2631 }
2632 
2633 static void ept_access_test_guest(void)
2634 {
2635 	struct ept_access_test_data *data = &ept_access_test_data;
2636 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2637 
2638 	while (true) {
2639 		switch (data->op) {
2640 		case OP_READ:
2641 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2642 			break;
2643 		case OP_WRITE:
2644 			*data->gva = MAGIC_VAL_2;
2645 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2646 			*data->gva = MAGIC_VAL_1;
2647 			break;
2648 		case OP_EXEC:
2649 			TEST_ASSERT_EQ(42, code());
2650 			break;
2651 		case OP_FLUSH_TLB:
2652 			write_cr3(read_cr3());
2653 			break;
2654 		case OP_EXIT:
2655 			return;
2656 		default:
2657 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2658 		}
2659 		vmcall();
2660 	}
2661 }
2662 
2663 static void ept_access_test_setup(void)
2664 {
2665 	struct ept_access_test_data *data = &ept_access_test_data;
2666 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2667 	unsigned long size = npages * PAGE_SIZE;
2668 	unsigned long *page_table = current_page_table();
2669 	unsigned long pte;
2670 
2671 	if (setup_ept(false))
2672 		test_skip("EPT not supported");
2673 
2674 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2675 	if (cpuid_maxphyaddr() < 40)
2676 		test_skip("Test needs MAXPHYADDR >= 40");
2677 
2678 	test_set_guest(ept_access_test_guest);
2679 	test_add_teardown(ept_access_test_teardown, NULL);
2680 
2681 	data->hva = get_1g_page();
2682 	TEST_ASSERT(data->hva);
2683 	data->hpa = virt_to_phys(data->hva);
2684 
2685 	data->gpa = 1ul << 39;
2686 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2687 				   size);
2688 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2689 	install_pages(page_table, data->gpa, size, data->gva);
2690 
2691 	/*
2692 	 * Make sure nothing's mapped here so the tests that screw with the
2693 	 * pml4 entry don't inadvertently break something.
2694 	 */
2695 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2696 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2697 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2698 
2699 	data->hva[0] = MAGIC_VAL_1;
2700 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2701 }
2702 
2703 static void ept_access_test_not_present(void)
2704 {
2705 	ept_access_test_setup();
2706 	/* --- */
2707 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2708 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2709 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2710 }
2711 
2712 static void ept_access_test_read_only(void)
2713 {
2714 	ept_access_test_setup();
2715 
2716 	/* r-- */
2717 	ept_access_allowed(EPT_RA, OP_READ);
2718 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2719 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2720 }
2721 
2722 static void ept_access_test_write_only(void)
2723 {
2724 	ept_access_test_setup();
2725 	/* -w- */
2726 	ept_access_misconfig(EPT_WA);
2727 }
2728 
2729 static void ept_access_test_read_write(void)
2730 {
2731 	ept_access_test_setup();
2732 	/* rw- */
2733 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2734 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2735 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2736 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2737 }
2738 
2739 
2740 static void ept_access_test_execute_only(void)
2741 {
2742 	ept_access_test_setup();
2743 	/* --x */
2744 	if (ept_execute_only_supported()) {
2745 		ept_access_violation(EPT_EA, OP_READ,
2746 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2747 		ept_access_violation(EPT_EA, OP_WRITE,
2748 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2749 		ept_access_allowed(EPT_EA, OP_EXEC);
2750 	} else {
2751 		ept_access_misconfig(EPT_EA);
2752 	}
2753 }
2754 
2755 static void ept_access_test_read_execute(void)
2756 {
2757 	ept_access_test_setup();
2758 	/* r-x */
2759 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2760 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2761 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2762 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2763 }
2764 
2765 static void ept_access_test_write_execute(void)
2766 {
2767 	ept_access_test_setup();
2768 	/* -wx */
2769 	ept_access_misconfig(EPT_WA | EPT_EA);
2770 }
2771 
2772 static void ept_access_test_read_write_execute(void)
2773 {
2774 	ept_access_test_setup();
2775 	/* rwx */
2776 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2777 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2778 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2779 }
2780 
2781 static void ept_access_test_reserved_bits(void)
2782 {
2783 	int i;
2784 	int maxphyaddr;
2785 
2786 	ept_access_test_setup();
2787 
2788 	/* Reserved bits above maxphyaddr. */
2789 	maxphyaddr = cpuid_maxphyaddr();
2790 	for (i = maxphyaddr; i <= 51; i++) {
2791 		report_prefix_pushf("reserved_bit=%d", i);
2792 		ept_reserved_bit(i);
2793 		report_prefix_pop();
2794 	}
2795 
2796 	/* Level-specific reserved bits. */
2797 	ept_reserved_bit_at_level_nohuge(2, 3);
2798 	ept_reserved_bit_at_level_nohuge(2, 4);
2799 	ept_reserved_bit_at_level_nohuge(2, 5);
2800 	ept_reserved_bit_at_level_nohuge(2, 6);
2801 	/* 2M alignment. */
2802 	for (i = 12; i < 20; i++) {
2803 		report_prefix_pushf("reserved_bit=%d", i);
2804 		ept_reserved_bit_at_level_huge(2, i);
2805 		report_prefix_pop();
2806 	}
2807 	ept_reserved_bit_at_level_nohuge(3, 3);
2808 	ept_reserved_bit_at_level_nohuge(3, 4);
2809 	ept_reserved_bit_at_level_nohuge(3, 5);
2810 	ept_reserved_bit_at_level_nohuge(3, 6);
2811 	/* 1G alignment. */
2812 	for (i = 12; i < 29; i++) {
2813 		report_prefix_pushf("reserved_bit=%d", i);
2814 		ept_reserved_bit_at_level_huge(3, i);
2815 		report_prefix_pop();
2816 	}
2817 	ept_reserved_bit_at_level(4, 3);
2818 	ept_reserved_bit_at_level(4, 4);
2819 	ept_reserved_bit_at_level(4, 5);
2820 	ept_reserved_bit_at_level(4, 6);
2821 	ept_reserved_bit_at_level(4, 7);
2822 }
2823 
2824 static void ept_access_test_ignored_bits(void)
2825 {
2826 	ept_access_test_setup();
2827 	/*
2828 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2829 	 * far as translation is concerned even if AD bits are enabled in the
2830 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2831 	 * control is 0.
2832 	 */
2833 	ept_ignored_bit(8);
2834 	ept_ignored_bit(9);
2835 	ept_ignored_bit(10);
2836 	ept_ignored_bit(11);
2837 	ept_ignored_bit(52);
2838 	ept_ignored_bit(53);
2839 	ept_ignored_bit(54);
2840 	ept_ignored_bit(55);
2841 	ept_ignored_bit(56);
2842 	ept_ignored_bit(57);
2843 	ept_ignored_bit(58);
2844 	ept_ignored_bit(59);
2845 	ept_ignored_bit(60);
2846 	ept_ignored_bit(61);
2847 	ept_ignored_bit(62);
2848 	ept_ignored_bit(63);
2849 }
2850 
2851 static void ept_access_test_paddr_not_present_ad_disabled(void)
2852 {
2853 	ept_access_test_setup();
2854 	ept_disable_ad_bits();
2855 
2856 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2857 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2858 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2859 }
2860 
2861 static void ept_access_test_paddr_not_present_ad_enabled(void)
2862 {
2863 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2864 
2865 	ept_access_test_setup();
2866 	ept_enable_ad_bits_or_skip_test();
2867 
2868 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2869 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2870 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2871 }
2872 
2873 static void ept_access_test_paddr_read_only_ad_disabled(void)
2874 {
2875 	/*
2876 	 * When EPT AD bits are disabled, all accesses to guest paging
2877 	 * structures are reported separately as a read and (after
2878 	 * translation of the GPA to host physical address) a read+write
2879 	 * if the A/D bits have to be set.
2880 	 */
2881 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2882 
2883 	ept_access_test_setup();
2884 	ept_disable_ad_bits();
2885 
2886 	/* Can't update A bit, so all accesses fail. */
2887 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2888 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2889 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2890 	/* AD bits disabled, so only writes try to update the D bit. */
2891 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
2892 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2893 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
2894 	/* Both A and D already set, so read-only is OK. */
2895 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
2896 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
2897 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
2898 }
2899 
2900 static void ept_access_test_paddr_read_only_ad_enabled(void)
2901 {
2902 	/*
2903 	 * When EPT AD bits are enabled, all accesses to guest paging
2904 	 * structures are considered writes as far as EPT translation
2905 	 * is concerned.
2906 	 */
2907 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2908 
2909 	ept_access_test_setup();
2910 	ept_enable_ad_bits_or_skip_test();
2911 
2912 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2913 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2914 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2915 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
2916 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2917 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
2918 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
2919 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
2920 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
2921 }
2922 
2923 static void ept_access_test_paddr_read_write(void)
2924 {
2925 	ept_access_test_setup();
2926 	/* Read-write access to paging structure. */
2927 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
2928 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
2929 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
2930 }
2931 
2932 static void ept_access_test_paddr_read_write_execute(void)
2933 {
2934 	ept_access_test_setup();
2935 	/* RWX access to paging structure. */
2936 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
2937 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
2938 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
2939 }
2940 
2941 static void ept_access_test_paddr_read_execute_ad_disabled(void)
2942 {
2943   	/*
2944 	 * When EPT AD bits are disabled, all accesses to guest paging
2945 	 * structures are reported separately as a read and (after
2946 	 * translation of the GPA to host physical address) a read+write
2947 	 * if the A/D bits have to be set.
2948 	 */
2949 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2950 
2951 	ept_access_test_setup();
2952 	ept_disable_ad_bits();
2953 
2954 	/* Can't update A bit, so all accesses fail. */
2955 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2956 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2957 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2958 	/* AD bits disabled, so only writes try to update the D bit. */
2959 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
2960 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2961 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
2962 	/* Both A and D already set, so read-only is OK. */
2963 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
2964 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
2965 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
2966 }
2967 
2968 static void ept_access_test_paddr_read_execute_ad_enabled(void)
2969 {
2970 	/*
2971 	 * When EPT AD bits are enabled, all accesses to guest paging
2972 	 * structures are considered writes as far as EPT translation
2973 	 * is concerned.
2974 	 */
2975 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
2976 
2977 	ept_access_test_setup();
2978 	ept_enable_ad_bits_or_skip_test();
2979 
2980 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
2981 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
2982 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
2983 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
2984 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
2985 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
2986 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
2987 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
2988 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
2989 }
2990 
2991 static void ept_access_test_paddr_not_present_page_fault(void)
2992 {
2993 	ept_access_test_setup();
2994 	/*
2995 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
2996 	 * page is read-only in EPT but GVA is also mapped read only in PT.
2997 	 * Thus guest page fault before host takes EPT violation for trying to
2998 	 * update A bit.
2999 	 */
3000 }
3001 
3002 static void ept_access_test_force_2m_page(void)
3003 {
3004 	ept_access_test_setup();
3005 
3006 	TEST_ASSERT_EQ(ept_2m_supported(), true);
3007 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
3008 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
3009 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
3010 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
3011 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
3012 }
3013 
3014 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
3015 {
3016 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3017 
3018 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
3019 
3020 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
3021 		return false;
3022 
3023 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
3024 		return false;
3025 
3026 	if (vpid >> 16)
3027 		return false;
3028 
3029 	if (type != INVVPID_ALL && !vpid)
3030 		return false;
3031 
3032 	if (type == INVVPID_ADDR && !is_canonical(gla))
3033 		return false;
3034 
3035 	return true;
3036 }
3037 
3038 static void try_invvpid(u64 type, u64 vpid, u64 gla)
3039 {
3040 	int rc;
3041 	bool valid = invvpid_valid(type, vpid, gla);
3042 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
3043 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
3044 	/*
3045 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
3046 	 * that we can tell if it is updated by INVVPID.
3047 	 */
3048 	vmcs_read(~0);
3049 	rc = invvpid(type, vpid, gla);
3050 	report("INVVPID type %ld VPID %lx GLA %lx %s",
3051 	       !rc == valid, type, vpid, gla,
3052 	       valid ? "passes" : "fails");
3053 	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3054 	       vmcs_read(VMX_INST_ERROR) == expected,
3055 	       rc ? "failed" : "successful",
3056 	       expected, vmcs_read(VMX_INST_ERROR));
3057 }
3058 
3059 static void ds_invvpid(void *data)
3060 {
3061 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3062 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3063 
3064 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3065 	asm volatile("invvpid %0, %1"
3066 		     :
3067 		     : "m"(*(struct invvpid_operand *)data),
3068 		       "r"(type));
3069 }
3070 
3071 /*
3072  * The SS override is ignored in 64-bit mode, so we use an addressing
3073  * mode with %rsp as the base register to generate an implicit SS
3074  * reference.
3075  */
3076 static void ss_invvpid(void *data)
3077 {
3078 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3079 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3080 
3081 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3082 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3083 		     : "+r"(data)
3084 		     : "r"(type));
3085 }
3086 
3087 static void invvpid_test_gp(void)
3088 {
3089 	bool fault;
3090 
3091 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3092 				   (void *)NONCANONICAL);
3093 	report("INVVPID with non-canonical DS operand raises #GP", fault);
3094 }
3095 
3096 static void invvpid_test_ss(void)
3097 {
3098 	bool fault;
3099 
3100 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3101 				   (void *)NONCANONICAL);
3102 	report("INVVPID with non-canonical SS operand raises #SS", fault);
3103 }
3104 
3105 static void invvpid_test_pf(void)
3106 {
3107 	void *vpage = alloc_vpage();
3108 	bool fault;
3109 
3110 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3111 	report("INVVPID with unmapped operand raises #PF", fault);
3112 }
3113 
3114 static void try_compat_invvpid(void *unused)
3115 {
3116 	struct far_pointer32 fp = {
3117 		.offset = (uintptr_t)&&invvpid,
3118 		.selector = KERNEL_CS32,
3119 	};
3120 	register uintptr_t rsp asm("rsp");
3121 
3122 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3123 			"Code address too high.");
3124 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3125 
3126 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3127 	return;
3128 invvpid:
3129 	asm volatile (".code32;"
3130 		      "invvpid (%eax), %eax;"
3131 		      "lret;"
3132 		      ".code64");
3133 	__builtin_unreachable();
3134 }
3135 
3136 static void invvpid_test_compatibility_mode(void)
3137 {
3138 	bool fault;
3139 
3140 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3141 	report("Compatibility mode INVVPID raises #UD", fault);
3142 }
3143 
3144 static void invvpid_test_not_in_vmx_operation(void)
3145 {
3146 	bool fault;
3147 
3148 	TEST_ASSERT(!vmx_off());
3149 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3150 	report("INVVPID outside of VMX operation raises #UD", fault);
3151 	TEST_ASSERT(!vmx_on());
3152 }
3153 
3154 /*
3155  * This does not test real-address mode, virtual-8086 mode, protected mode,
3156  * or CPL > 0.
3157  */
3158 static void invvpid_test_v2(void)
3159 {
3160 	u64 msr;
3161 	int i;
3162 	unsigned types = 0;
3163 	unsigned type;
3164 
3165 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3166 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3167 		test_skip("VPID not supported");
3168 
3169 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3170 
3171 	if (!(msr & VPID_CAP_INVVPID))
3172 		test_skip("INVVPID not supported.\n");
3173 
3174 	if (msr & VPID_CAP_INVVPID_ADDR)
3175 		types |= 1u << INVVPID_ADDR;
3176 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3177 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3178 	if (msr & VPID_CAP_INVVPID_ALL)
3179 		types |= 1u << INVVPID_ALL;
3180 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3181 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3182 
3183 	if (!types)
3184 		test_skip("No INVVPID types supported.\n");
3185 
3186 	for (i = -127; i < 128; i++)
3187 		try_invvpid(i, 0xffff, 0);
3188 
3189 	/*
3190 	 * VPID must not be more than 16 bits.
3191 	 */
3192 	for (i = 0; i < 64; i++)
3193 		for (type = 0; type < 4; type++)
3194 			if (types & (1u << type))
3195 				try_invvpid(type, 1ul << i, 0);
3196 
3197 	/*
3198 	 * VPID must not be zero, except for "all contexts."
3199 	 */
3200 	for (type = 0; type < 4; type++)
3201 		if (types & (1u << type))
3202 			try_invvpid(type, 0, 0);
3203 
3204 	/*
3205 	 * The gla operand is only validated for single-address INVVPID.
3206 	 */
3207 	if (types & (1u << INVVPID_ADDR))
3208 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3209 
3210 	invvpid_test_gp();
3211 	invvpid_test_ss();
3212 	invvpid_test_pf();
3213 	invvpid_test_compatibility_mode();
3214 	invvpid_test_not_in_vmx_operation();
3215 }
3216 
3217 /*
3218  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3219  * at least as far as the guest-state checks. Returns false if the
3220  * VMLAUNCH fails early and execution falls through to the next
3221  * instruction.
3222  */
3223 static bool vmlaunch_succeeds(void)
3224 {
3225 	/*
3226 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3227 	 * unsupported VMCS component"). The caller can then check
3228 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3229 	 */
3230 	vmcs_write(~0u, 0);
3231 
3232 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3233 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3234 				   :
3235 				   : "r" ((u64)HOST_RSP)
3236 				   : "cc", "memory"
3237 				   : success);
3238 	return false;
3239 success:
3240 	TEST_ASSERT(vmcs_read(EXI_REASON) ==
3241 		    (VMX_FAIL_STATE | VMX_ENTRY_FAILURE));
3242 	return true;
3243 }
3244 
3245 /*
3246  * Try to launch the current VMCS.
3247  */
3248 static void test_vmx_controls(bool controls_valid, bool xfail)
3249 {
3250 	bool success = vmlaunch_succeeds();
3251 	u32 vmx_inst_err;
3252 
3253 	report_xfail("vmlaunch %s", xfail, success == controls_valid,
3254 		     controls_valid ? "succeeds" : "fails");
3255 	if (!success) {
3256 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3257 		report("VMX inst error is %d (actual %d)",
3258 		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
3259 		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
3260 	}
3261 }
3262 
3263 /*
3264  * Test a particular value of a VM-execution control bit, if the value
3265  * is required or if the value is zero.
3266  */
3267 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3268 				    enum Encoding encoding, unsigned bit,
3269 				    unsigned val)
3270 {
3271 	u32 mask = 1u << bit;
3272 	bool expected;
3273 	u32 controls;
3274 
3275 	if (msr.set & mask)
3276 		TEST_ASSERT(msr.clr & mask);
3277 
3278 	/*
3279 	 * We can't arbitrarily turn on a control bit, because it may
3280 	 * introduce dependencies on other VMCS fields. So, we only
3281 	 * test turning on bits that have a required setting.
3282 	 */
3283 	if (val && (msr.clr & mask) && !(msr.set & mask))
3284 		return;
3285 
3286 	report_prefix_pushf("%s %s bit %d",
3287 			    val ? "Set" : "Clear", name, bit);
3288 
3289 	controls = vmcs_read(encoding);
3290 	if (val) {
3291 		vmcs_write(encoding, msr.set | mask);
3292 		expected = (msr.clr & mask);
3293 	} else {
3294 		vmcs_write(encoding, msr.set & ~mask);
3295 		expected = !(msr.set & mask);
3296 	}
3297 	test_vmx_controls(expected, false);
3298 	vmcs_write(encoding, controls);
3299 	report_prefix_pop();
3300 }
3301 
3302 /*
3303  * Test reserved values of a VM-execution control bit, based on the
3304  * allowed bit settings from the corresponding VMX capability MSR.
3305  */
3306 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3307 			      enum Encoding encoding, unsigned bit)
3308 {
3309 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3310 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3311 }
3312 
3313 /*
3314  * Reserved bits in the pin-based VM-execution controls must be set
3315  * properly. Software may consult the VMX capability MSRs to determine
3316  * the proper settings.
3317  * [Intel SDM]
3318  */
3319 static void test_pin_based_ctls(void)
3320 {
3321 	unsigned bit;
3322 
3323 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3324 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3325 	for (bit = 0; bit < 32; bit++)
3326 		test_rsvd_ctl_bit("pin-based controls",
3327 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3328 }
3329 
3330 /*
3331  * Reserved bits in the primary processor-based VM-execution controls
3332  * must be set properly. Software may consult the VMX capability MSRs
3333  * to determine the proper settings.
3334  * [Intel SDM]
3335  */
3336 static void test_primary_processor_based_ctls(void)
3337 {
3338 	unsigned bit;
3339 
3340 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3341 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3342 	for (bit = 0; bit < 32; bit++)
3343 		test_rsvd_ctl_bit("primary processor-based controls",
3344 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3345 }
3346 
3347 /*
3348  * If the "activate secondary controls" primary processor-based
3349  * VM-execution control is 1, reserved bits in the secondary
3350  * processor-based VM-execution controls must be cleared. Software may
3351  * consult the VMX capability MSRs to determine which bits are
3352  * reserved.
3353  * If the "activate secondary controls" primary processor-based
3354  * VM-execution control is 0 (or if the processor does not support the
3355  * 1-setting of that control), no checks are performed on the
3356  * secondary processor-based VM-execution controls.
3357  * [Intel SDM]
3358  */
3359 static void test_secondary_processor_based_ctls(void)
3360 {
3361 	u32 primary;
3362 	u32 secondary;
3363 	unsigned bit;
3364 
3365 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3366 		return;
3367 
3368 	primary = vmcs_read(CPU_EXEC_CTRL0);
3369 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3370 
3371 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3372 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3373 	for (bit = 0; bit < 32; bit++)
3374 		test_rsvd_ctl_bit("secondary processor-based controls",
3375 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3376 
3377 	/*
3378 	 * When the "activate secondary controls" VM-execution control
3379 	 * is clear, there are no checks on the secondary controls.
3380 	 */
3381 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3382 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3383 	report("Secondary processor-based controls ignored",
3384 	       vmlaunch_succeeds());
3385 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3386 	vmcs_write(CPU_EXEC_CTRL0, primary);
3387 }
3388 
3389 static void try_cr3_target_count(unsigned i, unsigned max)
3390 {
3391 	report_prefix_pushf("CR3 target count 0x%x", i);
3392 	vmcs_write(CR3_TARGET_COUNT, i);
3393 	test_vmx_controls(i <= max, false);
3394 	report_prefix_pop();
3395 }
3396 
3397 /*
3398  * The CR3-target count must not be greater than 4. Future processors
3399  * may support a different number of CR3-target values. Software
3400  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3401  * number of values supported.
3402  * [Intel SDM]
3403  */
3404 static void test_cr3_targets(void)
3405 {
3406 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3407 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3408 	unsigned i;
3409 
3410 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3411 	TEST_ASSERT(supported_targets <= 256);
3412 
3413 	try_cr3_target_count(-1u, supported_targets);
3414 	try_cr3_target_count(0x80000000, supported_targets);
3415 	try_cr3_target_count(0x7fffffff, supported_targets);
3416 	for (i = 0; i <= supported_targets + 1; i++)
3417 		try_cr3_target_count(i, supported_targets);
3418 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3419 }
3420 
3421 /*
3422  * Test a particular address setting for a physical page reference in
3423  * the VMCS.
3424  */
3425 static void test_vmcs_page_addr(const char *name,
3426 				enum Encoding encoding,
3427 				bool ignored,
3428 				bool xfail_beyond_mapped_ram,
3429 				u64 addr)
3430 {
3431 	bool xfail =
3432 		(xfail_beyond_mapped_ram &&
3433 		 addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - PAGE_SIZE &&
3434 		 addr < (1ul << cpuid_maxphyaddr()));
3435 
3436 	report_prefix_pushf("%s = %lx", name, addr);
3437 	vmcs_write(encoding, addr);
3438 	test_vmx_controls(ignored || (IS_ALIGNED(addr, PAGE_SIZE) &&
3439 				  addr < (1ul << cpuid_maxphyaddr())),
3440 			  xfail);
3441 	report_prefix_pop();
3442 	xfail = false;
3443 }
3444 
3445 /*
3446  * Test interesting values for a physical page reference in the VMCS.
3447  */
3448 static void test_vmcs_page_values(const char *name,
3449 				  enum Encoding encoding,
3450 				  bool ignored,
3451 				  bool xfail_beyond_mapped_ram)
3452 {
3453 	unsigned i;
3454 	u64 orig_val = vmcs_read(encoding);
3455 
3456 	for (i = 0; i < 64; i++)
3457 		test_vmcs_page_addr(name, encoding, ignored,
3458 				    xfail_beyond_mapped_ram, 1ul << i);
3459 
3460 	test_vmcs_page_addr(name, encoding, ignored,
3461 			    xfail_beyond_mapped_ram, PAGE_SIZE - 1);
3462 	test_vmcs_page_addr(name, encoding, ignored,
3463 			    xfail_beyond_mapped_ram, PAGE_SIZE);
3464 	test_vmcs_page_addr(name, encoding, ignored,
3465 			    xfail_beyond_mapped_ram,
3466 			    (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3467 	test_vmcs_page_addr(name, encoding, ignored,
3468 			    xfail_beyond_mapped_ram,
3469 			    -1ul);
3470 
3471 	vmcs_write(encoding, orig_val);
3472 }
3473 
3474 /*
3475  * Test a physical page reference in the VMCS, when the corresponding
3476  * feature is enabled and when the corresponding feature is disabled.
3477  */
3478 static void test_vmcs_page_reference(u32 control_bit, enum Encoding field,
3479 				     const char *field_name,
3480 				     const char *control_name,
3481 				     bool xfail_beyond_mapped_ram,
3482 				     bool control_primary)
3483 {
3484 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3485 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3486 	u64 page_addr;
3487 
3488 	if (control_primary) {
3489 		if (!(ctrl_cpu_rev[0].clr & control_bit))
3490 			return;
3491 	} else {
3492 		if (!(ctrl_cpu_rev[1].clr & control_bit))
3493 			return;
3494 	}
3495 
3496 	page_addr = vmcs_read(field);
3497 
3498 	report_prefix_pushf("%s enabled", control_name);
3499 	if (control_primary) {
3500 		vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3501 	} else {
3502 		vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3503 		vmcs_write(CPU_EXEC_CTRL1, secondary | control_bit);
3504 	}
3505 	test_vmcs_page_values(field_name, field, false, xfail_beyond_mapped_ram);
3506 	report_prefix_pop();
3507 
3508 	report_prefix_pushf("%s disabled", control_name);
3509 	if (control_primary) {
3510 		vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3511 	} else {
3512 		vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3513 		vmcs_write(CPU_EXEC_CTRL1, secondary & ~control_bit);
3514 	}
3515 	test_vmcs_page_values(field_name, field, true, false);
3516 	report_prefix_pop();
3517 
3518 	vmcs_write(field, page_addr);
3519 	vmcs_write(CPU_EXEC_CTRL0, primary);
3520 }
3521 
3522 /*
3523  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3524  * each I/O-bitmap address must be 0. Neither address should set any
3525  * bits beyond the processor's physical-address width.
3526  * [Intel SDM]
3527  */
3528 static void test_io_bitmaps(void)
3529 {
3530 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3531 				 "I/O bitmap A", "Use I/O bitmaps", false,
3532 				 true);
3533 	test_vmcs_page_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3534 				 "I/O bitmap B", "Use I/O bitmaps", false,
3535 				 true);
3536 }
3537 
3538 /*
3539  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3540  * the MSR-bitmap address must be 0. The address should not set any
3541  * bits beyond the processor's physical-address width.
3542  * [Intel SDM]
3543  */
3544 static void test_msr_bitmap(void)
3545 {
3546 	test_vmcs_page_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3547 				 "MSR bitmap", "Use MSR bitmaps", false,
3548 				 true);
3549 }
3550 
3551 /*
3552  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3553  * address must satisfy the following checks:
3554  * - Bits 11:0 of the address must be 0.
3555  * - The address should not set any bits beyond the processor's
3556  *   physical-address width.
3557  * [Intel SDM]
3558  */
3559 static void test_apic_virt_addr(void)
3560 {
3561 	test_vmcs_page_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3562 				 "virtual-APIC address", "Use TPR shadow",
3563 				 true, true);
3564 }
3565 
3566 /*
3567  * If the "virtualize APIC-accesses" VM-execution control is 1, the
3568  * APIC-access address must satisfy the following checks:
3569  *  - Bits 11:0 of the address must be 0.
3570  *  - The address should not set any bits beyond the processor's
3571  *    physical-address width.
3572  * [Intel SDM]
3573  */
3574 static void test_apic_access_addr(void)
3575 {
3576 	void *apic_access_page = alloc_page();
3577 
3578 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_page));
3579 
3580 	test_vmcs_page_reference(CPU_VIRT_APIC_ACCESSES, APIC_ACCS_ADDR,
3581 				 "APIC-access address",
3582 				 "virtualize APIC-accesses", true, false);
3583 }
3584 
3585 static bool set_bit_pattern(u8 mask, u32 *secondary)
3586 {
3587 	u8 i;
3588 	bool flag = false;
3589 	u32 test_bits[3] = {
3590 		CPU_VIRT_X2APIC,
3591 		CPU_APIC_REG_VIRT,
3592 		CPU_VINTD
3593 	};
3594 
3595         for (i = 0; i < ARRAY_SIZE(test_bits); i++) {
3596 		if ((mask & (1u << i)) &&
3597 		    (ctrl_cpu_rev[1].clr & test_bits[i])) {
3598 			*secondary |= test_bits[i];
3599 			flag = true;
3600 		}
3601 	}
3602 
3603 	return (flag);
3604 }
3605 
3606 /*
3607  * If the "use TPR shadow" VM-execution control is 0, the following
3608  * VM-execution controls must also be 0:
3609  * 	- virtualize x2APIC mode
3610  *	- APIC-register virtualization
3611  *	- virtual-interrupt delivery
3612  *    [Intel SDM]
3613  *
3614  * 2. If the "virtualize x2APIC mode" VM-execution control is 1, the
3615  *    "virtualize APIC accesses" VM-execution control must be 0.
3616  *    [Intel SDM]
3617  */
3618 static void test_apic_virtual_ctls(void)
3619 {
3620 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3621 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3622 	u32 primary = saved_primary;
3623 	u32 secondary = saved_secondary;
3624 	bool ctrl = false;
3625 	char str[10] = "disabled";
3626 	u8 i = 0, j;
3627 
3628 	/*
3629 	 * First test
3630 	 */
3631 	if (!((ctrl_cpu_rev[0].clr & (CPU_SECONDARY | CPU_TPR_SHADOW)) ==
3632 	    (CPU_SECONDARY | CPU_TPR_SHADOW)))
3633 		return;
3634 
3635 	primary |= CPU_SECONDARY;
3636 	primary &= ~CPU_TPR_SHADOW;
3637 	vmcs_write(CPU_EXEC_CTRL0, primary);
3638 
3639 	while (1) {
3640 		for (j = 1; j < 8; j++) {
3641 			secondary &= ~(CPU_VIRT_X2APIC | CPU_APIC_REG_VIRT | CPU_VINTD);
3642 			if (primary & CPU_TPR_SHADOW) {
3643 				ctrl = true;
3644 			} else {
3645 				if (! set_bit_pattern(j, &secondary))
3646 					ctrl = true;
3647 				else
3648 					ctrl = false;
3649 			}
3650 
3651 			vmcs_write(CPU_EXEC_CTRL1, secondary);
3652 			report_prefix_pushf("Use TPR shadow %s, virtualize x2APIC mode %s, APIC-register virtualization %s, virtual-interrupt delivery %s",
3653 				str, (secondary & CPU_VIRT_X2APIC) ? "enabled" : "disabled", (secondary & CPU_APIC_REG_VIRT) ? "enabled" : "disabled", (secondary & CPU_VINTD) ? "enabled" : "disabled");
3654 			test_vmx_controls(ctrl, false);
3655 			report_prefix_pop();
3656 		}
3657 
3658 		if (i == 1)
3659 			break;
3660 		i++;
3661 
3662 		primary |= CPU_TPR_SHADOW;
3663 		vmcs_write(CPU_EXEC_CTRL0, primary);
3664 		strcpy(str, "enabled");
3665 	}
3666 
3667 	/*
3668 	 * Second test
3669 	 */
3670 	u32 apic_virt_ctls = (CPU_VIRT_X2APIC | CPU_VIRT_APIC_ACCESSES);
3671 
3672 	primary = saved_primary;
3673 	secondary = saved_secondary;
3674 	if (!((ctrl_cpu_rev[1].clr & apic_virt_ctls) == apic_virt_ctls))
3675 		return;
3676 
3677 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3678 	secondary &= ~CPU_VIRT_APIC_ACCESSES;
3679 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_X2APIC);
3680 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access disabled");
3681 	test_vmx_controls(true, false);
3682 	report_prefix_pop();
3683 
3684 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_APIC_ACCESSES);
3685 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access enabled");
3686 	test_vmx_controls(true, false);
3687 	report_prefix_pop();
3688 
3689 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_X2APIC);
3690 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access enabled");
3691 	test_vmx_controls(false, false);
3692 	report_prefix_pop();
3693 
3694 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_APIC_ACCESSES);
3695 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access disabled");
3696 	test_vmx_controls(true, false);
3697 	report_prefix_pop();
3698 
3699 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3700 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3701 }
3702 
3703 static void test_apic_ctls(void)
3704 {
3705 	test_apic_virt_addr();
3706 	test_apic_access_addr();
3707 	test_apic_virtual_ctls();
3708 }
3709 
3710 static void set_vtpr(unsigned vtpr)
3711 {
3712 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
3713 }
3714 
3715 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
3716 {
3717 	bool valid = true;
3718 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3719 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3720 
3721 	if ((primary & CPU_TPR_SHADOW) &&
3722 	    (!(primary & CPU_SECONDARY) ||
3723 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
3724 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
3725 
3726 	set_vtpr(vtpr);
3727 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
3728 	    threshold, (vtpr >> 4) & 0xf);
3729 	test_vmx_controls(valid, false);
3730 	report_prefix_pop();
3731 }
3732 
3733 static void test_invalid_event_injection(void)
3734 {
3735 	u32 ent_intr_info_save = vmcs_read(ENT_INTR_INFO);
3736 	u32 ent_intr_error_save = vmcs_read(ENT_INTR_ERROR);
3737 	u32 ent_inst_len_save = vmcs_read(ENT_INST_LEN);
3738 	u32 primary_save = vmcs_read(CPU_EXEC_CTRL0);
3739 	u32 secondary_save = vmcs_read(CPU_EXEC_CTRL1);
3740 	u64 guest_cr0_save = vmcs_read(GUEST_CR0);
3741 	u32 ent_intr_info_base = INTR_INFO_VALID_MASK;
3742 	u32 ent_intr_info, ent_intr_err, ent_intr_len;
3743 	u32 cnt;
3744 
3745 	/* Setup */
3746 	report_prefix_push("invalid event injection");
3747 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
3748 	vmcs_write(ENT_INST_LEN, 0x00000001);
3749 
3750 	/* The field’s interruption type is not set to a reserved value. */
3751 	ent_intr_info = ent_intr_info_base | INTR_TYPE_RESERVED | DE_VECTOR;
3752 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3753 			    "RESERVED interruption type invalid [-]",
3754 			    ent_intr_info);
3755 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3756 	test_vmx_controls(false, false);
3757 	report_prefix_pop();
3758 
3759 	ent_intr_info = ent_intr_info_base | INTR_TYPE_EXT_INTR |
3760 			DE_VECTOR;
3761 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3762 			    "RESERVED interruption type invalid [+]",
3763 			    ent_intr_info);
3764 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3765 	test_vmx_controls(true, false);
3766 	report_prefix_pop();
3767 
3768 	/* If the interruption type is other event, the vector is 0. */
3769 	ent_intr_info = ent_intr_info_base | INTR_TYPE_OTHER_EVENT | DB_VECTOR;
3770 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3771 			    "(OTHER EVENT && vector != 0) invalid [-]",
3772 			    ent_intr_info);
3773 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3774 	test_vmx_controls(false, false);
3775 	report_prefix_pop();
3776 
3777 	/* If the interruption type is NMI, the vector is 2 (negative case). */
3778 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | DE_VECTOR;
3779 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3780 			    "(NMI && vector != 2) invalid [-]", ent_intr_info);
3781 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3782 	test_vmx_controls(false, false);
3783 	report_prefix_pop();
3784 
3785 	/* If the interruption type is NMI, the vector is 2 (positive case). */
3786 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | NMI_VECTOR;
3787 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3788 			    "(NMI && vector == 2) valid [+]", ent_intr_info);
3789 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3790 	test_vmx_controls(true, false);
3791 	report_prefix_pop();
3792 
3793 	/*
3794 	 * If the interruption type
3795 	 * is HW exception, the vector is at most 31.
3796 	 */
3797 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION | 0x20;
3798 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3799 			    "(HW exception && vector > 31) invalid [-]",
3800 			    ent_intr_info);
3801 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3802 	test_vmx_controls(false, false);
3803 	report_prefix_pop();
3804 
3805 	/*
3806 	 * deliver-error-code is 1 iff either
3807 	 * (a) the "unrestricted guest" VM-execution control is 0
3808 	 * (b) CR0.PE is set.
3809 	 */
3810 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
3811 			GP_VECTOR;
3812 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3813 			    "error code <-> (!URG || prot_mode) [-]",
3814 			    ent_intr_info);
3815 	disable_unrestricted_guest();
3816 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
3817 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3818 	test_vmx_controls(false, false);
3819 	report_prefix_pop();
3820 
3821 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
3822 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
3823 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3824 			    "error code <-> (!URG || prot_mode) [+]",
3825 			    ent_intr_info);
3826 	disable_unrestricted_guest();
3827 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
3828 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3829 	test_vmx_controls(true, false);
3830 	report_prefix_pop();
3831 
3832 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
3833 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
3834 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3835 			    "error code <-> (!URG || prot_mode) [-]",
3836 			    ent_intr_info);
3837 	enable_unrestricted_guest();
3838 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
3839 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3840 	test_vmx_controls(false, false);
3841 	report_prefix_pop();
3842 
3843 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
3844 			GP_VECTOR;
3845 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3846 			    "error code <-> (!URG || prot_mode) [-]",
3847 			    ent_intr_info);
3848 	vmcs_write(GUEST_CR0, guest_cr0_save | X86_CR0_PE);
3849 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3850 	test_vmx_controls(false, false);
3851 	report_prefix_pop();
3852 
3853 	/* deliver-error-code is 1 iff the interruption type is HW exception */
3854 	report_prefix_push("error code <-> HW exception");
3855 	for (cnt = 0; cnt < 8; cnt++) {
3856 		u32 exception_type_mask = cnt << 8;
3857 		u32 deliver_error_code_mask =
3858 			exception_type_mask != INTR_TYPE_HARD_EXCEPTION ?
3859 			INTR_INFO_DELIVER_CODE_MASK : 0;
3860 
3861 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
3862 				exception_type_mask | GP_VECTOR;
3863 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
3864 				    ent_intr_info);
3865 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
3866 		test_vmx_controls(false, false);
3867 		report_prefix_pop();
3868 	}
3869 	report_prefix_pop();
3870 
3871 	/*
3872 	 * deliver-error-code is 1 iff the the vector
3873 	 * indicates an exception that would normally deliver an error code
3874 	 */
3875 	report_prefix_push("error code <-> vector delivers error code");
3876 	for (cnt = 0; cnt < 32; cnt++) {
3877 		bool has_error_code = false;
3878 		u32 deliver_error_code_mask;
3879 
3880 		switch (cnt) {
3881 		case DF_VECTOR:
3882 		case TS_VECTOR:
3883 		case NP_VECTOR:
3884 		case SS_VECTOR:
3885 		case GP_VECTOR:
3886 		case PF_VECTOR:
3887 		case AC_VECTOR:
3888 			has_error_code = true;
3889 		}
3890 
3891 		/* Negative case */
3892 		deliver_error_code_mask = has_error_code ?
3893 						0 :
3894 						INTR_INFO_DELIVER_CODE_MASK;
3895 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
3896 				INTR_TYPE_HARD_EXCEPTION | cnt;
3897 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
3898 				    ent_intr_info);
3899 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
3900 		test_vmx_controls(false, false);
3901 		report_prefix_pop();
3902 
3903 		/* Positive case */
3904 		deliver_error_code_mask = has_error_code ?
3905 						INTR_INFO_DELIVER_CODE_MASK :
3906 						0;
3907 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
3908 				INTR_TYPE_HARD_EXCEPTION | cnt;
3909 		report_prefix_pushf("VM-entry intr info=0x%x [+]",
3910 				    ent_intr_info);
3911 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
3912 		test_vmx_controls(true, false);
3913 		report_prefix_pop();
3914 	}
3915 	report_prefix_pop();
3916 
3917 	/* Reserved bits in the field (30:12) are 0. */
3918 	report_prefix_push("reserved bits clear");
3919 	for (cnt = 12; cnt <= 30; cnt++) {
3920 		ent_intr_info = ent_intr_info_base |
3921 				INTR_INFO_DELIVER_CODE_MASK |
3922 				INTR_TYPE_HARD_EXCEPTION | GP_VECTOR |
3923 				(1U << cnt);
3924 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
3925 				    ent_intr_info);
3926 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
3927 		test_vmx_controls(false, false);
3928 		report_prefix_pop();
3929 	}
3930 	report_prefix_pop();
3931 
3932 	/*
3933 	 * If deliver-error-code is 1
3934 	 * bits 31:15 of the VM-entry exception error-code field are 0.
3935 	 */
3936 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
3937 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
3938 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
3939 			    "VM-entry exception error code[31:15] clear",
3940 			    ent_intr_info);
3941 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
3942 	for (cnt = 15; cnt <= 31; cnt++) {
3943 		ent_intr_err = 1U << cnt;
3944 		report_prefix_pushf("VM-entry intr error=0x%x [-]",
3945 				    ent_intr_err);
3946 		vmcs_write(ENT_INTR_ERROR, ent_intr_err);
3947 		test_vmx_controls(false, false);
3948 		report_prefix_pop();
3949 	}
3950 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
3951 	report_prefix_pop();
3952 
3953 	/*
3954 	 * If the interruption type is software interrupt, software exception,
3955 	 * or privileged software exception, the VM-entry instruction-length
3956 	 * field is in the range 0–15.
3957 	 */
3958 
3959 	for (cnt = 0; cnt < 3; cnt++) {
3960 		switch (cnt) {
3961 		case 0:
3962 			ent_intr_info = ent_intr_info_base |
3963 					INTR_TYPE_SOFT_INTR;
3964 			break;
3965 		case 1:
3966 			ent_intr_info = ent_intr_info_base |
3967 					INTR_TYPE_SOFT_EXCEPTION;
3968 			break;
3969 		case 2:
3970 			ent_intr_info = ent_intr_info_base |
3971 					INTR_TYPE_PRIV_SW_EXCEPTION;
3972 			break;
3973 		}
3974 		report_prefix_pushf("%s, VM-entry intr info=0x%x",
3975 				    "VM-entry instruction-length check",
3976 				    ent_intr_info);
3977 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
3978 
3979 		/* Instruction length set to -1 (0xFFFFFFFF) should fail */
3980 		ent_intr_len = -1;
3981 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
3982 				    ent_intr_len);
3983 		vmcs_write(ENT_INST_LEN, ent_intr_len);
3984 		test_vmx_controls(false, false);
3985 		report_prefix_pop();
3986 
3987 		/* Instruction length set to 16 should fail */
3988 		ent_intr_len = 0x00000010;
3989 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
3990 				    ent_intr_len);
3991 		vmcs_write(ENT_INST_LEN, 0x00000010);
3992 		test_vmx_controls(false, false);
3993 		report_prefix_pop();
3994 
3995 		report_prefix_pop();
3996 	}
3997 
3998 	/* Cleanup */
3999 	vmcs_write(ENT_INTR_INFO, ent_intr_info_save);
4000 	vmcs_write(ENT_INTR_ERROR, ent_intr_error_save);
4001 	vmcs_write(ENT_INST_LEN, ent_inst_len_save);
4002 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4003 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4004 	vmcs_write(GUEST_CR0, guest_cr0_save);
4005 	report_prefix_pop();
4006 }
4007 
4008 /*
4009  * Test interesting vTPR values for a given TPR threshold.
4010  */
4011 static void test_vtpr_values(unsigned threshold)
4012 {
4013 	try_tpr_threshold_and_vtpr(threshold, threshold - 1);
4014 	try_tpr_threshold_and_vtpr(threshold, threshold);
4015 	try_tpr_threshold_and_vtpr(threshold, threshold + 1);
4016 }
4017 
4018 static void try_tpr_threshold(unsigned threshold)
4019 {
4020 	bool valid = true;
4021 
4022 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4023 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4024 
4025 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
4026 	    (secondary & CPU_VINTD)))
4027 		valid = !(threshold >> 4);
4028 
4029 	set_vtpr(-1);
4030 	vmcs_write(TPR_THRESHOLD, threshold);
4031 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
4032 	test_vmx_controls(valid, false);
4033 	report_prefix_pop();
4034 
4035 	if (valid)
4036 		test_vtpr_values(threshold);
4037 }
4038 
4039 /*
4040  * Test interesting TPR threshold values.
4041  */
4042 static void test_tpr_threshold_values(void)
4043 {
4044 	unsigned i;
4045 
4046 	for (i = 0; i < 0x10; i++)
4047 		try_tpr_threshold(i);
4048 	for (i = 4; i < 32; i++)
4049 		try_tpr_threshold(1u << i);
4050 	try_tpr_threshold(-1u);
4051 	try_tpr_threshold(0x7fffffff);
4052 }
4053 
4054 /*
4055  * This test covers the following two VM entry checks:
4056  *
4057  *      i) If the "use TPR shadow" VM-execution control is 1 and the
4058  *         "virtual-interrupt delivery" VM-execution control is 0, bits
4059  *         31:4 of the TPR threshold VM-execution control field must
4060 	   be 0.
4061  *         [Intel SDM]
4062  *
4063  *      ii) If the "use TPR shadow" VM-execution control is 1, the
4064  *          "virtual-interrupt delivery" VM-execution control is 0
4065  *          and the "virtualize APIC accesses" VM-execution control
4066  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
4067  *          control field must not be greater than the value of bits
4068  *          7:4 of VTPR.
4069  *          [Intel SDM]
4070  */
4071 static void test_tpr_threshold(void)
4072 {
4073 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4074 	void *virtual_apic_page;
4075 
4076 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
4077 		return;
4078 
4079 	virtual_apic_page = alloc_page();
4080 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
4081 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
4082 
4083 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
4084 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
4085 	test_tpr_threshold_values();
4086 	report_prefix_pop();
4087 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
4088 	report_prefix_pushf("Use TPR shadow enabled");
4089 	test_tpr_threshold_values();
4090 	report_prefix_pop();
4091 
4092 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4093 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES))))
4094 		return;
4095 
4096 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4097 
4098 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
4099 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
4100 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4101 		test_tpr_threshold_values();
4102 		report_prefix_pop();
4103 
4104 		vmcs_write(CPU_EXEC_CTRL0,
4105 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4106 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4107 		test_tpr_threshold_values();
4108 		report_prefix_pop();
4109 	}
4110 
4111 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
4112 		vmcs_write(CPU_EXEC_CTRL0,
4113 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4114 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
4115 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4116 		test_tpr_threshold_values();
4117 		report_prefix_pop();
4118 
4119 		vmcs_write(CPU_EXEC_CTRL0,
4120 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4121 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4122 		test_tpr_threshold_values();
4123 		report_prefix_pop();
4124 	}
4125 
4126 	if ((ctrl_cpu_rev[1].clr &
4127 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
4128 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
4129 		vmcs_write(CPU_EXEC_CTRL0,
4130 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4131 		vmcs_write(CPU_EXEC_CTRL1,
4132 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
4133 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4134 		test_tpr_threshold_values();
4135 		report_prefix_pop();
4136 
4137 		vmcs_write(CPU_EXEC_CTRL0,
4138 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4139 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4140 		test_tpr_threshold_values();
4141 		report_prefix_pop();
4142 	}
4143 
4144 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4145 	vmcs_write(CPU_EXEC_CTRL0, primary);
4146 }
4147 
4148 /*
4149  * This test verifies the following two vmentry checks:
4150  *
4151  *  If the "NMI exiting" VM-execution control is 0, "Virtual NMIs"
4152  *  VM-execution control must be 0.
4153  *  [Intel SDM]
4154  *
4155  *  If the “virtual NMIs” VM-execution control is 0, the “NMI-window
4156  *  exiting” VM-execution control must be 0.
4157  *  [Intel SDM]
4158  */
4159 static void test_nmi_ctrls(void)
4160 {
4161 	u32 pin_ctrls, cpu_ctrls0, test_pin_ctrls, test_cpu_ctrls0;
4162 
4163 	if ((ctrl_pin_rev.clr & (PIN_NMI | PIN_VIRT_NMI)) !=
4164 	    (PIN_NMI | PIN_VIRT_NMI)) {
4165 		test_skip("NMI exiting and Virtual NMIs are not supported !");
4166 		return;
4167 	}
4168 
4169 	/* Save the controls so that we can restore them after our tests */
4170 	pin_ctrls = vmcs_read(PIN_CONTROLS);
4171 	cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
4172 
4173 	test_pin_ctrls = pin_ctrls & ~(PIN_NMI | PIN_VIRT_NMI);
4174 	test_cpu_ctrls0 = cpu_ctrls0 & ~CPU_NMI_WINDOW;
4175 
4176 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4177 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs disabled");
4178 	test_vmx_controls(true, false);
4179 	report_prefix_pop();
4180 
4181 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_VIRT_NMI);
4182 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs enabled");
4183 	test_vmx_controls(false, false);
4184 	report_prefix_pop();
4185 
4186 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4187 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs enabled");
4188 	test_vmx_controls(true, false);
4189 	report_prefix_pop();
4190 
4191 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_NMI);
4192 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs disabled");
4193 	test_vmx_controls(true, false);
4194 	report_prefix_pop();
4195 
4196 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
4197 		report_info("NMI-window exiting is not supported, skipping...");
4198 		goto done;
4199 	}
4200 
4201 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4202 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4203 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting enabled");
4204 	test_vmx_controls(false, false);
4205 	report_prefix_pop();
4206 
4207 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4208 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4209 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting disabled");
4210 	test_vmx_controls(true, false);
4211 	report_prefix_pop();
4212 
4213 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4214 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4215 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting enabled");
4216 	test_vmx_controls(true, false);
4217 	report_prefix_pop();
4218 
4219 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4220 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4221 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting disabled");
4222 	test_vmx_controls(true, false);
4223 	report_prefix_pop();
4224 
4225 	/* Restore the controls to their original values */
4226 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
4227 done:
4228 	vmcs_write(PIN_CONTROLS, pin_ctrls);
4229 }
4230 
4231 
4232 /*
4233  * Check that the virtual CPU checks all of the VMX controls as
4234  * documented in the Intel SDM.
4235  */
4236 static void vmx_controls_test(void)
4237 {
4238 	/*
4239 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
4240 	 * fail due to invalid guest state, should we make it that
4241 	 * far.
4242 	 */
4243 	vmcs_write(GUEST_RFLAGS, 0);
4244 
4245 	test_pin_based_ctls();
4246 	test_primary_processor_based_ctls();
4247 	test_secondary_processor_based_ctls();
4248 	test_cr3_targets();
4249 	test_io_bitmaps();
4250 	test_msr_bitmap();
4251 	test_apic_ctls();
4252 	test_tpr_threshold();
4253 	test_nmi_ctrls();
4254 	test_invalid_event_injection();
4255 }
4256 
4257 static bool valid_vmcs_for_vmentry(void)
4258 {
4259 	struct vmcs *current_vmcs = NULL;
4260 
4261 	if (vmcs_save(&current_vmcs))
4262 		return false;
4263 
4264 	return current_vmcs && !(current_vmcs->revision_id >> 31);
4265 }
4266 
4267 static void try_vmentry_in_movss_shadow(void)
4268 {
4269 	u32 vm_inst_err;
4270 	u32 flags;
4271 	bool early_failure = false;
4272 	u32 expected_flags = X86_EFLAGS_FIXED;
4273 	bool valid_vmcs = valid_vmcs_for_vmentry();
4274 
4275 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
4276 
4277 	/*
4278 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
4279 	 * unsupported VMCS component").
4280 	 */
4281 	vmcs_write(~0u, 0);
4282 
4283 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
4284 			      "vmwrite %%rsp, %%rdx;"
4285 			      "mov 0f, %%rax;"
4286 			      "mov %[host_rip], %%edx;"
4287 			      "vmwrite %%rax, %%rdx;"
4288 			      "mov $-1, %%ah;"
4289 			      "sahf;"
4290 			      "mov %%ss, %%ax;"
4291 			      "mov %%ax, %%ss;"
4292 			      "vmlaunch;"
4293 			      "mov $1, %[early_failure];"
4294 			      "0: lahf;"
4295 			      "movzbl %%ah, %[flags]"
4296 			      : [early_failure] "+r" (early_failure),
4297 				[flags] "=&a" (flags)
4298 			      : [host_rsp] "i" (HOST_RSP),
4299 				[host_rip] "i" (HOST_RIP)
4300 			      : "rdx", "cc", "memory");
4301 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
4302 
4303 	report("Early VM-entry failure", early_failure);
4304 	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
4305 	       expected_flags, flags);
4306 	if (valid_vmcs)
4307 		report("VM-instruction error is %d (actual %d)",
4308 		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
4309 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
4310 }
4311 
4312 static void vmentry_movss_shadow_test(void)
4313 {
4314 	struct vmcs *orig_vmcs;
4315 
4316 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
4317 
4318 	/*
4319 	 * Set the launched flag on the current VMCS to verify the correct
4320 	 * error priority, below.
4321 	 */
4322 	test_set_guest(v2_null_test_guest);
4323 	enter_guest();
4324 
4325 	/*
4326 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
4327 	 * fail due to invalid guest state (if we make it that far).
4328 	 */
4329 	vmcs_write(GUEST_RFLAGS, 0);
4330 
4331 	/*
4332 	 * "VM entry with events blocked by MOV SS" takes precedence over
4333 	 * "VMLAUNCH with non-clear VMCS."
4334 	 */
4335 	report_prefix_push("valid current-VMCS");
4336 	try_vmentry_in_movss_shadow();
4337 	report_prefix_pop();
4338 
4339 	/*
4340 	 * VMfailInvalid takes precedence over "VM entry with events
4341 	 * blocked by MOV SS."
4342 	 */
4343 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
4344 	report_prefix_push("no current-VMCS");
4345 	try_vmentry_in_movss_shadow();
4346 	report_prefix_pop();
4347 
4348 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
4349 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
4350 }
4351 
4352 #define X86_FEATURE_PCID       (1 << 17)
4353 #define X86_FEATURE_MCE        (1 << 7)
4354 
4355 static int write_cr4_checking(unsigned long val)
4356 {
4357 	asm volatile(ASM_TRY("1f")
4358 		     "mov %0, %%cr4\n\t"
4359 		     "1:": : "r" (val));
4360 	return exception_vector();
4361 }
4362 
4363 static void vmx_cr_load_test(void)
4364 {
4365 	struct cpuid _cpuid = cpuid(1);
4366 	unsigned long cr4 = read_cr4(), cr3 = read_cr3();
4367 
4368 	if (!(_cpuid.c & X86_FEATURE_PCID)) {
4369 		report_skip("PCID not detected");
4370 		return;
4371 	}
4372 	if (!(_cpuid.d & X86_FEATURE_MCE)) {
4373 		report_skip("MCE not detected");
4374 		return;
4375 	}
4376 
4377 	TEST_ASSERT(!(cr4 & (X86_CR4_PCIDE | X86_CR4_MCE)));
4378 	TEST_ASSERT(!(cr3 & X86_CR3_PCID_MASK));
4379 
4380 	/* Enable PCID for L1. */
4381 	cr4 |= X86_CR4_PCIDE;
4382 	cr3 |= 0x1;
4383 	TEST_ASSERT(!write_cr4_checking(cr4));
4384 	write_cr3(cr3);
4385 
4386 	test_set_guest(v2_null_test_guest);
4387 	vmcs_write(HOST_CR4, cr4);
4388 	vmcs_write(HOST_CR3, cr3);
4389 	enter_guest();
4390 
4391 	/*
4392 	 * No exception is expected.
4393 	 *
4394 	 * NB. KVM loads the last guest write to CR4 into CR4 read
4395 	 *     shadow. In order to trigger an exit to KVM, we can set a
4396 	 *     bit that was zero in the above CR4 write and is owned by
4397 	 *     KVM. We choose to set CR4.MCE, which shall have no side
4398 	 *     effect because normally no guest MCE (e.g., as the result
4399 	 *     of bad memory) would happen during this test.
4400 	 */
4401 	TEST_ASSERT(!write_cr4_checking(cr4 | X86_CR4_MCE));
4402 
4403 	/* Cleanup L1 state: disable PCID. */
4404 	write_cr3(cr3 & ~X86_CR3_PCID_MASK);
4405 	TEST_ASSERT(!write_cr4_checking(cr4 & ~X86_CR4_PCIDE));
4406 }
4407 
4408 static bool cpu_has_apicv(void)
4409 {
4410 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
4411 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
4412 		(ctrl_pin_rev.clr & PIN_POST_INTR));
4413 }
4414 
4415 static void trigger_ioapic_scan_thread(void *data)
4416 {
4417 	/* Wait until other CPU entered L2 */
4418 	while (vmx_get_test_stage() != 1)
4419 		;
4420 
4421 	/* Trigger ioapic scan */
4422 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
4423 	vmx_set_test_stage(2);
4424 }
4425 
4426 static void irq_79_handler_guest(isr_regs_t *regs)
4427 {
4428 	eoi();
4429 
4430 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
4431 	vmcall();
4432 }
4433 
4434 /*
4435  * Constant for num of busy-loop iterations after which
4436  * a timer interrupt should have happened in host
4437  */
4438 #define TIMER_INTERRUPT_DELAY 100000000
4439 
4440 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
4441 {
4442 	handle_irq(0x79, irq_79_handler_guest);
4443 	irq_enable();
4444 
4445 	/* Signal to L1 CPU to trigger ioapic scan */
4446 	vmx_set_test_stage(1);
4447 	/* Wait until L1 CPU to trigger ioapic scan */
4448 	while (vmx_get_test_stage() != 2)
4449 		;
4450 
4451 	/*
4452 	 * Wait for L0 timer interrupt to be raised while we run in L2
4453 	 * such that L0 will process the IOAPIC scan request before
4454 	 * resuming L2
4455 	 */
4456 	delay(TIMER_INTERRUPT_DELAY);
4457 
4458 	asm volatile ("int $0x79");
4459 }
4460 
4461 static void vmx_eoi_bitmap_ioapic_scan_test(void)
4462 {
4463 	void *msr_bitmap;
4464 	void *virtual_apic_page;
4465 
4466 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
4467 		report_skip(__func__);
4468 		return;
4469 	}
4470 
4471 	msr_bitmap = alloc_page();
4472 	virtual_apic_page = alloc_page();
4473 
4474 	u64 cpu_ctrl_0 = CPU_SECONDARY | CPU_TPR_SHADOW | CPU_MSR_BITMAP;
4475 	u64 cpu_ctrl_1 = CPU_VINTD | CPU_VIRT_X2APIC;
4476 
4477 	memset(msr_bitmap, 0x0, PAGE_SIZE);
4478 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
4479 
4480 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
4481 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
4482 
4483 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
4484 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
4485 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
4486 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
4487 
4488 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
4489 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
4490 
4491 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
4492 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
4493 
4494 	/*
4495 	 * Launch L2.
4496 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
4497 	 * In case the reason isn't VMX_VMCALL, the asserion inside
4498 	 * skip_exit_vmcall() will fail.
4499 	 */
4500 	enter_guest();
4501 	skip_exit_vmcall();
4502 
4503 	/* Let L2 finish */
4504 	enter_guest();
4505 	report(__func__, 1);
4506 }
4507 
4508 static void set_irq_line_thread(void *data)
4509 {
4510 	/* Wait until other CPU entered L2 */
4511 	while (vmx_get_test_stage() != 1)
4512 		;
4513 
4514 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
4515 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
4516 	vmx_set_test_stage(2);
4517 }
4518 
4519 static bool irq_78_handler_vmcall_before_eoi;
4520 static void irq_78_handler_guest(isr_regs_t *regs)
4521 {
4522 	set_irq_line(0xf, 0);
4523 	if (irq_78_handler_vmcall_before_eoi)
4524 		vmcall();
4525 	eoi();
4526 	vmcall();
4527 }
4528 
4529 static void vmx_apic_passthrough_guest(void)
4530 {
4531 	handle_irq(0x78, irq_78_handler_guest);
4532 	irq_enable();
4533 
4534 	/* If requested, wait for other CPU to trigger ioapic scan */
4535 	if (vmx_get_test_stage() < 1) {
4536 		vmx_set_test_stage(1);
4537 		while (vmx_get_test_stage() != 2)
4538 			;
4539 	}
4540 
4541 	set_irq_line(0xf, 1);
4542 }
4543 
4544 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
4545 {
4546 	void *msr_bitmap;
4547 
4548 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
4549 		report_skip(__func__);
4550 		return;
4551 	}
4552 
4553 	msr_bitmap = alloc_page();
4554 
4555 	u64 cpu_ctrl_0 = CPU_SECONDARY | CPU_MSR_BITMAP;
4556 	u64 cpu_ctrl_1 = 0;
4557 
4558 	memset(msr_bitmap, 0x0, PAGE_SIZE);
4559 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
4560 
4561 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
4562 
4563 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
4564 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
4565 
4566 	if (set_irq_line_from_thread) {
4567 		irq_78_handler_vmcall_before_eoi = false;
4568 		on_cpu_async(1, set_irq_line_thread, NULL);
4569 	} else {
4570 		irq_78_handler_vmcall_before_eoi = true;
4571 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
4572 		vmx_set_test_stage(2);
4573 	}
4574 	test_set_guest(vmx_apic_passthrough_guest);
4575 
4576 	if (irq_78_handler_vmcall_before_eoi) {
4577 		/* Before EOI remote_irr should still be set */
4578 		enter_guest();
4579 		skip_exit_vmcall();
4580 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
4581 			"IOAPIC pass-through: remote_irr=1 before EOI");
4582 	}
4583 
4584 	/* After EOI remote_irr should be cleared */
4585 	enter_guest();
4586 	skip_exit_vmcall();
4587 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
4588 		"IOAPIC pass-through: remote_irr=0 after EOI");
4589 
4590 	/* Let L2 finish */
4591 	enter_guest();
4592 	report(__func__, 1);
4593 }
4594 
4595 static void vmx_apic_passthrough_test(void)
4596 {
4597 	vmx_apic_passthrough(false);
4598 }
4599 
4600 static void vmx_apic_passthrough_thread_test(void)
4601 {
4602 	vmx_apic_passthrough(true);
4603 }
4604 
4605 #define TEST(name) { #name, .v2 = name }
4606 
4607 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
4608 struct vmx_test vmx_tests[] = {
4609 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
4610 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
4611 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
4612 		preemption_timer_exit_handler, NULL, {0} },
4613 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
4614 		test_ctrl_pat_exit_handler, NULL, {0} },
4615 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
4616 		test_ctrl_efer_exit_handler, NULL, {0} },
4617 	{ "CR shadowing", NULL, cr_shadowing_main,
4618 		cr_shadowing_exit_handler, NULL, {0} },
4619 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
4620 		NULL, {0} },
4621 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
4622 		insn_intercept_exit_handler, NULL, {0} },
4623 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
4624 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
4625 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
4626 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
4627 	{ "interrupt", interrupt_init, interrupt_main,
4628 		interrupt_exit_handler, NULL, {0} },
4629 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
4630 		NULL, {0} },
4631 	{ "MSR switch", msr_switch_init, msr_switch_main,
4632 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
4633 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
4634 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
4635 		disable_rdtscp_exit_handler, NULL, {0} },
4636 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
4637 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
4638 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
4639 		exit_monitor_from_l2_handler, NULL, {0} },
4640 	/* Basic V2 tests. */
4641 	TEST(v2_null_test),
4642 	TEST(v2_multiple_entries_test),
4643 	TEST(fixture_test_case1),
4644 	TEST(fixture_test_case2),
4645 	/* Opcode tests. */
4646 	TEST(invvpid_test_v2),
4647 	/* VM-entry tests */
4648 	TEST(vmx_controls_test),
4649 	TEST(vmentry_movss_shadow_test),
4650 	/* APICv tests */
4651 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
4652 	/* APIC pass-through tests */
4653 	TEST(vmx_apic_passthrough_test),
4654 	TEST(vmx_apic_passthrough_thread_test),
4655 	/* Regression tests */
4656 	TEST(vmx_cr_load_test),
4657 	/* EPT access tests. */
4658 	TEST(ept_access_test_not_present),
4659 	TEST(ept_access_test_read_only),
4660 	TEST(ept_access_test_write_only),
4661 	TEST(ept_access_test_read_write),
4662 	TEST(ept_access_test_execute_only),
4663 	TEST(ept_access_test_read_execute),
4664 	TEST(ept_access_test_write_execute),
4665 	TEST(ept_access_test_read_write_execute),
4666 	TEST(ept_access_test_reserved_bits),
4667 	TEST(ept_access_test_ignored_bits),
4668 	TEST(ept_access_test_paddr_not_present_ad_disabled),
4669 	TEST(ept_access_test_paddr_not_present_ad_enabled),
4670 	TEST(ept_access_test_paddr_read_only_ad_disabled),
4671 	TEST(ept_access_test_paddr_read_only_ad_enabled),
4672 	TEST(ept_access_test_paddr_read_write),
4673 	TEST(ept_access_test_paddr_read_write_execute),
4674 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
4675 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
4676 	TEST(ept_access_test_paddr_not_present_page_fault),
4677 	TEST(ept_access_test_force_2m_page),
4678 	{ NULL, NULL, NULL, NULL, NULL, {0} },
4679 };
4680