xref: /kvm-unit-tests/x86/vmx_tests.c (revision 4227347b322e10d8386a5281c691296efbff5d7c)
1 /*
2  * All test cases of nested virtualization should be in this file
3  *
4  * Author : Arthur Chunqi Li <yzt356@gmail.com>
5  */
6 
7 #include <asm/debugreg.h>
8 
9 #include "vmx.h"
10 #include "msr.h"
11 #include "processor.h"
12 #include "vm.h"
13 #include "pci.h"
14 #include "fwcfg.h"
15 #include "isr.h"
16 #include "desc.h"
17 #include "apic.h"
18 #include "types.h"
19 #include "vmalloc.h"
20 #include "alloc_page.h"
21 #include "smp.h"
22 #include "delay.h"
23 
24 #define NONCANONICAL            0xaaaaaaaaaaaaaaaaull
25 
26 #define VPID_CAP_INVVPID_TYPES_SHIFT 40
27 
28 u64 ia32_pat;
29 u64 ia32_efer;
30 void *io_bitmap_a, *io_bitmap_b;
31 u16 ioport;
32 
33 unsigned long *pml4;
34 u64 eptp;
35 void *data_page1, *data_page2;
36 
37 phys_addr_t pci_physaddr;
38 
39 void *pml_log;
40 #define PML_INDEX 512
41 
42 static inline unsigned ffs(unsigned x)
43 {
44 	int pos = -1;
45 
46 	__asm__ __volatile__("bsf %1, %%eax; cmovnz %%eax, %0"
47 			     : "+r"(pos) : "rm"(x) : "eax");
48 	return pos + 1;
49 }
50 
51 static inline void vmcall(void)
52 {
53 	asm volatile("vmcall");
54 }
55 
56 static void basic_guest_main(void)
57 {
58 	report("Basic VMX test", 1);
59 }
60 
61 static int basic_exit_handler(void)
62 {
63 	report("Basic VMX test", 0);
64 	print_vmexit_info();
65 	return VMX_TEST_EXIT;
66 }
67 
68 static void vmenter_main(void)
69 {
70 	u64 rax;
71 	u64 rsp, resume_rsp;
72 
73 	report("test vmlaunch", 1);
74 
75 	asm volatile(
76 		"mov %%rsp, %0\n\t"
77 		"mov %3, %%rax\n\t"
78 		"vmcall\n\t"
79 		"mov %%rax, %1\n\t"
80 		"mov %%rsp, %2\n\t"
81 		: "=r"(rsp), "=r"(rax), "=r"(resume_rsp)
82 		: "g"(0xABCD));
83 	report("test vmresume", (rax == 0xFFFF) && (rsp == resume_rsp));
84 }
85 
86 static int vmenter_exit_handler(void)
87 {
88 	u64 guest_rip;
89 	ulong reason;
90 
91 	guest_rip = vmcs_read(GUEST_RIP);
92 	reason = vmcs_read(EXI_REASON) & 0xff;
93 	switch (reason) {
94 	case VMX_VMCALL:
95 		if (regs.rax != 0xABCD) {
96 			report("test vmresume", 0);
97 			return VMX_TEST_VMEXIT;
98 		}
99 		regs.rax = 0xFFFF;
100 		vmcs_write(GUEST_RIP, guest_rip + 3);
101 		return VMX_TEST_RESUME;
102 	default:
103 		report("test vmresume", 0);
104 		print_vmexit_info();
105 	}
106 	return VMX_TEST_VMEXIT;
107 }
108 
109 u32 preempt_scale;
110 volatile unsigned long long tsc_val;
111 volatile u32 preempt_val;
112 u64 saved_rip;
113 
114 static int preemption_timer_init(struct vmcs *vmcs)
115 {
116 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
117 		printf("\tPreemption timer is not supported\n");
118 		return VMX_TEST_EXIT;
119 	}
120 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
121 	preempt_val = 10000000;
122 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
123 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
124 
125 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
126 		printf("\tSave preemption value is not supported\n");
127 
128 	return VMX_TEST_START;
129 }
130 
131 static void preemption_timer_main(void)
132 {
133 	tsc_val = rdtsc();
134 	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
135 		vmx_set_test_stage(0);
136 		vmcall();
137 		if (vmx_get_test_stage() == 1)
138 			vmcall();
139 	}
140 	vmx_set_test_stage(1);
141 	while (vmx_get_test_stage() == 1) {
142 		if (((rdtsc() - tsc_val) >> preempt_scale)
143 				> 10 * preempt_val) {
144 			vmx_set_test_stage(2);
145 			vmcall();
146 		}
147 	}
148 	tsc_val = rdtsc();
149 	asm volatile ("hlt");
150 	vmcall();
151 	vmx_set_test_stage(5);
152 	vmcall();
153 }
154 
155 static int preemption_timer_exit_handler(void)
156 {
157 	bool guest_halted;
158 	u64 guest_rip;
159 	ulong reason;
160 	u32 insn_len;
161 	u32 ctrl_exit;
162 
163 	guest_rip = vmcs_read(GUEST_RIP);
164 	reason = vmcs_read(EXI_REASON) & 0xff;
165 	insn_len = vmcs_read(EXI_INST_LEN);
166 	switch (reason) {
167 	case VMX_PREEMPT:
168 		switch (vmx_get_test_stage()) {
169 		case 1:
170 		case 2:
171 			report("busy-wait for preemption timer",
172 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
173 			       preempt_val);
174 			vmx_set_test_stage(3);
175 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
176 			return VMX_TEST_RESUME;
177 		case 3:
178 			guest_halted =
179 				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
180 			report("preemption timer during hlt",
181 			       ((rdtsc() - tsc_val) >> preempt_scale) >=
182 			       preempt_val && guest_halted);
183 			vmx_set_test_stage(4);
184 			vmcs_write(PIN_CONTROLS,
185 				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
186 			vmcs_write(EXI_CONTROLS,
187 				   vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_PREEMPT);
188 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
189 			return VMX_TEST_RESUME;
190 		case 4:
191 			report("preemption timer with 0 value",
192 			       saved_rip == guest_rip);
193 			break;
194 		default:
195 			report("Invalid stage.", false);
196 			print_vmexit_info();
197 			break;
198 		}
199 		break;
200 	case VMX_VMCALL:
201 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
202 		switch (vmx_get_test_stage()) {
203 		case 0:
204 			report("Keep preemption value",
205 			       vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val);
206 			vmx_set_test_stage(1);
207 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
208 			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
209 				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
210 			vmcs_write(EXI_CONTROLS, ctrl_exit);
211 			return VMX_TEST_RESUME;
212 		case 1:
213 			report("Save preemption value",
214 			       vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val);
215 			return VMX_TEST_RESUME;
216 		case 2:
217 			report("busy-wait for preemption timer", 0);
218 			vmx_set_test_stage(3);
219 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
220 			return VMX_TEST_RESUME;
221 		case 3:
222 			report("preemption timer during hlt", 0);
223 			vmx_set_test_stage(4);
224 			/* fall through */
225 		case 4:
226 			vmcs_write(PIN_CONTROLS,
227 				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
228 			vmcs_write(PREEMPT_TIMER_VALUE, 0);
229 			saved_rip = guest_rip + insn_len;
230 			return VMX_TEST_RESUME;
231 		case 5:
232 			report("preemption timer with 0 value (vmcall stage 5)", 0);
233 			break;
234 		default:
235 			// Should not reach here
236 			report("unexpected stage, %d", false,
237 			       vmx_get_test_stage());
238 			print_vmexit_info();
239 			return VMX_TEST_VMEXIT;
240 		}
241 		break;
242 	default:
243 		report("Unknown exit reason, %ld", false, reason);
244 		print_vmexit_info();
245 	}
246 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
247 	return VMX_TEST_VMEXIT;
248 }
249 
250 static void msr_bmp_init(void)
251 {
252 	void *msr_bitmap;
253 	u32 ctrl_cpu0;
254 
255 	msr_bitmap = alloc_page();
256 	memset(msr_bitmap, 0x0, PAGE_SIZE);
257 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
258 	ctrl_cpu0 |= CPU_MSR_BITMAP;
259 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
260 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
261 }
262 
263 static void *get_msr_bitmap(void)
264 {
265 	void *msr_bitmap;
266 
267 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_MSR_BITMAP) {
268 		msr_bitmap = (void *)vmcs_read(MSR_BITMAP);
269 	} else {
270 		msr_bitmap = alloc_page();
271 		memset(msr_bitmap, 0xff, PAGE_SIZE);
272 		vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
273 		vmcs_set_bits(CPU_EXEC_CTRL0, CPU_MSR_BITMAP);
274 	}
275 
276 	return msr_bitmap;
277 }
278 
279 static void disable_intercept_for_x2apic_msrs(void)
280 {
281 	unsigned long *msr_bitmap = (unsigned long *)get_msr_bitmap();
282 	u32 msr;
283 
284 	for (msr = APIC_BASE_MSR;
285 		 msr < (APIC_BASE_MSR+0xff);
286 		 msr += BITS_PER_LONG) {
287 		unsigned int word = msr / BITS_PER_LONG;
288 
289 		msr_bitmap[word] = 0;
290 		msr_bitmap[word + (0x800 / sizeof(long))] = 0;
291 	}
292 }
293 
294 static int test_ctrl_pat_init(struct vmcs *vmcs)
295 {
296 	u64 ctrl_ent;
297 	u64 ctrl_exi;
298 
299 	msr_bmp_init();
300 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
301 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
302 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
303 		printf("\tSave/load PAT is not supported\n");
304 		return 1;
305 	}
306 
307 	ctrl_ent = vmcs_read(ENT_CONTROLS);
308 	ctrl_exi = vmcs_read(EXI_CONTROLS);
309 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
310 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
311 	vmcs_write(ENT_CONTROLS, ctrl_ent);
312 	vmcs_write(EXI_CONTROLS, ctrl_exi);
313 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
314 	vmcs_write(GUEST_PAT, 0x0);
315 	vmcs_write(HOST_PAT, ia32_pat);
316 	return VMX_TEST_START;
317 }
318 
319 static void test_ctrl_pat_main(void)
320 {
321 	u64 guest_ia32_pat;
322 
323 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
324 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
325 		printf("\tENT_LOAD_PAT is not supported.\n");
326 	else {
327 		if (guest_ia32_pat != 0) {
328 			report("Entry load PAT", 0);
329 			return;
330 		}
331 	}
332 	wrmsr(MSR_IA32_CR_PAT, 0x6);
333 	vmcall();
334 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
335 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
336 		report("Entry load PAT", guest_ia32_pat == ia32_pat);
337 }
338 
339 static int test_ctrl_pat_exit_handler(void)
340 {
341 	u64 guest_rip;
342 	ulong reason;
343 	u64 guest_pat;
344 
345 	guest_rip = vmcs_read(GUEST_RIP);
346 	reason = vmcs_read(EXI_REASON) & 0xff;
347 	switch (reason) {
348 	case VMX_VMCALL:
349 		guest_pat = vmcs_read(GUEST_PAT);
350 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
351 			printf("\tEXI_SAVE_PAT is not supported\n");
352 			vmcs_write(GUEST_PAT, 0x6);
353 		} else {
354 			report("Exit save PAT", guest_pat == 0x6);
355 		}
356 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
357 			printf("\tEXI_LOAD_PAT is not supported\n");
358 		else
359 			report("Exit load PAT", rdmsr(MSR_IA32_CR_PAT) == ia32_pat);
360 		vmcs_write(GUEST_PAT, ia32_pat);
361 		vmcs_write(GUEST_RIP, guest_rip + 3);
362 		return VMX_TEST_RESUME;
363 	default:
364 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
365 		break;
366 	}
367 	return VMX_TEST_VMEXIT;
368 }
369 
370 static int test_ctrl_efer_init(struct vmcs *vmcs)
371 {
372 	u64 ctrl_ent;
373 	u64 ctrl_exi;
374 
375 	msr_bmp_init();
376 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
377 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
378 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
379 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
380 	ia32_efer = rdmsr(MSR_EFER);
381 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
382 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
383 	return VMX_TEST_START;
384 }
385 
386 static void test_ctrl_efer_main(void)
387 {
388 	u64 guest_ia32_efer;
389 
390 	guest_ia32_efer = rdmsr(MSR_EFER);
391 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
392 		printf("\tENT_LOAD_EFER is not supported.\n");
393 	else {
394 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
395 			report("Entry load EFER", 0);
396 			return;
397 		}
398 	}
399 	wrmsr(MSR_EFER, ia32_efer);
400 	vmcall();
401 	guest_ia32_efer = rdmsr(MSR_EFER);
402 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
403 		report("Entry load EFER", guest_ia32_efer == ia32_efer);
404 }
405 
406 static int test_ctrl_efer_exit_handler(void)
407 {
408 	u64 guest_rip;
409 	ulong reason;
410 	u64 guest_efer;
411 
412 	guest_rip = vmcs_read(GUEST_RIP);
413 	reason = vmcs_read(EXI_REASON) & 0xff;
414 	switch (reason) {
415 	case VMX_VMCALL:
416 		guest_efer = vmcs_read(GUEST_EFER);
417 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
418 			printf("\tEXI_SAVE_EFER is not supported\n");
419 			vmcs_write(GUEST_EFER, ia32_efer);
420 		} else {
421 			report("Exit save EFER", guest_efer == ia32_efer);
422 		}
423 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
424 			printf("\tEXI_LOAD_EFER is not supported\n");
425 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
426 		} else {
427 			report("Exit load EFER", rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX));
428 		}
429 		vmcs_write(GUEST_PAT, ia32_efer);
430 		vmcs_write(GUEST_RIP, guest_rip + 3);
431 		return VMX_TEST_RESUME;
432 	default:
433 		printf("ERROR : Undefined exit reason, reason = %ld.\n", reason);
434 		break;
435 	}
436 	return VMX_TEST_VMEXIT;
437 }
438 
439 u32 guest_cr0, guest_cr4;
440 
441 static void cr_shadowing_main(void)
442 {
443 	u32 cr0, cr4, tmp;
444 
445 	// Test read through
446 	vmx_set_test_stage(0);
447 	guest_cr0 = read_cr0();
448 	if (vmx_get_test_stage() == 1)
449 		report("Read through CR0", 0);
450 	else
451 		vmcall();
452 	vmx_set_test_stage(1);
453 	guest_cr4 = read_cr4();
454 	if (vmx_get_test_stage() == 2)
455 		report("Read through CR4", 0);
456 	else
457 		vmcall();
458 	// Test write through
459 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
460 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
461 	vmx_set_test_stage(2);
462 	write_cr0(guest_cr0);
463 	if (vmx_get_test_stage() == 3)
464 		report("Write throuth CR0", 0);
465 	else
466 		vmcall();
467 	vmx_set_test_stage(3);
468 	write_cr4(guest_cr4);
469 	if (vmx_get_test_stage() == 4)
470 		report("Write through CR4", 0);
471 	else
472 		vmcall();
473 	// Test read shadow
474 	vmx_set_test_stage(4);
475 	vmcall();
476 	cr0 = read_cr0();
477 	if (vmx_get_test_stage() != 5)
478 		report("Read shadowing CR0", cr0 == guest_cr0);
479 	vmx_set_test_stage(5);
480 	cr4 = read_cr4();
481 	if (vmx_get_test_stage() != 6)
482 		report("Read shadowing CR4", cr4 == guest_cr4);
483 	// Test write shadow (same value with shadow)
484 	vmx_set_test_stage(6);
485 	write_cr0(guest_cr0);
486 	if (vmx_get_test_stage() == 7)
487 		report("Write shadowing CR0 (same value with shadow)", 0);
488 	else
489 		vmcall();
490 	vmx_set_test_stage(7);
491 	write_cr4(guest_cr4);
492 	if (vmx_get_test_stage() == 8)
493 		report("Write shadowing CR4 (same value with shadow)", 0);
494 	else
495 		vmcall();
496 	// Test write shadow (different value)
497 	vmx_set_test_stage(8);
498 	tmp = guest_cr0 ^ X86_CR0_TS;
499 	asm volatile("mov %0, %%rsi\n\t"
500 		"mov %%rsi, %%cr0\n\t"
501 		::"m"(tmp)
502 		:"rsi", "memory", "cc");
503 	report("Write shadowing different X86_CR0_TS", vmx_get_test_stage() == 9);
504 	vmx_set_test_stage(9);
505 	tmp = guest_cr0 ^ X86_CR0_MP;
506 	asm volatile("mov %0, %%rsi\n\t"
507 		"mov %%rsi, %%cr0\n\t"
508 		::"m"(tmp)
509 		:"rsi", "memory", "cc");
510 	report("Write shadowing different X86_CR0_MP", vmx_get_test_stage() == 10);
511 	vmx_set_test_stage(10);
512 	tmp = guest_cr4 ^ X86_CR4_TSD;
513 	asm volatile("mov %0, %%rsi\n\t"
514 		"mov %%rsi, %%cr4\n\t"
515 		::"m"(tmp)
516 		:"rsi", "memory", "cc");
517 	report("Write shadowing different X86_CR4_TSD", vmx_get_test_stage() == 11);
518 	vmx_set_test_stage(11);
519 	tmp = guest_cr4 ^ X86_CR4_DE;
520 	asm volatile("mov %0, %%rsi\n\t"
521 		"mov %%rsi, %%cr4\n\t"
522 		::"m"(tmp)
523 		:"rsi", "memory", "cc");
524 	report("Write shadowing different X86_CR4_DE", vmx_get_test_stage() == 12);
525 }
526 
527 static int cr_shadowing_exit_handler(void)
528 {
529 	u64 guest_rip;
530 	ulong reason;
531 	u32 insn_len;
532 	u32 exit_qual;
533 
534 	guest_rip = vmcs_read(GUEST_RIP);
535 	reason = vmcs_read(EXI_REASON) & 0xff;
536 	insn_len = vmcs_read(EXI_INST_LEN);
537 	exit_qual = vmcs_read(EXI_QUALIFICATION);
538 	switch (reason) {
539 	case VMX_VMCALL:
540 		switch (vmx_get_test_stage()) {
541 		case 0:
542 			report("Read through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
543 			break;
544 		case 1:
545 			report("Read through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
546 			break;
547 		case 2:
548 			report("Write through CR0", guest_cr0 == vmcs_read(GUEST_CR0));
549 			break;
550 		case 3:
551 			report("Write through CR4", guest_cr4 == vmcs_read(GUEST_CR4));
552 			break;
553 		case 4:
554 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
555 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
556 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
557 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
558 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
559 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
560 			break;
561 		case 6:
562 			report("Write shadowing CR0 (same value)",
563 					guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)));
564 			break;
565 		case 7:
566 			report("Write shadowing CR4 (same value)",
567 					guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)));
568 			break;
569 		default:
570 			// Should not reach here
571 			report("unexpected stage, %d", false,
572 			       vmx_get_test_stage());
573 			print_vmexit_info();
574 			return VMX_TEST_VMEXIT;
575 		}
576 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
577 		return VMX_TEST_RESUME;
578 	case VMX_CR:
579 		switch (vmx_get_test_stage()) {
580 		case 4:
581 			report("Read shadowing CR0", 0);
582 			vmx_inc_test_stage();
583 			break;
584 		case 5:
585 			report("Read shadowing CR4", 0);
586 			vmx_inc_test_stage();
587 			break;
588 		case 6:
589 			report("Write shadowing CR0 (same value)", 0);
590 			vmx_inc_test_stage();
591 			break;
592 		case 7:
593 			report("Write shadowing CR4 (same value)", 0);
594 			vmx_inc_test_stage();
595 			break;
596 		case 8:
597 		case 9:
598 			// 0x600 encodes "mov %esi, %cr0"
599 			if (exit_qual == 0x600)
600 				vmx_inc_test_stage();
601 			break;
602 		case 10:
603 		case 11:
604 			// 0x604 encodes "mov %esi, %cr4"
605 			if (exit_qual == 0x604)
606 				vmx_inc_test_stage();
607 			break;
608 		default:
609 			// Should not reach here
610 			report("unexpected stage, %d", false,
611 			       vmx_get_test_stage());
612 			print_vmexit_info();
613 			return VMX_TEST_VMEXIT;
614 		}
615 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
616 		return VMX_TEST_RESUME;
617 	default:
618 		report("Unknown exit reason, %ld", false, reason);
619 		print_vmexit_info();
620 	}
621 	return VMX_TEST_VMEXIT;
622 }
623 
624 static int iobmp_init(struct vmcs *vmcs)
625 {
626 	u32 ctrl_cpu0;
627 
628 	io_bitmap_a = alloc_page();
629 	io_bitmap_b = alloc_page();
630 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
631 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
632 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
633 	ctrl_cpu0 |= CPU_IO_BITMAP;
634 	ctrl_cpu0 &= (~CPU_IO);
635 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
636 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
637 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
638 	return VMX_TEST_START;
639 }
640 
641 static void iobmp_main(void)
642 {
643 	// stage 0, test IO pass
644 	vmx_set_test_stage(0);
645 	inb(0x5000);
646 	outb(0x0, 0x5000);
647 	report("I/O bitmap - I/O pass", vmx_get_test_stage() == 0);
648 	// test IO width, in/out
649 	((u8 *)io_bitmap_a)[0] = 0xFF;
650 	vmx_set_test_stage(2);
651 	inb(0x0);
652 	report("I/O bitmap - trap in", vmx_get_test_stage() == 3);
653 	vmx_set_test_stage(3);
654 	outw(0x0, 0x0);
655 	report("I/O bitmap - trap out", vmx_get_test_stage() == 4);
656 	vmx_set_test_stage(4);
657 	inl(0x0);
658 	report("I/O bitmap - I/O width, long", vmx_get_test_stage() == 5);
659 	// test low/high IO port
660 	vmx_set_test_stage(5);
661 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
662 	inb(0x5000);
663 	report("I/O bitmap - I/O port, low part", vmx_get_test_stage() == 6);
664 	vmx_set_test_stage(6);
665 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
666 	inb(0x9000);
667 	report("I/O bitmap - I/O port, high part", vmx_get_test_stage() == 7);
668 	// test partial pass
669 	vmx_set_test_stage(7);
670 	inl(0x4FFF);
671 	report("I/O bitmap - partial pass", vmx_get_test_stage() == 8);
672 	// test overrun
673 	vmx_set_test_stage(8);
674 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
675 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
676 	inl(0xFFFF);
677 	report("I/O bitmap - overrun", vmx_get_test_stage() == 9);
678 	vmx_set_test_stage(9);
679 	vmcall();
680 	outb(0x0, 0x0);
681 	report("I/O bitmap - ignore unconditional exiting",
682 	       vmx_get_test_stage() == 9);
683 	vmx_set_test_stage(10);
684 	vmcall();
685 	outb(0x0, 0x0);
686 	report("I/O bitmap - unconditional exiting",
687 	       vmx_get_test_stage() == 11);
688 }
689 
690 static int iobmp_exit_handler(void)
691 {
692 	u64 guest_rip;
693 	ulong reason, exit_qual;
694 	u32 insn_len, ctrl_cpu0;
695 
696 	guest_rip = vmcs_read(GUEST_RIP);
697 	reason = vmcs_read(EXI_REASON) & 0xff;
698 	exit_qual = vmcs_read(EXI_QUALIFICATION);
699 	insn_len = vmcs_read(EXI_INST_LEN);
700 	switch (reason) {
701 	case VMX_IO:
702 		switch (vmx_get_test_stage()) {
703 		case 0:
704 		case 1:
705 			vmx_inc_test_stage();
706 			break;
707 		case 2:
708 			report("I/O bitmap - I/O width, byte",
709 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE);
710 			report("I/O bitmap - I/O direction, in", exit_qual & VMX_IO_IN);
711 			vmx_inc_test_stage();
712 			break;
713 		case 3:
714 			report("I/O bitmap - I/O width, word",
715 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD);
716 			report("I/O bitmap - I/O direction, out",
717 					!(exit_qual & VMX_IO_IN));
718 			vmx_inc_test_stage();
719 			break;
720 		case 4:
721 			report("I/O bitmap - I/O width, long",
722 					(exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG);
723 			vmx_inc_test_stage();
724 			break;
725 		case 5:
726 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
727 				vmx_inc_test_stage();
728 			break;
729 		case 6:
730 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
731 				vmx_inc_test_stage();
732 			break;
733 		case 7:
734 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
735 				vmx_inc_test_stage();
736 			break;
737 		case 8:
738 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
739 				vmx_inc_test_stage();
740 			break;
741 		case 9:
742 		case 10:
743 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
744 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
745 			vmx_inc_test_stage();
746 			break;
747 		default:
748 			// Should not reach here
749 			report("unexpected stage, %d", false,
750 			       vmx_get_test_stage());
751 			print_vmexit_info();
752 			return VMX_TEST_VMEXIT;
753 		}
754 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
755 		return VMX_TEST_RESUME;
756 	case VMX_VMCALL:
757 		switch (vmx_get_test_stage()) {
758 		case 9:
759 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
760 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
761 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
762 			break;
763 		case 10:
764 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
765 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
766 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
767 			break;
768 		default:
769 			// Should not reach here
770 			report("unexpected stage, %d", false,
771 			       vmx_get_test_stage());
772 			print_vmexit_info();
773 			return VMX_TEST_VMEXIT;
774 		}
775 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
776 		return VMX_TEST_RESUME;
777 	default:
778 		printf("guest_rip = %#lx\n", guest_rip);
779 		printf("\tERROR : Undefined exit reason, reason = %ld.\n", reason);
780 		break;
781 	}
782 	return VMX_TEST_VMEXIT;
783 }
784 
785 #define INSN_CPU0		0
786 #define INSN_CPU1		1
787 #define INSN_ALWAYS_TRAP	2
788 
789 #define FIELD_EXIT_QUAL		(1 << 0)
790 #define FIELD_INSN_INFO		(1 << 1)
791 
792 asm(
793 	"insn_hlt: hlt;ret\n\t"
794 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
795 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
796 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
797 	"insn_rdtsc: rdtsc;ret\n\t"
798 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
799 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
800 #ifdef __x86_64__
801 	"insn_cr8_load: xor %eax, %eax; mov %rax,%cr8;ret\n\t"
802 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
803 #endif
804 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
805 	"insn_pause: pause;ret\n\t"
806 	"insn_wbinvd: wbinvd;ret\n\t"
807 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
808 	"insn_invd: invd;ret\n\t"
809 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
810 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
811 	"insn_sidt: sidt idt_descr;ret\n\t"
812 	"insn_lidt: lidt idt_descr;ret\n\t"
813 	"insn_sldt: sldt %ax;ret\n\t"
814 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
815 	"insn_str: str %ax;ret\n\t"
816 	"insn_rdrand: rdrand %rax;ret\n\t"
817 	"insn_rdseed: rdseed %rax;ret\n\t"
818 );
819 extern void insn_hlt(void);
820 extern void insn_invlpg(void);
821 extern void insn_mwait(void);
822 extern void insn_rdpmc(void);
823 extern void insn_rdtsc(void);
824 extern void insn_cr3_load(void);
825 extern void insn_cr3_store(void);
826 #ifdef __x86_64__
827 extern void insn_cr8_load(void);
828 extern void insn_cr8_store(void);
829 #endif
830 extern void insn_monitor(void);
831 extern void insn_pause(void);
832 extern void insn_wbinvd(void);
833 extern void insn_sgdt(void);
834 extern void insn_lgdt(void);
835 extern void insn_sidt(void);
836 extern void insn_lidt(void);
837 extern void insn_sldt(void);
838 extern void insn_lldt(void);
839 extern void insn_str(void);
840 extern void insn_cpuid(void);
841 extern void insn_invd(void);
842 extern void insn_rdrand(void);
843 extern void insn_rdseed(void);
844 
845 u32 cur_insn;
846 u64 cr3;
847 
848 struct insn_table {
849 	const char *name;
850 	u32 flag;
851 	void (*insn_func)(void);
852 	u32 type;
853 	u32 reason;
854 	ulong exit_qual;
855 	u32 insn_info;
856 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
857 	// which field need to be tested, reason is always tested
858 	u32 test_field;
859 };
860 
861 /*
862  * Add more test cases of instruction intercept here. Elements in this
863  * table is:
864  *	name/control flag/insn function/type/exit reason/exit qulification/
865  *	instruction info/field to test
866  * The last field defines which fields (exit_qual and insn_info) need to be
867  * tested in exit handler. If set to 0, only "reason" is checked.
868  */
869 static struct insn_table insn_table[] = {
870 	// Flags for Primary Processor-Based VM-Execution Controls
871 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
872 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
873 		0x12345678, 0, FIELD_EXIT_QUAL},
874 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0},
875 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
876 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
877 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
878 		FIELD_EXIT_QUAL},
879 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
880 		FIELD_EXIT_QUAL},
881 #ifdef __x86_64__
882 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
883 		FIELD_EXIT_QUAL},
884 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
885 		FIELD_EXIT_QUAL},
886 #endif
887 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0},
888 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
889 	// Flags for Secondary Processor-Based VM-Execution Controls
890 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
891 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
892 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
893 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
894 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
895 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
896 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
897 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
898 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
899 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
900 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
901 	// Instructions always trap
902 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
903 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
904 	// Instructions never trap
905 	{NULL},
906 };
907 
908 static int insn_intercept_init(struct vmcs *vmcs)
909 {
910 	u32 ctrl_cpu;
911 
912 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
913 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
914 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
915 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
916 	cr3 = read_cr3();
917 	return VMX_TEST_START;
918 }
919 
920 static void insn_intercept_main(void)
921 {
922 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
923 		vmx_set_test_stage(cur_insn * 2);
924 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
925 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
926 		    (insn_table[cur_insn].type == INSN_CPU1 &&
927 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
928 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
929 			       insn_table[cur_insn].type - INSN_CPU0,
930 			       insn_table[cur_insn].name);
931 			continue;
932 		}
933 
934 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
935 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
936 		    (insn_table[cur_insn].type == INSN_CPU1 &&
937 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
938 			/* skip hlt, it stalls the guest and is tested below */
939 			if (insn_table[cur_insn].insn_func != insn_hlt)
940 				insn_table[cur_insn].insn_func();
941 			report("execute %s", vmx_get_test_stage() == cur_insn * 2,
942 					insn_table[cur_insn].name);
943 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
944 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
945 			       insn_table[cur_insn].type - INSN_CPU0,
946 			       insn_table[cur_insn].name);
947 
948 		vmcall();
949 
950 		insn_table[cur_insn].insn_func();
951 		report("intercept %s", vmx_get_test_stage() == cur_insn * 2 + 1,
952 				insn_table[cur_insn].name);
953 
954 		vmx_set_test_stage(cur_insn * 2 + 1);
955 		vmcall();
956 	}
957 }
958 
959 static int insn_intercept_exit_handler(void)
960 {
961 	u64 guest_rip;
962 	u32 reason;
963 	ulong exit_qual;
964 	u32 insn_len;
965 	u32 insn_info;
966 	bool pass;
967 
968 	guest_rip = vmcs_read(GUEST_RIP);
969 	reason = vmcs_read(EXI_REASON) & 0xff;
970 	exit_qual = vmcs_read(EXI_QUALIFICATION);
971 	insn_len = vmcs_read(EXI_INST_LEN);
972 	insn_info = vmcs_read(EXI_INST_INFO);
973 
974 	if (reason == VMX_VMCALL) {
975 		u32 val = 0;
976 
977 		if (insn_table[cur_insn].type == INSN_CPU0)
978 			val = vmcs_read(CPU_EXEC_CTRL0);
979 		else if (insn_table[cur_insn].type == INSN_CPU1)
980 			val = vmcs_read(CPU_EXEC_CTRL1);
981 
982 		if (vmx_get_test_stage() & 1)
983 			val &= ~insn_table[cur_insn].flag;
984 		else
985 			val |= insn_table[cur_insn].flag;
986 
987 		if (insn_table[cur_insn].type == INSN_CPU0)
988 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
989 		else if (insn_table[cur_insn].type == INSN_CPU1)
990 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
991 	} else {
992 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
993 			insn_table[cur_insn].reason == reason;
994 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
995 		    insn_table[cur_insn].exit_qual != exit_qual)
996 			pass = false;
997 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
998 		    insn_table[cur_insn].insn_info != insn_info)
999 			pass = false;
1000 		if (pass)
1001 			vmx_inc_test_stage();
1002 	}
1003 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
1004 	return VMX_TEST_RESUME;
1005 }
1006 
1007 static int setup_eptp(u64 hpa, bool enable_ad)
1008 {
1009 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1010 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
1011 		printf("\tEPT is not supported");
1012 		return 1;
1013 	}
1014 
1015 	if (!(ept_vpid.val & EPT_CAP_UC) &&
1016 			!(ept_vpid.val & EPT_CAP_WB)) {
1017 		printf("\tEPT paging-structure memory type "
1018 				"UC&WB are not supported\n");
1019 		return 1;
1020 	}
1021 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
1022 		printf("\tPWL4 is not supported\n");
1023 		return 1;
1024 	}
1025 
1026 	if (ept_vpid.val & EPT_CAP_UC)
1027 		eptp = EPT_MEM_TYPE_UC;
1028 	else
1029 		eptp = EPT_MEM_TYPE_WB;
1030 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1031 	eptp |= hpa;
1032 	if (enable_ad)
1033 		eptp |= EPTP_AD_FLAG;
1034 
1035 	vmcs_write(EPTP, eptp);
1036 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0)| CPU_SECONDARY);
1037 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1)| CPU_EPT);
1038 
1039 	return 0;
1040 }
1041 
1042 /* Enables EPT and sets up the identity map. */
1043 static int setup_ept(bool enable_ad)
1044 {
1045 	unsigned long end_of_memory;
1046 
1047 	pml4 = alloc_page();
1048 
1049 	setup_eptp(virt_to_phys(pml4), enable_ad);
1050 
1051 	memset(pml4, 0, PAGE_SIZE);
1052 
1053 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1054 	if (end_of_memory < (1ul << 32))
1055 		end_of_memory = (1ul << 32);
1056 	/* Cannot use large EPT pages if we need to track EPT
1057 	 * accessed/dirty bits at 4K granularity.
1058 	 */
1059 	setup_ept_range(pml4, 0, end_of_memory, 0,
1060 			!enable_ad && ept_2m_supported(),
1061 			EPT_WA | EPT_RA | EPT_EA);
1062 	return 0;
1063 }
1064 
1065 static int enable_ept(void)
1066 {
1067 	return setup_eptp(0, false);
1068 }
1069 
1070 static int enable_unrestricted_guest(void)
1071 {
1072 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1073 	    !(ctrl_cpu_rev[1].clr & CPU_URG))
1074 		return 1;
1075 
1076 	if (enable_ept())
1077 		return 1;
1078 
1079 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
1080 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | CPU_URG);
1081 
1082 	return 0;
1083 }
1084 
1085 static void ept_enable_ad_bits(void)
1086 {
1087 	eptp |= EPTP_AD_FLAG;
1088 	vmcs_write(EPTP, eptp);
1089 }
1090 
1091 static void ept_disable_ad_bits(void)
1092 {
1093 	eptp &= ~EPTP_AD_FLAG;
1094 	vmcs_write(EPTP, eptp);
1095 }
1096 
1097 static void ept_enable_ad_bits_or_skip_test(void)
1098 {
1099 	if (!ept_ad_bits_supported())
1100 		test_skip("EPT AD bits not supported.");
1101 	ept_enable_ad_bits();
1102 }
1103 
1104 static int apic_version;
1105 
1106 static int ept_init_common(bool have_ad)
1107 {
1108 	int ret;
1109 	struct pci_dev pcidev;
1110 
1111 	if (setup_ept(have_ad))
1112 		return VMX_TEST_EXIT;
1113 	data_page1 = alloc_page();
1114 	data_page2 = alloc_page();
1115 	memset(data_page1, 0x0, PAGE_SIZE);
1116 	memset(data_page2, 0x0, PAGE_SIZE);
1117 	*((u32 *)data_page1) = MAGIC_VAL_1;
1118 	*((u32 *)data_page2) = MAGIC_VAL_2;
1119 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1120 			EPT_RA | EPT_WA | EPT_EA);
1121 
1122 	apic_version = apic_read(APIC_LVR);
1123 
1124 	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
1125 	if (ret != PCIDEVADDR_INVALID) {
1126 		pci_dev_init(&pcidev, ret);
1127 		pci_physaddr = pcidev.resource[PCI_TESTDEV_BAR_MEM];
1128 	}
1129 
1130 	return VMX_TEST_START;
1131 }
1132 
1133 static int ept_init(struct vmcs *vmcs)
1134 {
1135 	return ept_init_common(false);
1136 }
1137 
1138 static void ept_common(void)
1139 {
1140 	vmx_set_test_stage(0);
1141 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1142 			*((u32 *)data_page1) != MAGIC_VAL_1)
1143 		report("EPT basic framework - read", 0);
1144 	else {
1145 		*((u32 *)data_page2) = MAGIC_VAL_3;
1146 		vmcall();
1147 		if (vmx_get_test_stage() == 1) {
1148 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1149 					*((u32 *)data_page2) == MAGIC_VAL_2)
1150 				report("EPT basic framework", 1);
1151 			else
1152 				report("EPT basic framework - remap", 1);
1153 		}
1154 	}
1155 	// Test EPT Misconfigurations
1156 	vmx_set_test_stage(1);
1157 	vmcall();
1158 	*((u32 *)data_page1) = MAGIC_VAL_1;
1159 	if (vmx_get_test_stage() != 2) {
1160 		report("EPT misconfigurations", 0);
1161 		goto t1;
1162 	}
1163 	vmx_set_test_stage(2);
1164 	vmcall();
1165 	*((u32 *)data_page1) = MAGIC_VAL_1;
1166 	report("EPT misconfigurations", vmx_get_test_stage() == 3);
1167 t1:
1168 	// Test EPT violation
1169 	vmx_set_test_stage(3);
1170 	vmcall();
1171 	*((u32 *)data_page1) = MAGIC_VAL_1;
1172 	report("EPT violation - page permission", vmx_get_test_stage() == 4);
1173 	// Violation caused by EPT paging structure
1174 	vmx_set_test_stage(4);
1175 	vmcall();
1176 	*((u32 *)data_page1) = MAGIC_VAL_2;
1177 	report("EPT violation - paging structure", vmx_get_test_stage() == 5);
1178 
1179 	// MMIO Read/Write
1180 	vmx_set_test_stage(5);
1181 	vmcall();
1182 
1183 	*(u32 volatile *)pci_physaddr;
1184 	report("MMIO EPT violation - read", vmx_get_test_stage() == 6);
1185 
1186 	*(u32 volatile *)pci_physaddr = MAGIC_VAL_1;
1187 	report("MMIO EPT violation - write", vmx_get_test_stage() == 7);
1188 }
1189 
1190 static void ept_main(void)
1191 {
1192 	ept_common();
1193 
1194 	// Test EPT access to L1 MMIO
1195 	vmx_set_test_stage(7);
1196 	report("EPT - MMIO access", *((u32 *)0xfee00030UL) == apic_version);
1197 
1198 	// Test invalid operand for INVEPT
1199 	vmcall();
1200 	report("EPT - unsupported INVEPT", vmx_get_test_stage() == 8);
1201 }
1202 
1203 static bool invept_test(int type, u64 eptp)
1204 {
1205 	bool ret, supported;
1206 
1207 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1208 	ret = invept(type, eptp);
1209 
1210 	if (ret == !supported)
1211 		return false;
1212 
1213 	if (!supported)
1214 		printf("WARNING: unsupported invept passed!\n");
1215 	else
1216 		printf("WARNING: invept failed!\n");
1217 
1218 	return true;
1219 }
1220 
1221 static int pml_exit_handler(void)
1222 {
1223 	u16 index, count;
1224 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1225 	u64 *pmlbuf = pml_log;
1226 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1227 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1228 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1229 
1230 	switch (reason) {
1231 	case VMX_VMCALL:
1232 		switch (vmx_get_test_stage()) {
1233 		case 0:
1234 			index = vmcs_read(GUEST_PML_INDEX);
1235 			for (count = index + 1; count < PML_INDEX; count++) {
1236 				if (pmlbuf[count] == (u64)data_page2) {
1237 					vmx_inc_test_stage();
1238 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1239 					break;
1240 				}
1241 			}
1242 			break;
1243 		case 1:
1244 			index = vmcs_read(GUEST_PML_INDEX);
1245 			/* Keep clearing the dirty bit till a overflow */
1246 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1247 			break;
1248 		default:
1249 			report("unexpected stage, %d.", false,
1250 			       vmx_get_test_stage());
1251 			print_vmexit_info();
1252 			return VMX_TEST_VMEXIT;
1253 		}
1254 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1255 		return VMX_TEST_RESUME;
1256 	case VMX_PML_FULL:
1257 		vmx_inc_test_stage();
1258 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1259 		return VMX_TEST_RESUME;
1260 	default:
1261 		report("Unknown exit reason, %ld", false, reason);
1262 		print_vmexit_info();
1263 	}
1264 	return VMX_TEST_VMEXIT;
1265 }
1266 
1267 static int ept_exit_handler_common(bool have_ad)
1268 {
1269 	u64 guest_rip;
1270 	u64 guest_cr3;
1271 	ulong reason;
1272 	u32 insn_len;
1273 	u32 exit_qual;
1274 	static unsigned long data_page1_pte, data_page1_pte_pte, memaddr_pte;
1275 
1276 	guest_rip = vmcs_read(GUEST_RIP);
1277 	guest_cr3 = vmcs_read(GUEST_CR3);
1278 	reason = vmcs_read(EXI_REASON) & 0xff;
1279 	insn_len = vmcs_read(EXI_INST_LEN);
1280 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1281 	switch (reason) {
1282 	case VMX_VMCALL:
1283 		switch (vmx_get_test_stage()) {
1284 		case 0:
1285 			check_ept_ad(pml4, guest_cr3,
1286 				     (unsigned long)data_page1,
1287 				     have_ad ? EPT_ACCESS_FLAG : 0,
1288 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1289 			check_ept_ad(pml4, guest_cr3,
1290 				     (unsigned long)data_page2,
1291 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1292 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1293 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1294 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1295 			if (have_ad)
1296 				ept_sync(INVEPT_SINGLE, eptp);;
1297 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1298 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1299 				vmx_inc_test_stage();
1300 				install_ept(pml4, (unsigned long)data_page2,
1301 						(unsigned long)data_page2,
1302 						EPT_RA | EPT_WA | EPT_EA);
1303 			} else
1304 				report("EPT basic framework - write", 0);
1305 			break;
1306 		case 1:
1307 			install_ept(pml4, (unsigned long)data_page1,
1308  				(unsigned long)data_page1, EPT_WA);
1309 			ept_sync(INVEPT_SINGLE, eptp);
1310 			break;
1311 		case 2:
1312 			install_ept(pml4, (unsigned long)data_page1,
1313  				(unsigned long)data_page1,
1314  				EPT_RA | EPT_WA | EPT_EA |
1315  				(2 << EPT_MEM_TYPE_SHIFT));
1316 			ept_sync(INVEPT_SINGLE, eptp);
1317 			break;
1318 		case 3:
1319 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1320 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1321 						1, &data_page1_pte));
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 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1328 						2, &data_page1_pte));
1329 			data_page1_pte &= PAGE_MASK;
1330 			TEST_ASSERT(get_ept_pte(pml4, data_page1_pte,
1331 						2, &data_page1_pte_pte));
1332 			set_ept_pte(pml4, data_page1_pte, 2,
1333 				data_page1_pte_pte & ~EPT_PRESENT);
1334 			ept_sync(INVEPT_SINGLE, eptp);
1335 			break;
1336 		case 5:
1337 			install_ept(pml4, (unsigned long)pci_physaddr,
1338 				(unsigned long)pci_physaddr, 0);
1339 			ept_sync(INVEPT_SINGLE, eptp);
1340 			break;
1341 		case 7:
1342 			if (!invept_test(0, eptp))
1343 				vmx_inc_test_stage();
1344 			break;
1345 		// Should not reach here
1346 		default:
1347 			report("ERROR - unexpected stage, %d.", false,
1348 			       vmx_get_test_stage());
1349 			print_vmexit_info();
1350 			return VMX_TEST_VMEXIT;
1351 		}
1352 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1353 		return VMX_TEST_RESUME;
1354 	case VMX_EPT_MISCONFIG:
1355 		switch (vmx_get_test_stage()) {
1356 		case 1:
1357 		case 2:
1358 			vmx_inc_test_stage();
1359 			install_ept(pml4, (unsigned long)data_page1,
1360  				(unsigned long)data_page1,
1361  				EPT_RA | EPT_WA | EPT_EA);
1362 			ept_sync(INVEPT_SINGLE, eptp);
1363 			break;
1364 		// Should not reach here
1365 		default:
1366 			report("ERROR - unexpected stage, %d.", false,
1367 			       vmx_get_test_stage());
1368 			print_vmexit_info();
1369 			return VMX_TEST_VMEXIT;
1370 		}
1371 		return VMX_TEST_RESUME;
1372 	case VMX_EPT_VIOLATION:
1373 		switch(vmx_get_test_stage()) {
1374 		case 3:
1375 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1376 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1377 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1378 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1379 					EPT_VLT_PADDR))
1380 				vmx_inc_test_stage();
1381 			set_ept_pte(pml4, (unsigned long)data_page1,
1382 				1, data_page1_pte | (EPT_PRESENT));
1383 			ept_sync(INVEPT_SINGLE, eptp);
1384 			break;
1385 		case 4:
1386 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1387 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1388 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1389 			if (exit_qual == (EPT_VLT_RD |
1390 					  (have_ad ? EPT_VLT_WR : 0) |
1391 					  EPT_VLT_LADDR_VLD))
1392 				vmx_inc_test_stage();
1393 			set_ept_pte(pml4, data_page1_pte, 2,
1394 				data_page1_pte_pte | (EPT_PRESENT));
1395 			ept_sync(INVEPT_SINGLE, eptp);
1396 			break;
1397 		case 5:
1398 			if (exit_qual & EPT_VLT_RD)
1399 				vmx_inc_test_stage();
1400 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1401 						1, &memaddr_pte));
1402 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA);
1403 			ept_sync(INVEPT_SINGLE, eptp);
1404 			break;
1405 		case 6:
1406 			if (exit_qual & EPT_VLT_WR)
1407 				vmx_inc_test_stage();
1408 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1409 						1, &memaddr_pte));
1410 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA | EPT_WA);
1411 			ept_sync(INVEPT_SINGLE, eptp);
1412 			break;
1413 		default:
1414 			// Should not reach here
1415 			report("ERROR : unexpected stage, %d", false,
1416 			       vmx_get_test_stage());
1417 			print_vmexit_info();
1418 			return VMX_TEST_VMEXIT;
1419 		}
1420 		return VMX_TEST_RESUME;
1421 	default:
1422 		report("Unknown exit reason, %ld", false, reason);
1423 		print_vmexit_info();
1424 	}
1425 	return VMX_TEST_VMEXIT;
1426 }
1427 
1428 static int ept_exit_handler(void)
1429 {
1430 	return ept_exit_handler_common(false);
1431 }
1432 
1433 static int eptad_init(struct vmcs *vmcs)
1434 {
1435 	int r = ept_init_common(true);
1436 
1437 	if (r == VMX_TEST_EXIT)
1438 		return r;
1439 
1440 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1441 		printf("\tEPT A/D bits are not supported");
1442 		return VMX_TEST_EXIT;
1443 	}
1444 
1445 	return r;
1446 }
1447 
1448 static int pml_init(struct vmcs *vmcs)
1449 {
1450 	u32 ctrl_cpu;
1451 	int r = eptad_init(vmcs);
1452 
1453 	if (r == VMX_TEST_EXIT)
1454 		return r;
1455 
1456 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1457 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1458 		printf("\tPML is not supported");
1459 		return VMX_TEST_EXIT;
1460 	}
1461 
1462 	pml_log = alloc_page();
1463 	memset(pml_log, 0x0, PAGE_SIZE);
1464 	vmcs_write(PMLADDR, (u64)pml_log);
1465 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1466 
1467 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1468 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1469 
1470 	return VMX_TEST_START;
1471 }
1472 
1473 static void pml_main(void)
1474 {
1475 	int count = 0;
1476 
1477 	vmx_set_test_stage(0);
1478 	*((u32 *)data_page2) = 0x1;
1479 	vmcall();
1480 	report("PML - Dirty GPA Logging", vmx_get_test_stage() == 1);
1481 
1482 	while (vmx_get_test_stage() == 1) {
1483 		vmcall();
1484 		*((u32 *)data_page2) = 0x1;
1485 		if (count++ > PML_INDEX)
1486 			break;
1487 	}
1488 	report("PML Full Event", vmx_get_test_stage() == 2);
1489 }
1490 
1491 static void eptad_main(void)
1492 {
1493 	ept_common();
1494 }
1495 
1496 static int eptad_exit_handler(void)
1497 {
1498 	return ept_exit_handler_common(true);
1499 }
1500 
1501 static bool invvpid_test(int type, u16 vpid)
1502 {
1503 	bool ret, supported;
1504 
1505 	supported = ept_vpid.val &
1506 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1507 	ret = invvpid(type, vpid, 0);
1508 
1509 	if (ret == !supported)
1510 		return false;
1511 
1512 	if (!supported)
1513 		printf("WARNING: unsupported invvpid passed!\n");
1514 	else
1515 		printf("WARNING: invvpid failed!\n");
1516 
1517 	return true;
1518 }
1519 
1520 static int vpid_init(struct vmcs *vmcs)
1521 {
1522 	u32 ctrl_cpu1;
1523 
1524 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1525 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1526 		printf("\tVPID is not supported");
1527 		return VMX_TEST_EXIT;
1528 	}
1529 
1530 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1531 	ctrl_cpu1 |= CPU_VPID;
1532 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1533 	return VMX_TEST_START;
1534 }
1535 
1536 static void vpid_main(void)
1537 {
1538 	vmx_set_test_stage(0);
1539 	vmcall();
1540 	report("INVVPID SINGLE ADDRESS", vmx_get_test_stage() == 1);
1541 	vmx_set_test_stage(2);
1542 	vmcall();
1543 	report("INVVPID SINGLE", vmx_get_test_stage() == 3);
1544 	vmx_set_test_stage(4);
1545 	vmcall();
1546 	report("INVVPID ALL", vmx_get_test_stage() == 5);
1547 }
1548 
1549 static int vpid_exit_handler(void)
1550 {
1551 	u64 guest_rip;
1552 	ulong reason;
1553 	u32 insn_len;
1554 
1555 	guest_rip = vmcs_read(GUEST_RIP);
1556 	reason = vmcs_read(EXI_REASON) & 0xff;
1557 	insn_len = vmcs_read(EXI_INST_LEN);
1558 
1559 	switch (reason) {
1560 	case VMX_VMCALL:
1561 		switch(vmx_get_test_stage()) {
1562 		case 0:
1563 			if (!invvpid_test(INVVPID_ADDR, 1))
1564 				vmx_inc_test_stage();
1565 			break;
1566 		case 2:
1567 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1568 				vmx_inc_test_stage();
1569 			break;
1570 		case 4:
1571 			if (!invvpid_test(INVVPID_ALL, 1))
1572 				vmx_inc_test_stage();
1573 			break;
1574 		default:
1575 			report("ERROR: unexpected stage, %d", false,
1576 					vmx_get_test_stage());
1577 			print_vmexit_info();
1578 			return VMX_TEST_VMEXIT;
1579 		}
1580 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1581 		return VMX_TEST_RESUME;
1582 	default:
1583 		report("Unknown exit reason, %ld", false, reason);
1584 		print_vmexit_info();
1585 	}
1586 	return VMX_TEST_VMEXIT;
1587 }
1588 
1589 #define TIMER_VECTOR	222
1590 
1591 static volatile bool timer_fired;
1592 
1593 static void timer_isr(isr_regs_t *regs)
1594 {
1595 	timer_fired = true;
1596 	apic_write(APIC_EOI, 0);
1597 }
1598 
1599 static int interrupt_init(struct vmcs *vmcs)
1600 {
1601 	msr_bmp_init();
1602 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1603 	handle_irq(TIMER_VECTOR, timer_isr);
1604 	return VMX_TEST_START;
1605 }
1606 
1607 static void interrupt_main(void)
1608 {
1609 	long long start, loops;
1610 
1611 	vmx_set_test_stage(0);
1612 
1613 	apic_write(APIC_LVTT, TIMER_VECTOR);
1614 	irq_enable();
1615 
1616 	apic_write(APIC_TMICT, 1);
1617 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1618 		asm volatile ("nop");
1619 	report("direct interrupt while running guest", timer_fired);
1620 
1621 	apic_write(APIC_TMICT, 0);
1622 	irq_disable();
1623 	vmcall();
1624 	timer_fired = false;
1625 	apic_write(APIC_TMICT, 1);
1626 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1627 		asm volatile ("nop");
1628 	report("intercepted interrupt while running guest", timer_fired);
1629 
1630 	irq_enable();
1631 	apic_write(APIC_TMICT, 0);
1632 	irq_disable();
1633 	vmcall();
1634 	timer_fired = false;
1635 	start = rdtsc();
1636 	apic_write(APIC_TMICT, 1000000);
1637 
1638 	asm volatile ("sti; hlt");
1639 
1640 	report("direct interrupt + hlt",
1641 	       rdtsc() - start > 1000000 && timer_fired);
1642 
1643 	apic_write(APIC_TMICT, 0);
1644 	irq_disable();
1645 	vmcall();
1646 	timer_fired = false;
1647 	start = rdtsc();
1648 	apic_write(APIC_TMICT, 1000000);
1649 
1650 	asm volatile ("sti; hlt");
1651 
1652 	report("intercepted interrupt + hlt",
1653 	       rdtsc() - start > 10000 && timer_fired);
1654 
1655 	apic_write(APIC_TMICT, 0);
1656 	irq_disable();
1657 	vmcall();
1658 	timer_fired = false;
1659 	start = rdtsc();
1660 	apic_write(APIC_TMICT, 1000000);
1661 
1662 	irq_enable();
1663 	asm volatile ("nop");
1664 	vmcall();
1665 
1666 	report("direct interrupt + activity state hlt",
1667 	       rdtsc() - start > 10000 && timer_fired);
1668 
1669 	apic_write(APIC_TMICT, 0);
1670 	irq_disable();
1671 	vmcall();
1672 	timer_fired = false;
1673 	start = rdtsc();
1674 	apic_write(APIC_TMICT, 1000000);
1675 
1676 	irq_enable();
1677 	asm volatile ("nop");
1678 	vmcall();
1679 
1680 	report("intercepted interrupt + activity state hlt",
1681 	       rdtsc() - start > 10000 && timer_fired);
1682 
1683 	apic_write(APIC_TMICT, 0);
1684 	irq_disable();
1685 	vmx_set_test_stage(7);
1686 	vmcall();
1687 	timer_fired = false;
1688 	apic_write(APIC_TMICT, 1);
1689 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1690 		asm volatile ("nop");
1691 	report("running a guest with interrupt acknowledgement set", timer_fired);
1692 
1693 	apic_write(APIC_TMICT, 0);
1694 	irq_enable();
1695 	timer_fired = false;
1696 	vmcall();
1697 	report("Inject an event to a halted guest", timer_fired);
1698 }
1699 
1700 static int interrupt_exit_handler(void)
1701 {
1702 	u64 guest_rip = vmcs_read(GUEST_RIP);
1703 	ulong reason = vmcs_read(EXI_REASON) & 0xff;
1704 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1705 
1706 	switch (reason) {
1707 	case VMX_VMCALL:
1708 		switch (vmx_get_test_stage()) {
1709 		case 0:
1710 		case 2:
1711 		case 5:
1712 			vmcs_write(PIN_CONTROLS,
1713 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1714 			break;
1715 		case 7:
1716 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1717 			vmcs_write(PIN_CONTROLS,
1718 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1719 			break;
1720 		case 1:
1721 		case 3:
1722 			vmcs_write(PIN_CONTROLS,
1723 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1724 			break;
1725 		case 4:
1726 		case 6:
1727 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1728 			break;
1729 
1730 		case 8:
1731 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1732 			vmcs_write(ENT_INTR_INFO,
1733 				   TIMER_VECTOR |
1734 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1735 				   INTR_INFO_VALID_MASK);
1736 			break;
1737 		}
1738 		vmx_inc_test_stage();
1739 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1740 		return VMX_TEST_RESUME;
1741 	case VMX_EXTINT:
1742 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1743 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1744 			handle_external_interrupt(vector);
1745 		} else {
1746 			irq_enable();
1747 			asm volatile ("nop");
1748 			irq_disable();
1749 		}
1750 		if (vmx_get_test_stage() >= 2)
1751 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1752 		return VMX_TEST_RESUME;
1753 	default:
1754 		report("Unknown exit reason, %ld", false, reason);
1755 		print_vmexit_info();
1756 	}
1757 
1758 	return VMX_TEST_VMEXIT;
1759 }
1760 
1761 static int dbgctls_init(struct vmcs *vmcs)
1762 {
1763 	u64 dr7 = 0x402;
1764 	u64 zero = 0;
1765 
1766 	msr_bmp_init();
1767 	asm volatile(
1768 		"mov %0,%%dr0\n\t"
1769 		"mov %0,%%dr1\n\t"
1770 		"mov %0,%%dr2\n\t"
1771 		"mov %1,%%dr7\n\t"
1772 		: : "r" (zero), "r" (dr7));
1773 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1774 	vmcs_write(GUEST_DR7, 0x404);
1775 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1776 
1777 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1778 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1779 
1780 	return VMX_TEST_START;
1781 }
1782 
1783 static void dbgctls_main(void)
1784 {
1785 	u64 dr7, debugctl;
1786 
1787 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1788 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1789 	/* Commented out: KVM does not support DEBUGCTL so far */
1790 	(void)debugctl;
1791 	report("Load debug controls", dr7 == 0x404 /* && debugctl == 0x2 */);
1792 
1793 	dr7 = 0x408;
1794 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1795 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1796 
1797 	vmx_set_test_stage(0);
1798 	vmcall();
1799 	report("Save debug controls", vmx_get_test_stage() == 1);
1800 
1801 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1802 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1803 		printf("\tDebug controls are always loaded/saved\n");
1804 		return;
1805 	}
1806 	vmx_set_test_stage(2);
1807 	vmcall();
1808 
1809 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1810 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1811 	/* Commented out: KVM does not support DEBUGCTL so far */
1812 	(void)debugctl;
1813 	report("Guest=host debug controls", dr7 == 0x402 /* && debugctl == 0x1 */);
1814 
1815 	dr7 = 0x408;
1816 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1817 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1818 
1819 	vmx_set_test_stage(3);
1820 	vmcall();
1821 	report("Don't save debug controls", vmx_get_test_stage() == 4);
1822 }
1823 
1824 static int dbgctls_exit_handler(void)
1825 {
1826 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
1827 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1828 	u64 guest_rip = vmcs_read(GUEST_RIP);
1829 	u64 dr7, debugctl;
1830 
1831 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1832 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1833 
1834 	switch (reason) {
1835 	case VMX_VMCALL:
1836 		switch (vmx_get_test_stage()) {
1837 		case 0:
1838 			if (dr7 == 0x400 && debugctl == 0 &&
1839 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1840 			    Commented out: KVM does not support DEBUGCTL so far
1841 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1842 				vmx_inc_test_stage();
1843 			break;
1844 		case 2:
1845 			dr7 = 0x402;
1846 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
1847 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1848 			vmcs_write(GUEST_DR7, 0x404);
1849 			vmcs_write(GUEST_DEBUGCTL, 0x2);
1850 
1851 			vmcs_write(ENT_CONTROLS,
1852 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
1853 			vmcs_write(EXI_CONTROLS,
1854 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
1855 			break;
1856 		case 3:
1857 			if (dr7 == 0x400 && debugctl == 0 &&
1858 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
1859 			    Commented out: KVM does not support DEBUGCTL so far
1860 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
1861 				vmx_inc_test_stage();
1862 			break;
1863 		}
1864 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1865 		return VMX_TEST_RESUME;
1866 	default:
1867 		report("Unknown exit reason, %d", false, reason);
1868 		print_vmexit_info();
1869 	}
1870 	return VMX_TEST_VMEXIT;
1871 }
1872 
1873 struct vmx_msr_entry {
1874 	u32 index;
1875 	u32 reserved;
1876 	u64 value;
1877 } __attribute__((packed));
1878 
1879 #define MSR_MAGIC 0x31415926
1880 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
1881 
1882 static int msr_switch_init(struct vmcs *vmcs)
1883 {
1884 	msr_bmp_init();
1885 	exit_msr_store = alloc_page();
1886 	exit_msr_load = alloc_page();
1887 	entry_msr_load = alloc_page();
1888 	memset(exit_msr_store, 0, PAGE_SIZE);
1889 	memset(exit_msr_load, 0, PAGE_SIZE);
1890 	memset(entry_msr_load, 0, PAGE_SIZE);
1891 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
1892 	entry_msr_load[0].value = MSR_MAGIC;
1893 
1894 	vmx_set_test_stage(1);
1895 	vmcs_write(ENT_MSR_LD_CNT, 1);
1896 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
1897 	vmcs_write(EXI_MSR_ST_CNT, 1);
1898 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
1899 	vmcs_write(EXI_MSR_LD_CNT, 1);
1900 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
1901 	return VMX_TEST_START;
1902 }
1903 
1904 static void msr_switch_main(void)
1905 {
1906 	if (vmx_get_test_stage() == 1) {
1907 		report("VM entry MSR load",
1908 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC);
1909 		vmx_set_test_stage(2);
1910 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
1911 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
1912 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
1913 		exit_msr_load[0].value = MSR_MAGIC + 2;
1914 	}
1915 	vmcall();
1916 }
1917 
1918 static int msr_switch_exit_handler(void)
1919 {
1920 	ulong reason;
1921 
1922 	reason = vmcs_read(EXI_REASON);
1923 	if (reason == VMX_VMCALL && vmx_get_test_stage() == 2) {
1924 		report("VM exit MSR store",
1925 			exit_msr_store[0].value == MSR_MAGIC + 1);
1926 		report("VM exit MSR load",
1927 			rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2);
1928 		vmx_set_test_stage(3);
1929 		entry_msr_load[0].index = MSR_FS_BASE;
1930 		return VMX_TEST_RESUME;
1931 	}
1932 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1933 		__func__, vmx_get_test_stage(), reason);
1934 	return VMX_TEST_EXIT;
1935 }
1936 
1937 static int msr_switch_entry_failure(struct vmentry_failure *failure)
1938 {
1939 	ulong reason;
1940 
1941 	if (failure->early) {
1942 		printf("ERROR %s: early exit\n", __func__);
1943 		return VMX_TEST_EXIT;
1944 	}
1945 
1946 	reason = vmcs_read(EXI_REASON);
1947 	if (reason == (VMX_ENTRY_FAILURE | VMX_FAIL_MSR) &&
1948 	    vmx_get_test_stage() == 3) {
1949 		report("VM entry MSR load: try to load FS_BASE",
1950 			vmcs_read(EXI_QUALIFICATION) == 1);
1951 		return VMX_TEST_VMEXIT;
1952 	}
1953 	printf("ERROR %s: unexpected stage=%u or reason=%lu\n",
1954 		__func__, vmx_get_test_stage(), reason);
1955 	return VMX_TEST_EXIT;
1956 }
1957 
1958 static int vmmcall_init(struct vmcs *vmcs)
1959 {
1960 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
1961 	return VMX_TEST_START;
1962 }
1963 
1964 static void vmmcall_main(void)
1965 {
1966 	asm volatile(
1967 		"mov $0xABCD, %%rax\n\t"
1968 		"vmmcall\n\t"
1969 		::: "rax");
1970 
1971 	report("VMMCALL", 0);
1972 }
1973 
1974 static int vmmcall_exit_handler(void)
1975 {
1976 	ulong reason;
1977 
1978 	reason = vmcs_read(EXI_REASON);
1979 	switch (reason) {
1980 	case VMX_VMCALL:
1981 		printf("here\n");
1982 		report("VMMCALL triggers #UD", 0);
1983 		break;
1984 	case VMX_EXC_NMI:
1985 		report("VMMCALL triggers #UD",
1986 		       (vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR);
1987 		break;
1988 	default:
1989 		report("Unknown exit reason, %ld", false, reason);
1990 		print_vmexit_info();
1991 	}
1992 
1993 	return VMX_TEST_VMEXIT;
1994 }
1995 
1996 static int disable_rdtscp_init(struct vmcs *vmcs)
1997 {
1998 	u32 ctrl_cpu1;
1999 
2000 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
2001 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
2002 		ctrl_cpu1 &= ~CPU_RDTSCP;
2003 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
2004 	}
2005 
2006 	return VMX_TEST_START;
2007 }
2008 
2009 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
2010 {
2011 	switch (vmx_get_test_stage()) {
2012 	case 0:
2013 		report("RDTSCP triggers #UD", true);
2014 		vmx_inc_test_stage();
2015 		regs->rip += 3;
2016 		break;
2017 	case 2:
2018 		report("RDPID triggers #UD", true);
2019 		vmx_inc_test_stage();
2020 		regs->rip += 4;
2021 		break;
2022 	}
2023 	return;
2024 
2025 }
2026 
2027 static void disable_rdtscp_main(void)
2028 {
2029 	/* Test that #UD is properly injected in L2.  */
2030 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
2031 
2032 	vmx_set_test_stage(0);
2033 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
2034 	vmcall();
2035 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
2036 
2037 	handle_exception(UD_VECTOR, 0);
2038 	vmcall();
2039 }
2040 
2041 static int disable_rdtscp_exit_handler(void)
2042 {
2043 	unsigned int reason = vmcs_read(EXI_REASON) & 0xff;
2044 
2045 	switch (reason) {
2046 	case VMX_VMCALL:
2047 		switch (vmx_get_test_stage()) {
2048 		case 0:
2049 			report("RDTSCP triggers #UD", false);
2050 			vmx_inc_test_stage();
2051 			/* fallthrough */
2052 		case 1:
2053 			vmx_inc_test_stage();
2054 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
2055 			return VMX_TEST_RESUME;
2056 		case 2:
2057 			report("RDPID triggers #UD", false);
2058 			break;
2059 		}
2060 		break;
2061 
2062 	default:
2063 		report("Unknown exit reason, %d", false, reason);
2064 		print_vmexit_info();
2065 	}
2066 	return VMX_TEST_VMEXIT;
2067 }
2068 
2069 static int int3_init(struct vmcs *vmcs)
2070 {
2071 	vmcs_write(EXC_BITMAP, ~0u);
2072 	return VMX_TEST_START;
2073 }
2074 
2075 static void int3_guest_main(void)
2076 {
2077 	asm volatile ("int3");
2078 }
2079 
2080 static int int3_exit_handler(void)
2081 {
2082 	u32 reason = vmcs_read(EXI_REASON);
2083 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2084 
2085 	report("L1 intercepts #BP", reason == VMX_EXC_NMI &&
2086 	       (intr_info & INTR_INFO_VALID_MASK) &&
2087 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
2088 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2089 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2090 
2091 	return VMX_TEST_VMEXIT;
2092 }
2093 
2094 static int into_init(struct vmcs *vmcs)
2095 {
2096 	vmcs_write(EXC_BITMAP, ~0u);
2097 	return VMX_TEST_START;
2098 }
2099 
2100 static void into_guest_main(void)
2101 {
2102 	struct far_pointer32 fp = {
2103 		.offset = (uintptr_t)&&into,
2104 		.selector = KERNEL_CS32,
2105 	};
2106 	register uintptr_t rsp asm("rsp");
2107 
2108 	if (fp.offset != (uintptr_t)&&into) {
2109 		printf("Code address too high.\n");
2110 		return;
2111 	}
2112 	if ((u32)rsp != rsp) {
2113 		printf("Stack address too high.\n");
2114 		return;
2115 	}
2116 
2117 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2118 	return;
2119 into:
2120 	asm volatile (".code32;"
2121 		      "movl $0x7fffffff, %eax;"
2122 		      "addl %eax, %eax;"
2123 		      "into;"
2124 		      "lret;"
2125 		      ".code64");
2126 	__builtin_unreachable();
2127 }
2128 
2129 static int into_exit_handler(void)
2130 {
2131 	u32 reason = vmcs_read(EXI_REASON);
2132 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2133 
2134 	report("L1 intercepts #OF", reason == VMX_EXC_NMI &&
2135 	       (intr_info & INTR_INFO_VALID_MASK) &&
2136 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2137 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2138 		INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION);
2139 
2140 	return VMX_TEST_VMEXIT;
2141 }
2142 
2143 static void exit_monitor_from_l2_main(void)
2144 {
2145 	printf("Calling exit(0) from l2...\n");
2146 	exit(0);
2147 }
2148 
2149 static int exit_monitor_from_l2_handler(void)
2150 {
2151 	report("The guest should have killed the VMM", false);
2152 	return VMX_TEST_EXIT;
2153 }
2154 
2155 static void assert_exit_reason(u64 expected)
2156 {
2157 	u64 actual = vmcs_read(EXI_REASON);
2158 
2159 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2160 			   exit_reason_description(expected),
2161 			   exit_reason_description(actual));
2162 }
2163 
2164 static void skip_exit_insn(void)
2165 {
2166 	u64 guest_rip = vmcs_read(GUEST_RIP);
2167 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2168 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2169 }
2170 
2171 static void skip_exit_vmcall(void)
2172 {
2173 	assert_exit_reason(VMX_VMCALL);
2174 	skip_exit_insn();
2175 }
2176 
2177 static void v2_null_test_guest(void)
2178 {
2179 }
2180 
2181 static void v2_null_test(void)
2182 {
2183 	test_set_guest(v2_null_test_guest);
2184 	enter_guest();
2185 	report(__func__, 1);
2186 }
2187 
2188 static void v2_multiple_entries_test_guest(void)
2189 {
2190 	vmx_set_test_stage(1);
2191 	vmcall();
2192 	vmx_set_test_stage(2);
2193 }
2194 
2195 static void v2_multiple_entries_test(void)
2196 {
2197 	test_set_guest(v2_multiple_entries_test_guest);
2198 	enter_guest();
2199 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2200 	skip_exit_vmcall();
2201 	enter_guest();
2202 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2203 	report(__func__, 1);
2204 }
2205 
2206 static int fixture_test_data = 1;
2207 
2208 static void fixture_test_teardown(void *data)
2209 {
2210 	*((int *) data) = 1;
2211 }
2212 
2213 static void fixture_test_guest(void)
2214 {
2215 	fixture_test_data++;
2216 }
2217 
2218 
2219 static void fixture_test_setup(void)
2220 {
2221 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2222 			   "fixture_test_teardown didn't run?!");
2223 	fixture_test_data = 2;
2224 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2225 	test_set_guest(fixture_test_guest);
2226 }
2227 
2228 static void fixture_test_case1(void)
2229 {
2230 	fixture_test_setup();
2231 	TEST_ASSERT_EQ(2, fixture_test_data);
2232 	enter_guest();
2233 	TEST_ASSERT_EQ(3, fixture_test_data);
2234 	report(__func__, 1);
2235 }
2236 
2237 static void fixture_test_case2(void)
2238 {
2239 	fixture_test_setup();
2240 	TEST_ASSERT_EQ(2, fixture_test_data);
2241 	enter_guest();
2242 	TEST_ASSERT_EQ(3, fixture_test_data);
2243 	report(__func__, 1);
2244 }
2245 
2246 enum ept_access_op {
2247 	OP_READ,
2248 	OP_WRITE,
2249 	OP_EXEC,
2250 	OP_FLUSH_TLB,
2251 	OP_EXIT,
2252 };
2253 
2254 static struct ept_access_test_data {
2255 	unsigned long gpa;
2256 	unsigned long *gva;
2257 	unsigned long hpa;
2258 	unsigned long *hva;
2259 	enum ept_access_op op;
2260 } ept_access_test_data;
2261 
2262 extern unsigned char ret42_start;
2263 extern unsigned char ret42_end;
2264 
2265 /* Returns 42. */
2266 asm(
2267 	".align 64\n"
2268 	"ret42_start:\n"
2269 	"mov $42, %eax\n"
2270 	"ret\n"
2271 	"ret42_end:\n"
2272 );
2273 
2274 static void
2275 diagnose_ept_violation_qual(u64 expected, u64 actual)
2276 {
2277 
2278 #define DIAGNOSE(flag)							\
2279 do {									\
2280 	if ((expected & flag) != (actual & flag))			\
2281 		printf(#flag " %sexpected\n",				\
2282 		       (expected & flag) ? "" : "un");			\
2283 } while (0)
2284 
2285 	DIAGNOSE(EPT_VLT_RD);
2286 	DIAGNOSE(EPT_VLT_WR);
2287 	DIAGNOSE(EPT_VLT_FETCH);
2288 	DIAGNOSE(EPT_VLT_PERM_RD);
2289 	DIAGNOSE(EPT_VLT_PERM_WR);
2290 	DIAGNOSE(EPT_VLT_PERM_EX);
2291 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2292 	DIAGNOSE(EPT_VLT_PADDR);
2293 
2294 #undef DIAGNOSE
2295 }
2296 
2297 static void do_ept_access_op(enum ept_access_op op)
2298 {
2299 	ept_access_test_data.op = op;
2300 	enter_guest();
2301 }
2302 
2303 /*
2304  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2305  * needed by tests that modify guest PTEs.
2306  */
2307 static void ept_access_test_guest_flush_tlb(void)
2308 {
2309 	do_ept_access_op(OP_FLUSH_TLB);
2310 	skip_exit_vmcall();
2311 }
2312 
2313 /*
2314  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2315  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2316  * a huge page.
2317  */
2318 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2319 				 unsigned long clear, unsigned long set)
2320 {
2321 	struct ept_access_test_data *data = &ept_access_test_data;
2322 	unsigned long orig_pte;
2323 	unsigned long pte;
2324 
2325 	/* Screw with the mapping at the requested level. */
2326 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2327 	pte = orig_pte;
2328 	if (mkhuge)
2329 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2330 	else
2331 		pte = orig_pte;
2332 	pte = (pte & ~clear) | set;
2333 	set_ept_pte(pml4, gpa, level, pte);
2334 	ept_sync(INVEPT_SINGLE, eptp);
2335 
2336 	return orig_pte;
2337 }
2338 
2339 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2340 {
2341 	set_ept_pte(pml4, gpa, level, orig_pte);
2342 }
2343 
2344 static void do_ept_violation(bool leaf, enum ept_access_op op,
2345 			     u64 expected_qual, u64 expected_paddr)
2346 {
2347 	u64 qual;
2348 
2349 	/* Try the access and observe the violation. */
2350 	do_ept_access_op(op);
2351 
2352 	assert_exit_reason(VMX_EPT_VIOLATION);
2353 
2354 	qual = vmcs_read(EXI_QUALIFICATION);
2355 
2356 	diagnose_ept_violation_qual(expected_qual, qual);
2357 	TEST_EXPECT_EQ(expected_qual, qual);
2358 
2359 	#if 0
2360 	/* Disable for now otherwise every test will fail */
2361 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2362 		       (unsigned long) (
2363 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2364 	#endif
2365 	/*
2366 	 * TODO: tests that probe expected_paddr in pages other than the one at
2367 	 * the beginning of the 1g region.
2368 	 */
2369 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2370 }
2371 
2372 static void
2373 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2374 			      unsigned long set, enum ept_access_op op,
2375 			      u64 expected_qual)
2376 {
2377 	struct ept_access_test_data *data = &ept_access_test_data;
2378 	unsigned long orig_pte;
2379 
2380 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2381 
2382 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2383 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2384 					 data->gpa);
2385 
2386 	/* Fix the violation and resume the op loop. */
2387 	ept_untwiddle(data->gpa, level, orig_pte);
2388 	enter_guest();
2389 	skip_exit_vmcall();
2390 }
2391 
2392 static void
2393 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2394 		       enum ept_access_op op, u64 expected_qual)
2395 {
2396 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2397 				      expected_qual);
2398 	if (ept_huge_pages_supported(level))
2399 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2400 					      expected_qual);
2401 }
2402 
2403 static void ept_violation(unsigned long clear, unsigned long set,
2404 			  enum ept_access_op op, u64 expected_qual)
2405 {
2406 	ept_violation_at_level(1, clear, set, op, expected_qual);
2407 	ept_violation_at_level(2, clear, set, op, expected_qual);
2408 	ept_violation_at_level(3, clear, set, op, expected_qual);
2409 	ept_violation_at_level(4, clear, set, op, expected_qual);
2410 }
2411 
2412 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2413 				       u64 expected_qual)
2414 {
2415 	ept_violation(EPT_PRESENT, access, op,
2416 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2417 }
2418 
2419 /*
2420  * For translations that don't involve a GVA, that is physical address (paddr)
2421  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2422  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2423  * translations don't involve GVAs, such as when the hardware does the guest
2424  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2425  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2426  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2427  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2428  *
2429  * Note that paddr violations can also be triggered by loading PAE page tables
2430  * with wonky addresses. We don't test that yet.
2431  *
2432  * This function modifies the EPT entry that maps the GPA that the guest page
2433  * table entry mapping ept_access_data.gva resides on.
2434  *
2435  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2436  *
2437  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2438  *
2439  *	@op		Guest operation to perform with ept_access_data.gva.
2440  *
2441  *	@expect_violation
2442  *			Is a violation expected during the paddr access?
2443  *
2444  *	@expected_qual	Expected qualification for the EPT violation.
2445  *			EPT_VLT_PADDR should be clear.
2446  */
2447 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2448 			     enum ept_access_op op, bool expect_violation,
2449 			     u64 expected_qual)
2450 {
2451 	struct ept_access_test_data *data = &ept_access_test_data;
2452 	unsigned long *ptep;
2453 	unsigned long gpa;
2454 	unsigned long orig_epte;
2455 
2456 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2457 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2458 	TEST_ASSERT(ptep);
2459 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2460 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2461 	ept_access_test_guest_flush_tlb();
2462 
2463 	/*
2464 	 * Now modify the access bits on the EPT entry for the GPA that the
2465 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2466 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2467 	 * constructed our test such that those other 511 PTEs aren't used by
2468 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2469 	 * PTE we're modifying is at the beginning of a 4K page and the
2470 	 * following 511 entires are also under our control (and not touched by
2471 	 * the guest).
2472 	 */
2473 	gpa = virt_to_phys(ptep);
2474 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2475 	/*
2476 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2477 	 * otherwise our level=1 twiddling below will fail. We use the
2478 	 * identity map (gpa = gpa) since page tables are shared with the host.
2479 	 */
2480 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2481 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2482 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2483 
2484 	if (expect_violation) {
2485 		do_ept_violation(/*leaf=*/true, op,
2486 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2487 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2488 		do_ept_access_op(op);
2489 	} else {
2490 		do_ept_access_op(op);
2491 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2492 	}
2493 
2494 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2495 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2496 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2497 
2498 	skip_exit_vmcall();
2499 }
2500 
2501 static void ept_access_allowed_paddr(unsigned long ept_access,
2502 				     unsigned long pte_ad,
2503 				     enum ept_access_op op)
2504 {
2505 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2506 			 /*expected_qual=*/-1);
2507 }
2508 
2509 static void ept_access_violation_paddr(unsigned long ept_access,
2510 				       unsigned long pte_ad,
2511 				       enum ept_access_op op,
2512 				       u64 expected_qual)
2513 {
2514 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2515 			 expected_qual);
2516 }
2517 
2518 
2519 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2520 					unsigned long clear,
2521 					unsigned long set,
2522 					enum ept_access_op op)
2523 {
2524 	struct ept_access_test_data *data = &ept_access_test_data;
2525 	unsigned long orig_pte;
2526 
2527 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2528 
2529 	/* No violation. Should proceed to vmcall. */
2530 	do_ept_access_op(op);
2531 	skip_exit_vmcall();
2532 
2533 	ept_untwiddle(data->gpa, level, orig_pte);
2534 }
2535 
2536 static void ept_allowed_at_level(int level, unsigned long clear,
2537 				 unsigned long set, enum ept_access_op op)
2538 {
2539 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2540 	if (ept_huge_pages_supported(level))
2541 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2542 }
2543 
2544 static void ept_allowed(unsigned long clear, unsigned long set,
2545 			enum ept_access_op op)
2546 {
2547 	ept_allowed_at_level(1, clear, set, op);
2548 	ept_allowed_at_level(2, clear, set, op);
2549 	ept_allowed_at_level(3, clear, set, op);
2550 	ept_allowed_at_level(4, clear, set, op);
2551 }
2552 
2553 static void ept_ignored_bit(int bit)
2554 {
2555 	/* Set the bit. */
2556 	ept_allowed(0, 1ul << bit, OP_READ);
2557 	ept_allowed(0, 1ul << bit, OP_WRITE);
2558 	ept_allowed(0, 1ul << bit, OP_EXEC);
2559 
2560 	/* Clear the bit. */
2561 	ept_allowed(1ul << bit, 0, OP_READ);
2562 	ept_allowed(1ul << bit, 0, OP_WRITE);
2563 	ept_allowed(1ul << bit, 0, OP_EXEC);
2564 }
2565 
2566 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2567 {
2568 	ept_allowed(EPT_PRESENT, access, op);
2569 }
2570 
2571 
2572 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2573 					     unsigned long clear,
2574 					     unsigned long set,
2575 					     enum ept_access_op op)
2576 {
2577 	struct ept_access_test_data *data = &ept_access_test_data;
2578 	unsigned long orig_pte;
2579 
2580 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2581 
2582 	do_ept_access_op(op);
2583 	assert_exit_reason(VMX_EPT_MISCONFIG);
2584 
2585 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2586 	#if 0
2587 	/* broken: */
2588 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2589 	#endif
2590 	#if 0
2591 	/*
2592 	 * broken:
2593 	 * According to description of exit qual for EPT violation,
2594 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2595 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2596 	 * to be set for msiconfig.
2597 	 */
2598 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2599 		       (unsigned long) (
2600 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2601 	#endif
2602 
2603 	/* Fix the violation and resume the op loop. */
2604 	ept_untwiddle(data->gpa, level, orig_pte);
2605 	enter_guest();
2606 	skip_exit_vmcall();
2607 }
2608 
2609 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2610 					  unsigned long clear,
2611 					  unsigned long set)
2612 {
2613 	/* The op shouldn't matter (read, write, exec), so try them all! */
2614 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2615 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2616 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2617 }
2618 
2619 static void ept_misconfig_at_level(int level, unsigned long clear,
2620 				   unsigned long set)
2621 {
2622 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2623 	if (ept_huge_pages_supported(level))
2624 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2625 }
2626 
2627 static void ept_misconfig(unsigned long clear, unsigned long set)
2628 {
2629 	ept_misconfig_at_level(1, clear, set);
2630 	ept_misconfig_at_level(2, clear, set);
2631 	ept_misconfig_at_level(3, clear, set);
2632 	ept_misconfig_at_level(4, clear, set);
2633 }
2634 
2635 static void ept_access_misconfig(unsigned long access)
2636 {
2637 	ept_misconfig(EPT_PRESENT, access);
2638 }
2639 
2640 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2641 {
2642 	/* Setting the bit causes a misconfig. */
2643 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2644 
2645 	/* Making the entry non-present turns reserved bits into ignored. */
2646 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2647 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2648 }
2649 
2650 static void ept_reserved_bit_at_level_huge(int level, int bit)
2651 {
2652 	/* Setting the bit causes a misconfig. */
2653 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2654 
2655 	/* Making the entry non-present turns reserved bits into ignored. */
2656 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2657 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2658 }
2659 
2660 static void ept_reserved_bit_at_level(int level, int bit)
2661 {
2662 	/* Setting the bit causes a misconfig. */
2663 	ept_misconfig_at_level(level, 0, 1ul << bit);
2664 
2665 	/* Making the entry non-present turns reserved bits into ignored. */
2666 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2667 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2668 }
2669 
2670 static void ept_reserved_bit(int bit)
2671 {
2672 	ept_reserved_bit_at_level(1, bit);
2673 	ept_reserved_bit_at_level(2, bit);
2674 	ept_reserved_bit_at_level(3, bit);
2675 	ept_reserved_bit_at_level(4, bit);
2676 }
2677 
2678 #define PAGE_2M_ORDER 9
2679 #define PAGE_1G_ORDER 18
2680 
2681 static void *get_1g_page(void)
2682 {
2683 	static void *alloc;
2684 
2685 	if (!alloc)
2686 		alloc = alloc_pages(PAGE_1G_ORDER);
2687 	return alloc;
2688 }
2689 
2690 static void ept_access_test_teardown(void *unused)
2691 {
2692 	/* Exit the guest cleanly. */
2693 	do_ept_access_op(OP_EXIT);
2694 }
2695 
2696 static void ept_access_test_guest(void)
2697 {
2698 	struct ept_access_test_data *data = &ept_access_test_data;
2699 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2700 
2701 	while (true) {
2702 		switch (data->op) {
2703 		case OP_READ:
2704 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2705 			break;
2706 		case OP_WRITE:
2707 			*data->gva = MAGIC_VAL_2;
2708 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2709 			*data->gva = MAGIC_VAL_1;
2710 			break;
2711 		case OP_EXEC:
2712 			TEST_ASSERT_EQ(42, code());
2713 			break;
2714 		case OP_FLUSH_TLB:
2715 			write_cr3(read_cr3());
2716 			break;
2717 		case OP_EXIT:
2718 			return;
2719 		default:
2720 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2721 		}
2722 		vmcall();
2723 	}
2724 }
2725 
2726 static void ept_access_test_setup(void)
2727 {
2728 	struct ept_access_test_data *data = &ept_access_test_data;
2729 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2730 	unsigned long size = npages * PAGE_SIZE;
2731 	unsigned long *page_table = current_page_table();
2732 	unsigned long pte;
2733 
2734 	if (setup_ept(false))
2735 		test_skip("EPT not supported");
2736 
2737 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2738 	if (cpuid_maxphyaddr() < 40)
2739 		test_skip("Test needs MAXPHYADDR >= 40");
2740 
2741 	test_set_guest(ept_access_test_guest);
2742 	test_add_teardown(ept_access_test_teardown, NULL);
2743 
2744 	data->hva = get_1g_page();
2745 	TEST_ASSERT(data->hva);
2746 	data->hpa = virt_to_phys(data->hva);
2747 
2748 	data->gpa = 1ul << 39;
2749 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2750 				   size);
2751 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2752 	install_pages(page_table, data->gpa, size, data->gva);
2753 
2754 	/*
2755 	 * Make sure nothing's mapped here so the tests that screw with the
2756 	 * pml4 entry don't inadvertently break something.
2757 	 */
2758 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2759 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2760 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2761 
2762 	data->hva[0] = MAGIC_VAL_1;
2763 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2764 }
2765 
2766 static void ept_access_test_not_present(void)
2767 {
2768 	ept_access_test_setup();
2769 	/* --- */
2770 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2771 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2772 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2773 }
2774 
2775 static void ept_access_test_read_only(void)
2776 {
2777 	ept_access_test_setup();
2778 
2779 	/* r-- */
2780 	ept_access_allowed(EPT_RA, OP_READ);
2781 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2782 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2783 }
2784 
2785 static void ept_access_test_write_only(void)
2786 {
2787 	ept_access_test_setup();
2788 	/* -w- */
2789 	ept_access_misconfig(EPT_WA);
2790 }
2791 
2792 static void ept_access_test_read_write(void)
2793 {
2794 	ept_access_test_setup();
2795 	/* rw- */
2796 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2797 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2798 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2799 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2800 }
2801 
2802 
2803 static void ept_access_test_execute_only(void)
2804 {
2805 	ept_access_test_setup();
2806 	/* --x */
2807 	if (ept_execute_only_supported()) {
2808 		ept_access_violation(EPT_EA, OP_READ,
2809 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2810 		ept_access_violation(EPT_EA, OP_WRITE,
2811 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2812 		ept_access_allowed(EPT_EA, OP_EXEC);
2813 	} else {
2814 		ept_access_misconfig(EPT_EA);
2815 	}
2816 }
2817 
2818 static void ept_access_test_read_execute(void)
2819 {
2820 	ept_access_test_setup();
2821 	/* r-x */
2822 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2823 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2824 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2825 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2826 }
2827 
2828 static void ept_access_test_write_execute(void)
2829 {
2830 	ept_access_test_setup();
2831 	/* -wx */
2832 	ept_access_misconfig(EPT_WA | EPT_EA);
2833 }
2834 
2835 static void ept_access_test_read_write_execute(void)
2836 {
2837 	ept_access_test_setup();
2838 	/* rwx */
2839 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
2840 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
2841 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
2842 }
2843 
2844 static void ept_access_test_reserved_bits(void)
2845 {
2846 	int i;
2847 	int maxphyaddr;
2848 
2849 	ept_access_test_setup();
2850 
2851 	/* Reserved bits above maxphyaddr. */
2852 	maxphyaddr = cpuid_maxphyaddr();
2853 	for (i = maxphyaddr; i <= 51; i++) {
2854 		report_prefix_pushf("reserved_bit=%d", i);
2855 		ept_reserved_bit(i);
2856 		report_prefix_pop();
2857 	}
2858 
2859 	/* Level-specific reserved bits. */
2860 	ept_reserved_bit_at_level_nohuge(2, 3);
2861 	ept_reserved_bit_at_level_nohuge(2, 4);
2862 	ept_reserved_bit_at_level_nohuge(2, 5);
2863 	ept_reserved_bit_at_level_nohuge(2, 6);
2864 	/* 2M alignment. */
2865 	for (i = 12; i < 20; i++) {
2866 		report_prefix_pushf("reserved_bit=%d", i);
2867 		ept_reserved_bit_at_level_huge(2, i);
2868 		report_prefix_pop();
2869 	}
2870 	ept_reserved_bit_at_level_nohuge(3, 3);
2871 	ept_reserved_bit_at_level_nohuge(3, 4);
2872 	ept_reserved_bit_at_level_nohuge(3, 5);
2873 	ept_reserved_bit_at_level_nohuge(3, 6);
2874 	/* 1G alignment. */
2875 	for (i = 12; i < 29; i++) {
2876 		report_prefix_pushf("reserved_bit=%d", i);
2877 		ept_reserved_bit_at_level_huge(3, i);
2878 		report_prefix_pop();
2879 	}
2880 	ept_reserved_bit_at_level(4, 3);
2881 	ept_reserved_bit_at_level(4, 4);
2882 	ept_reserved_bit_at_level(4, 5);
2883 	ept_reserved_bit_at_level(4, 6);
2884 	ept_reserved_bit_at_level(4, 7);
2885 }
2886 
2887 static void ept_access_test_ignored_bits(void)
2888 {
2889 	ept_access_test_setup();
2890 	/*
2891 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
2892 	 * far as translation is concerned even if AD bits are enabled in the
2893 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
2894 	 * control is 0.
2895 	 */
2896 	ept_ignored_bit(8);
2897 	ept_ignored_bit(9);
2898 	ept_ignored_bit(10);
2899 	ept_ignored_bit(11);
2900 	ept_ignored_bit(52);
2901 	ept_ignored_bit(53);
2902 	ept_ignored_bit(54);
2903 	ept_ignored_bit(55);
2904 	ept_ignored_bit(56);
2905 	ept_ignored_bit(57);
2906 	ept_ignored_bit(58);
2907 	ept_ignored_bit(59);
2908 	ept_ignored_bit(60);
2909 	ept_ignored_bit(61);
2910 	ept_ignored_bit(62);
2911 	ept_ignored_bit(63);
2912 }
2913 
2914 static void ept_access_test_paddr_not_present_ad_disabled(void)
2915 {
2916 	ept_access_test_setup();
2917 	ept_disable_ad_bits();
2918 
2919 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
2920 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
2921 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
2922 }
2923 
2924 static void ept_access_test_paddr_not_present_ad_enabled(void)
2925 {
2926 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
2927 
2928 	ept_access_test_setup();
2929 	ept_enable_ad_bits_or_skip_test();
2930 
2931 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
2932 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
2933 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
2934 }
2935 
2936 static void ept_access_test_paddr_read_only_ad_disabled(void)
2937 {
2938 	/*
2939 	 * When EPT AD bits are disabled, all accesses to guest paging
2940 	 * structures are reported separately as a read and (after
2941 	 * translation of the GPA to host physical address) a read+write
2942 	 * if the A/D bits have to be set.
2943 	 */
2944 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2945 
2946 	ept_access_test_setup();
2947 	ept_disable_ad_bits();
2948 
2949 	/* Can't update A bit, so all accesses fail. */
2950 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2951 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2952 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2953 	/* AD bits disabled, so only writes try to update the D bit. */
2954 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
2955 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2956 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
2957 	/* Both A and D already set, so read-only is OK. */
2958 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
2959 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
2960 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
2961 }
2962 
2963 static void ept_access_test_paddr_read_only_ad_enabled(void)
2964 {
2965 	/*
2966 	 * When EPT AD bits are enabled, all accesses to guest paging
2967 	 * structures are considered writes as far as EPT translation
2968 	 * is concerned.
2969 	 */
2970 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
2971 
2972 	ept_access_test_setup();
2973 	ept_enable_ad_bits_or_skip_test();
2974 
2975 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
2976 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
2977 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
2978 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
2979 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
2980 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
2981 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
2982 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
2983 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
2984 }
2985 
2986 static void ept_access_test_paddr_read_write(void)
2987 {
2988 	ept_access_test_setup();
2989 	/* Read-write access to paging structure. */
2990 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
2991 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
2992 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
2993 }
2994 
2995 static void ept_access_test_paddr_read_write_execute(void)
2996 {
2997 	ept_access_test_setup();
2998 	/* RWX access to paging structure. */
2999 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
3000 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
3001 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
3002 }
3003 
3004 static void ept_access_test_paddr_read_execute_ad_disabled(void)
3005 {
3006   	/*
3007 	 * When EPT AD bits are disabled, all accesses to guest paging
3008 	 * structures are reported separately as a read and (after
3009 	 * translation of the GPA to host physical address) a read+write
3010 	 * if the A/D bits have to be set.
3011 	 */
3012 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3013 
3014 	ept_access_test_setup();
3015 	ept_disable_ad_bits();
3016 
3017 	/* Can't update A bit, so all accesses fail. */
3018 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3019 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3020 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3021 	/* AD bits disabled, so only writes try to update the D bit. */
3022 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
3023 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3024 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
3025 	/* Both A and D already set, so read-only is OK. */
3026 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
3027 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
3028 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
3029 }
3030 
3031 static void ept_access_test_paddr_read_execute_ad_enabled(void)
3032 {
3033 	/*
3034 	 * When EPT AD bits are enabled, all accesses to guest paging
3035 	 * structures are considered writes as far as EPT translation
3036 	 * is concerned.
3037 	 */
3038 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3039 
3040 	ept_access_test_setup();
3041 	ept_enable_ad_bits_or_skip_test();
3042 
3043 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3044 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3045 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3046 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
3047 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3048 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
3049 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
3050 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
3051 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
3052 }
3053 
3054 static void ept_access_test_paddr_not_present_page_fault(void)
3055 {
3056 	ept_access_test_setup();
3057 	/*
3058 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
3059 	 * page is read-only in EPT but GVA is also mapped read only in PT.
3060 	 * Thus guest page fault before host takes EPT violation for trying to
3061 	 * update A bit.
3062 	 */
3063 }
3064 
3065 static void ept_access_test_force_2m_page(void)
3066 {
3067 	ept_access_test_setup();
3068 
3069 	TEST_ASSERT_EQ(ept_2m_supported(), true);
3070 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
3071 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
3072 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
3073 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
3074 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
3075 }
3076 
3077 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
3078 {
3079 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3080 
3081 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
3082 
3083 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
3084 		return false;
3085 
3086 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
3087 		return false;
3088 
3089 	if (vpid >> 16)
3090 		return false;
3091 
3092 	if (type != INVVPID_ALL && !vpid)
3093 		return false;
3094 
3095 	if (type == INVVPID_ADDR && !is_canonical(gla))
3096 		return false;
3097 
3098 	return true;
3099 }
3100 
3101 static void try_invvpid(u64 type, u64 vpid, u64 gla)
3102 {
3103 	int rc;
3104 	bool valid = invvpid_valid(type, vpid, gla);
3105 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
3106 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
3107 	/*
3108 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
3109 	 * that we can tell if it is updated by INVVPID.
3110 	 */
3111 	vmcs_read(~0);
3112 	rc = invvpid(type, vpid, gla);
3113 	report("INVVPID type %ld VPID %lx GLA %lx %s",
3114 	       !rc == valid, type, vpid, gla,
3115 	       valid ? "passes" : "fails");
3116 	report("After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3117 	       vmcs_read(VMX_INST_ERROR) == expected,
3118 	       rc ? "failed" : "successful",
3119 	       expected, vmcs_read(VMX_INST_ERROR));
3120 }
3121 
3122 static void ds_invvpid(void *data)
3123 {
3124 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3125 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3126 
3127 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3128 	asm volatile("invvpid %0, %1"
3129 		     :
3130 		     : "m"(*(struct invvpid_operand *)data),
3131 		       "r"(type));
3132 }
3133 
3134 /*
3135  * The SS override is ignored in 64-bit mode, so we use an addressing
3136  * mode with %rsp as the base register to generate an implicit SS
3137  * reference.
3138  */
3139 static void ss_invvpid(void *data)
3140 {
3141 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3142 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3143 
3144 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3145 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3146 		     : "+r"(data)
3147 		     : "r"(type));
3148 }
3149 
3150 static void invvpid_test_gp(void)
3151 {
3152 	bool fault;
3153 
3154 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3155 				   (void *)NONCANONICAL);
3156 	report("INVVPID with non-canonical DS operand raises #GP", fault);
3157 }
3158 
3159 static void invvpid_test_ss(void)
3160 {
3161 	bool fault;
3162 
3163 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3164 				   (void *)NONCANONICAL);
3165 	report("INVVPID with non-canonical SS operand raises #SS", fault);
3166 }
3167 
3168 static void invvpid_test_pf(void)
3169 {
3170 	void *vpage = alloc_vpage();
3171 	bool fault;
3172 
3173 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3174 	report("INVVPID with unmapped operand raises #PF", fault);
3175 }
3176 
3177 static void try_compat_invvpid(void *unused)
3178 {
3179 	struct far_pointer32 fp = {
3180 		.offset = (uintptr_t)&&invvpid,
3181 		.selector = KERNEL_CS32,
3182 	};
3183 	register uintptr_t rsp asm("rsp");
3184 
3185 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3186 			"Code address too high.");
3187 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3188 
3189 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3190 	return;
3191 invvpid:
3192 	asm volatile (".code32;"
3193 		      "invvpid (%eax), %eax;"
3194 		      "lret;"
3195 		      ".code64");
3196 	__builtin_unreachable();
3197 }
3198 
3199 static void invvpid_test_compatibility_mode(void)
3200 {
3201 	bool fault;
3202 
3203 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3204 	report("Compatibility mode INVVPID raises #UD", fault);
3205 }
3206 
3207 static void invvpid_test_not_in_vmx_operation(void)
3208 {
3209 	bool fault;
3210 
3211 	TEST_ASSERT(!vmx_off());
3212 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3213 	report("INVVPID outside of VMX operation raises #UD", fault);
3214 	TEST_ASSERT(!vmx_on());
3215 }
3216 
3217 /*
3218  * This does not test real-address mode, virtual-8086 mode, protected mode,
3219  * or CPL > 0.
3220  */
3221 static void invvpid_test_v2(void)
3222 {
3223 	u64 msr;
3224 	int i;
3225 	unsigned types = 0;
3226 	unsigned type;
3227 
3228 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3229 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3230 		test_skip("VPID not supported");
3231 
3232 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3233 
3234 	if (!(msr & VPID_CAP_INVVPID))
3235 		test_skip("INVVPID not supported.\n");
3236 
3237 	if (msr & VPID_CAP_INVVPID_ADDR)
3238 		types |= 1u << INVVPID_ADDR;
3239 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3240 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3241 	if (msr & VPID_CAP_INVVPID_ALL)
3242 		types |= 1u << INVVPID_ALL;
3243 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3244 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3245 
3246 	if (!types)
3247 		test_skip("No INVVPID types supported.\n");
3248 
3249 	for (i = -127; i < 128; i++)
3250 		try_invvpid(i, 0xffff, 0);
3251 
3252 	/*
3253 	 * VPID must not be more than 16 bits.
3254 	 */
3255 	for (i = 0; i < 64; i++)
3256 		for (type = 0; type < 4; type++)
3257 			if (types & (1u << type))
3258 				try_invvpid(type, 1ul << i, 0);
3259 
3260 	/*
3261 	 * VPID must not be zero, except for "all contexts."
3262 	 */
3263 	for (type = 0; type < 4; type++)
3264 		if (types & (1u << type))
3265 			try_invvpid(type, 0, 0);
3266 
3267 	/*
3268 	 * The gla operand is only validated for single-address INVVPID.
3269 	 */
3270 	if (types & (1u << INVVPID_ADDR))
3271 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3272 
3273 	invvpid_test_gp();
3274 	invvpid_test_ss();
3275 	invvpid_test_pf();
3276 	invvpid_test_compatibility_mode();
3277 	invvpid_test_not_in_vmx_operation();
3278 }
3279 
3280 /*
3281  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3282  * at least as far as the guest-state checks. Returns false if the
3283  * VMLAUNCH fails early and execution falls through to the next
3284  * instruction.
3285  */
3286 static bool vmlaunch_succeeds(void)
3287 {
3288 	u32 exit_reason;
3289 
3290 	/*
3291 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3292 	 * unsupported VMCS component"). The caller can then check
3293 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3294 	 */
3295 	vmcs_write(~0u, 0);
3296 
3297 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3298 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3299 				   :
3300 				   : "r" ((u64)HOST_RSP)
3301 				   : "cc", "memory"
3302 				   : success);
3303 	return false;
3304 success:
3305 	exit_reason = vmcs_read(EXI_REASON);
3306 	TEST_ASSERT(exit_reason == (VMX_FAIL_STATE | VMX_ENTRY_FAILURE) ||
3307 		    exit_reason == (VMX_FAIL_MSR | VMX_ENTRY_FAILURE));
3308 	return true;
3309 }
3310 
3311 /*
3312  * Try to launch the current VMCS.
3313  */
3314 static void test_vmx_controls(bool controls_valid, bool xfail)
3315 {
3316 	bool success = vmlaunch_succeeds();
3317 	u32 vmx_inst_err;
3318 
3319 	report_xfail("vmlaunch %s", xfail, success == controls_valid,
3320 		     controls_valid ? "succeeds" : "fails");
3321 	if (!success) {
3322 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3323 		report("VMX inst error is %d (actual %d)",
3324 		       vmx_inst_err == VMXERR_ENTRY_INVALID_CONTROL_FIELD,
3325 		       VMXERR_ENTRY_INVALID_CONTROL_FIELD, vmx_inst_err);
3326 	}
3327 }
3328 
3329 /*
3330  * Test a particular value of a VM-execution control bit, if the value
3331  * is required or if the value is zero.
3332  */
3333 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3334 				    enum Encoding encoding, unsigned bit,
3335 				    unsigned val)
3336 {
3337 	u32 mask = 1u << bit;
3338 	bool expected;
3339 	u32 controls;
3340 
3341 	if (msr.set & mask)
3342 		TEST_ASSERT(msr.clr & mask);
3343 
3344 	/*
3345 	 * We can't arbitrarily turn on a control bit, because it may
3346 	 * introduce dependencies on other VMCS fields. So, we only
3347 	 * test turning on bits that have a required setting.
3348 	 */
3349 	if (val && (msr.clr & mask) && !(msr.set & mask))
3350 		return;
3351 
3352 	report_prefix_pushf("%s %s bit %d",
3353 			    val ? "Set" : "Clear", name, bit);
3354 
3355 	controls = vmcs_read(encoding);
3356 	if (val) {
3357 		vmcs_write(encoding, msr.set | mask);
3358 		expected = (msr.clr & mask);
3359 	} else {
3360 		vmcs_write(encoding, msr.set & ~mask);
3361 		expected = !(msr.set & mask);
3362 	}
3363 	test_vmx_controls(expected, false);
3364 	vmcs_write(encoding, controls);
3365 	report_prefix_pop();
3366 }
3367 
3368 /*
3369  * Test reserved values of a VM-execution control bit, based on the
3370  * allowed bit settings from the corresponding VMX capability MSR.
3371  */
3372 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3373 			      enum Encoding encoding, unsigned bit)
3374 {
3375 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3376 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3377 }
3378 
3379 /*
3380  * Reserved bits in the pin-based VM-execution controls must be set
3381  * properly. Software may consult the VMX capability MSRs to determine
3382  * the proper settings.
3383  * [Intel SDM]
3384  */
3385 static void test_pin_based_ctls(void)
3386 {
3387 	unsigned bit;
3388 
3389 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3390 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3391 	for (bit = 0; bit < 32; bit++)
3392 		test_rsvd_ctl_bit("pin-based controls",
3393 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3394 }
3395 
3396 /*
3397  * Reserved bits in the primary processor-based VM-execution controls
3398  * must be set properly. Software may consult the VMX capability MSRs
3399  * to determine the proper settings.
3400  * [Intel SDM]
3401  */
3402 static void test_primary_processor_based_ctls(void)
3403 {
3404 	unsigned bit;
3405 
3406 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3407 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3408 	for (bit = 0; bit < 32; bit++)
3409 		test_rsvd_ctl_bit("primary processor-based controls",
3410 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3411 }
3412 
3413 /*
3414  * If the "activate secondary controls" primary processor-based
3415  * VM-execution control is 1, reserved bits in the secondary
3416  * processor-based VM-execution controls must be cleared. Software may
3417  * consult the VMX capability MSRs to determine which bits are
3418  * reserved.
3419  * If the "activate secondary controls" primary processor-based
3420  * VM-execution control is 0 (or if the processor does not support the
3421  * 1-setting of that control), no checks are performed on the
3422  * secondary processor-based VM-execution controls.
3423  * [Intel SDM]
3424  */
3425 static void test_secondary_processor_based_ctls(void)
3426 {
3427 	u32 primary;
3428 	u32 secondary;
3429 	unsigned bit;
3430 
3431 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3432 		return;
3433 
3434 	primary = vmcs_read(CPU_EXEC_CTRL0);
3435 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3436 
3437 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3438 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3439 	for (bit = 0; bit < 32; bit++)
3440 		test_rsvd_ctl_bit("secondary processor-based controls",
3441 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3442 
3443 	/*
3444 	 * When the "activate secondary controls" VM-execution control
3445 	 * is clear, there are no checks on the secondary controls.
3446 	 */
3447 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3448 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3449 	report("Secondary processor-based controls ignored",
3450 	       vmlaunch_succeeds());
3451 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3452 	vmcs_write(CPU_EXEC_CTRL0, primary);
3453 }
3454 
3455 static void try_cr3_target_count(unsigned i, unsigned max)
3456 {
3457 	report_prefix_pushf("CR3 target count 0x%x", i);
3458 	vmcs_write(CR3_TARGET_COUNT, i);
3459 	test_vmx_controls(i <= max, false);
3460 	report_prefix_pop();
3461 }
3462 
3463 /*
3464  * The CR3-target count must not be greater than 4. Future processors
3465  * may support a different number of CR3-target values. Software
3466  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3467  * number of values supported.
3468  * [Intel SDM]
3469  */
3470 static void test_cr3_targets(void)
3471 {
3472 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3473 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3474 	unsigned i;
3475 
3476 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3477 	TEST_ASSERT(supported_targets <= 256);
3478 
3479 	try_cr3_target_count(-1u, supported_targets);
3480 	try_cr3_target_count(0x80000000, supported_targets);
3481 	try_cr3_target_count(0x7fffffff, supported_targets);
3482 	for (i = 0; i <= supported_targets + 1; i++)
3483 		try_cr3_target_count(i, supported_targets);
3484 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3485 }
3486 
3487 /*
3488  * Test a particular address setting in the VMCS
3489  */
3490 static void test_vmcs_addr(const char *name,
3491 			   enum Encoding encoding,
3492 			   u64 align,
3493 			   bool ignored,
3494 			   bool xfail_beyond_mapped_ram,
3495 			   u64 addr)
3496 {
3497 	bool xfail =
3498 		(xfail_beyond_mapped_ram &&
3499 		 addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - align &&
3500 		 addr < (1ul << cpuid_maxphyaddr()));
3501 
3502 	report_prefix_pushf("%s = %lx", name, addr);
3503 	vmcs_write(encoding, addr);
3504 	test_vmx_controls(ignored || (IS_ALIGNED(addr, align) &&
3505 				  addr < (1ul << cpuid_maxphyaddr())),
3506 			  xfail);
3507 	report_prefix_pop();
3508 	xfail = false;
3509 }
3510 
3511 /*
3512  * Test interesting values for a VMCS address
3513  */
3514 static void test_vmcs_addr_values(const char *name,
3515 				  enum Encoding encoding,
3516 				  u64 align,
3517 				  bool ignored,
3518 				  bool xfail_beyond_mapped_ram,
3519 				  u32 bit_start, u32 bit_end)
3520 {
3521 	unsigned i;
3522 	u64 orig_val = vmcs_read(encoding);
3523 
3524 	for (i = bit_start; i <= bit_end; i++)
3525 		test_vmcs_addr(name, encoding, align, ignored,
3526 			       xfail_beyond_mapped_ram, 1ul << i);
3527 
3528 	test_vmcs_addr(name, encoding, align, ignored,
3529 		       xfail_beyond_mapped_ram, PAGE_SIZE - 1);
3530 	test_vmcs_addr(name, encoding, align, ignored,
3531 		       xfail_beyond_mapped_ram, PAGE_SIZE);
3532 	test_vmcs_addr(name, encoding, align, ignored,
3533 		       xfail_beyond_mapped_ram,
3534 		      (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3535 	test_vmcs_addr(name, encoding, align, ignored,
3536 		       xfail_beyond_mapped_ram, -1ul);
3537 
3538 	vmcs_write(encoding, orig_val);
3539 }
3540 
3541 /*
3542  * Test a physical address reference in the VMCS, when the corresponding
3543  * feature is enabled and when the corresponding feature is disabled.
3544  */
3545 static void test_vmcs_addr_reference(u32 control_bit, enum Encoding field,
3546 				     const char *field_name,
3547 				     const char *control_name, u64 align,
3548 				     bool xfail_beyond_mapped_ram,
3549 				     bool control_primary)
3550 {
3551 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3552 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3553 	u64 page_addr;
3554 
3555 	if (control_primary) {
3556 		if (!(ctrl_cpu_rev[0].clr & control_bit))
3557 			return;
3558 	} else {
3559 		if (!(ctrl_cpu_rev[1].clr & control_bit))
3560 			return;
3561 	}
3562 
3563 	page_addr = vmcs_read(field);
3564 
3565 	report_prefix_pushf("%s enabled", control_name);
3566 	if (control_primary) {
3567 		vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3568 	} else {
3569 		vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3570 		vmcs_write(CPU_EXEC_CTRL1, secondary | control_bit);
3571 	}
3572 
3573 	test_vmcs_addr_values(field_name, field, align, false,
3574 			      xfail_beyond_mapped_ram, 0, 63);
3575 	report_prefix_pop();
3576 
3577 	report_prefix_pushf("%s disabled", control_name);
3578 	if (control_primary) {
3579 		vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3580 	} else {
3581 		vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3582 		vmcs_write(CPU_EXEC_CTRL1, secondary & ~control_bit);
3583 	}
3584 
3585 	test_vmcs_addr_values(field_name, field, align, true, false, 0, 63);
3586 	report_prefix_pop();
3587 
3588 	vmcs_write(field, page_addr);
3589 	vmcs_write(CPU_EXEC_CTRL0, primary);
3590 }
3591 
3592 /*
3593  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3594  * each I/O-bitmap address must be 0. Neither address should set any
3595  * bits beyond the processor's physical-address width.
3596  * [Intel SDM]
3597  */
3598 static void test_io_bitmaps(void)
3599 {
3600 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3601 				 "I/O bitmap A", "Use I/O bitmaps",
3602 				 PAGE_SIZE, false, true);
3603 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3604 				 "I/O bitmap B", "Use I/O bitmaps",
3605 				 PAGE_SIZE, false, true);
3606 }
3607 
3608 /*
3609  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3610  * the MSR-bitmap address must be 0. The address should not set any
3611  * bits beyond the processor's physical-address width.
3612  * [Intel SDM]
3613  */
3614 static void test_msr_bitmap(void)
3615 {
3616 	test_vmcs_addr_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3617 				 "MSR bitmap", "Use MSR bitmaps",
3618 				 PAGE_SIZE, false, true);
3619 }
3620 
3621 /*
3622  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3623  * address must satisfy the following checks:
3624  * - Bits 11:0 of the address must be 0.
3625  * - The address should not set any bits beyond the processor's
3626  *   physical-address width.
3627  * [Intel SDM]
3628  */
3629 static void test_apic_virt_addr(void)
3630 {
3631 	test_vmcs_addr_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3632 				 "virtual-APIC address", "Use TPR shadow",
3633 				 PAGE_SIZE, true, true);
3634 }
3635 
3636 /*
3637  * If the "virtualize APIC-accesses" VM-execution control is 1, the
3638  * APIC-access address must satisfy the following checks:
3639  *  - Bits 11:0 of the address must be 0.
3640  *  - The address should not set any bits beyond the processor's
3641  *    physical-address width.
3642  * [Intel SDM]
3643  */
3644 static void test_apic_access_addr(void)
3645 {
3646 	void *apic_access_page = alloc_page();
3647 
3648 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_page));
3649 
3650 	test_vmcs_addr_reference(CPU_VIRT_APIC_ACCESSES, APIC_ACCS_ADDR,
3651 				 "APIC-access address",
3652 				 "virtualize APIC-accesses", PAGE_SIZE,
3653 				 false, false);
3654 }
3655 
3656 static bool set_bit_pattern(u8 mask, u32 *secondary)
3657 {
3658 	u8 i;
3659 	bool flag = false;
3660 	u32 test_bits[3] = {
3661 		CPU_VIRT_X2APIC,
3662 		CPU_APIC_REG_VIRT,
3663 		CPU_VINTD
3664 	};
3665 
3666         for (i = 0; i < ARRAY_SIZE(test_bits); i++) {
3667 		if ((mask & (1u << i)) &&
3668 		    (ctrl_cpu_rev[1].clr & test_bits[i])) {
3669 			*secondary |= test_bits[i];
3670 			flag = true;
3671 		}
3672 	}
3673 
3674 	return (flag);
3675 }
3676 
3677 /*
3678  * If the "use TPR shadow" VM-execution control is 0, the following
3679  * VM-execution controls must also be 0:
3680  * 	- virtualize x2APIC mode
3681  *	- APIC-register virtualization
3682  *	- virtual-interrupt delivery
3683  *    [Intel SDM]
3684  *
3685  * 2. If the "virtualize x2APIC mode" VM-execution control is 1, the
3686  *    "virtualize APIC accesses" VM-execution control must be 0.
3687  *    [Intel SDM]
3688  */
3689 static void test_apic_virtual_ctls(void)
3690 {
3691 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3692 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3693 	u32 primary = saved_primary;
3694 	u32 secondary = saved_secondary;
3695 	bool ctrl = false;
3696 	char str[10] = "disabled";
3697 	u8 i = 0, j;
3698 
3699 	/*
3700 	 * First test
3701 	 */
3702 	if (!((ctrl_cpu_rev[0].clr & (CPU_SECONDARY | CPU_TPR_SHADOW)) ==
3703 	    (CPU_SECONDARY | CPU_TPR_SHADOW)))
3704 		return;
3705 
3706 	primary |= CPU_SECONDARY;
3707 	primary &= ~CPU_TPR_SHADOW;
3708 	vmcs_write(CPU_EXEC_CTRL0, primary);
3709 
3710 	while (1) {
3711 		for (j = 1; j < 8; j++) {
3712 			secondary &= ~(CPU_VIRT_X2APIC | CPU_APIC_REG_VIRT | CPU_VINTD);
3713 			if (primary & CPU_TPR_SHADOW) {
3714 				ctrl = true;
3715 			} else {
3716 				if (! set_bit_pattern(j, &secondary))
3717 					ctrl = true;
3718 				else
3719 					ctrl = false;
3720 			}
3721 
3722 			vmcs_write(CPU_EXEC_CTRL1, secondary);
3723 			report_prefix_pushf("Use TPR shadow %s, virtualize x2APIC mode %s, APIC-register virtualization %s, virtual-interrupt delivery %s",
3724 				str, (secondary & CPU_VIRT_X2APIC) ? "enabled" : "disabled", (secondary & CPU_APIC_REG_VIRT) ? "enabled" : "disabled", (secondary & CPU_VINTD) ? "enabled" : "disabled");
3725 			test_vmx_controls(ctrl, false);
3726 			report_prefix_pop();
3727 		}
3728 
3729 		if (i == 1)
3730 			break;
3731 		i++;
3732 
3733 		primary |= CPU_TPR_SHADOW;
3734 		vmcs_write(CPU_EXEC_CTRL0, primary);
3735 		strcpy(str, "enabled");
3736 	}
3737 
3738 	/*
3739 	 * Second test
3740 	 */
3741 	u32 apic_virt_ctls = (CPU_VIRT_X2APIC | CPU_VIRT_APIC_ACCESSES);
3742 
3743 	primary = saved_primary;
3744 	secondary = saved_secondary;
3745 	if (!((ctrl_cpu_rev[1].clr & apic_virt_ctls) == apic_virt_ctls))
3746 		return;
3747 
3748 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3749 	secondary &= ~CPU_VIRT_APIC_ACCESSES;
3750 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_X2APIC);
3751 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access disabled");
3752 	test_vmx_controls(true, false);
3753 	report_prefix_pop();
3754 
3755 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_APIC_ACCESSES);
3756 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access enabled");
3757 	test_vmx_controls(true, false);
3758 	report_prefix_pop();
3759 
3760 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_X2APIC);
3761 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access enabled");
3762 	test_vmx_controls(false, false);
3763 	report_prefix_pop();
3764 
3765 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_APIC_ACCESSES);
3766 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access disabled");
3767 	test_vmx_controls(true, false);
3768 	report_prefix_pop();
3769 
3770 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3771 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3772 }
3773 
3774 /*
3775  * If the "virtual-interrupt delivery" VM-execution control is 1, the
3776  * "external-interrupt exiting" VM-execution control must be 1.
3777  * [Intel SDM]
3778  */
3779 static void test_virtual_intr_ctls(void)
3780 {
3781 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3782 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3783 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3784 	u32 primary = saved_primary;
3785 	u32 secondary = saved_secondary;
3786 	u32 pin = saved_pin;
3787 
3788 	if (!((ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3789 	    (ctrl_pin_rev.clr & PIN_EXTINT)))
3790 		return;
3791 
3792 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3793 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VINTD);
3794 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3795 	report_prefix_pushf("Virtualize interrupt-delivery disabled; external-interrupt exiting disabled");
3796 	test_vmx_controls(true, false);
3797 	report_prefix_pop();
3798 
3799 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VINTD);
3800 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3801 	test_vmx_controls(false, false);
3802 	report_prefix_pop();
3803 
3804 	vmcs_write(PIN_CONTROLS, pin | PIN_EXTINT);
3805 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting enabled");
3806 	test_vmx_controls(true, false);
3807 	report_prefix_pop();
3808 
3809 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
3810 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
3811 	test_vmx_controls(false, false);
3812 	report_prefix_pop();
3813 
3814 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3815 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3816 	vmcs_write(PIN_CONTROLS, saved_pin);
3817 }
3818 
3819 static void test_pi_desc_addr(u64 addr, bool ctrl)
3820 {
3821 	vmcs_write(POSTED_INTR_DESC_ADDR, addr);
3822 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-descriptor-address 0x%lx", addr);
3823 	test_vmx_controls(ctrl, false);
3824 	report_prefix_pop();
3825 }
3826 
3827 /*
3828  * If the “process posted interrupts†VM-execution control is 1, the
3829  * following must be true:
3830  *
3831  *	- The “virtual-interrupt delivery†VM-execution control is 1.
3832  *	- The “acknowledge interrupt on exit†VM-exit control is 1.
3833  *	- The posted-interrupt notification vector has a value in the
3834  *	- range 0–255 (bits 15:8 are all 0).
3835  *	- Bits 5:0 of the posted-interrupt descriptor address are all 0.
3836  *	- The posted-interrupt descriptor address does not set any bits
3837  *	  beyond the processor's physical-address width.
3838  * [Intel SDM]
3839  */
3840 static void test_posted_intr(void)
3841 {
3842 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3843 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3844 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
3845 	u32 exit_ctl_saved = vmcs_read(EXI_CONTROLS);
3846 	u32 primary = saved_primary;
3847 	u32 secondary = saved_secondary;
3848 	u32 pin = saved_pin;
3849 	u32 exit_ctl = exit_ctl_saved;
3850 	u16 vec;
3851 	int i;
3852 
3853 	if (!((ctrl_pin_rev.clr & PIN_POST_INTR) &&
3854 	    (ctrl_cpu_rev[1].clr & CPU_VINTD) &&
3855 	    (ctrl_exit_rev.clr & EXI_INTA)))
3856 		return;
3857 
3858 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
3859 
3860 	/*
3861 	 * Test virtual-interrupt-delivery and acknowledge-interrupt-on-exit
3862 	 */
3863 	pin |= PIN_POST_INTR;
3864 	vmcs_write(PIN_CONTROLS, pin);
3865 	secondary &= ~CPU_VINTD;
3866 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3867 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled");
3868 	test_vmx_controls(false, false);
3869 	report_prefix_pop();
3870 
3871 	secondary |= CPU_VINTD;
3872 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3873 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled");
3874 	test_vmx_controls(false, false);
3875 	report_prefix_pop();
3876 
3877 	exit_ctl &= ~EXI_INTA;
3878 	vmcs_write(EXI_CONTROLS, exit_ctl);
3879 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit disabled");
3880 	test_vmx_controls(false, false);
3881 	report_prefix_pop();
3882 
3883 	exit_ctl |= EXI_INTA;
3884 	vmcs_write(EXI_CONTROLS, exit_ctl);
3885 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
3886 	test_vmx_controls(true, false);
3887 	report_prefix_pop();
3888 
3889 	secondary &= ~CPU_VINTD;
3890 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3891 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled; acknowledge-interrupt-on-exit enabled");
3892 	test_vmx_controls(false, false);
3893 	report_prefix_pop();
3894 
3895 	secondary |= CPU_VINTD;
3896 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3897 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
3898 	test_vmx_controls(true, false);
3899 	report_prefix_pop();
3900 
3901 	/*
3902 	 * Test posted-interrupt notification vector
3903 	 */
3904 	for (i = 0; i < 8; i++) {
3905 		vec = (1ul << i);
3906 		vmcs_write(PINV, vec);
3907 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3908 		test_vmx_controls(true, false);
3909 		report_prefix_pop();
3910 	}
3911 	for (i = 8; i < 16; i++) {
3912 		vec = (1ul << i);
3913 		vmcs_write(PINV, vec);
3914 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3915 		test_vmx_controls(false, false);
3916 		report_prefix_pop();
3917 	}
3918 
3919 	vec &= ~(0xff << 8);
3920 	vmcs_write(PINV, vec);
3921 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
3922 	test_vmx_controls(true, false);
3923 	report_prefix_pop();
3924 
3925 	/*
3926 	 * Test posted-interrupt descriptor addresss
3927 	 */
3928 	for (i = 0; i < 6; i++) {
3929 		test_pi_desc_addr(1ul << i, false);
3930 	}
3931 
3932 	test_pi_desc_addr(0xf0, false);
3933 	test_pi_desc_addr(0xff, false);
3934 	test_pi_desc_addr(0x0f, false);
3935 	test_pi_desc_addr(0x8000, true);
3936 	test_pi_desc_addr(0x00, true);
3937 	test_pi_desc_addr(0xc000, true);
3938 
3939 	test_vmcs_addr_values("process-posted interrupts",
3940 			       POSTED_INTR_DESC_ADDR, 64,
3941 			       false, false, 0, 63);
3942 
3943 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3944 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3945 	vmcs_write(PIN_CONTROLS, saved_pin);
3946 }
3947 
3948 static void test_apic_ctls(void)
3949 {
3950 	test_apic_virt_addr();
3951 	test_apic_access_addr();
3952 	test_apic_virtual_ctls();
3953 	test_virtual_intr_ctls();
3954 	test_posted_intr();
3955 }
3956 
3957 /*
3958  * If the “enable VPID†VM-execution control is 1, the value of the
3959  * of the VPID VM-execution control field must not be 0000H.
3960  * [Intel SDM]
3961  */
3962 static void test_vpid(void)
3963 {
3964 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3965 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3966 	u16 vpid = 0x0000;
3967 	int i;
3968 
3969 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
3970 	    (ctrl_cpu_rev[1].clr & CPU_VPID))) {
3971 		test_skip("Secondary controls and/or VPID not supported");
3972 		return;
3973 	}
3974 
3975 	vmcs_write(CPU_EXEC_CTRL0, saved_primary | CPU_SECONDARY);
3976 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary & ~CPU_VPID);
3977 	vmcs_write(VPID, vpid);
3978 	report_prefix_pushf("VPID disabled; VPID value %x", vpid);
3979 	test_vmx_controls(true, false);
3980 	report_prefix_pop();
3981 
3982 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary | CPU_VPID);
3983 	report_prefix_pushf("VPID enabled; VPID value %x", vpid);
3984 	test_vmx_controls(false, false);
3985 	report_prefix_pop();
3986 
3987 	for (i = 0; i < 16; i++) {
3988 		vpid = (short)1 << i;;
3989 		vmcs_write(VPID, vpid);
3990 		report_prefix_pushf("VPID enabled; VPID value %x", vpid);
3991 		test_vmx_controls(true, false);
3992 		report_prefix_pop();
3993 	}
3994 
3995 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3996 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3997 }
3998 
3999 static void set_vtpr(unsigned vtpr)
4000 {
4001 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
4002 }
4003 
4004 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
4005 {
4006 	bool valid = true;
4007 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4008 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4009 
4010 	if ((primary & CPU_TPR_SHADOW) &&
4011 	    (!(primary & CPU_SECONDARY) ||
4012 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
4013 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
4014 
4015 	set_vtpr(vtpr);
4016 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
4017 	    threshold, (vtpr >> 4) & 0xf);
4018 	test_vmx_controls(valid, false);
4019 	report_prefix_pop();
4020 }
4021 
4022 static void test_invalid_event_injection(void)
4023 {
4024 	u32 ent_intr_info_save = vmcs_read(ENT_INTR_INFO);
4025 	u32 ent_intr_error_save = vmcs_read(ENT_INTR_ERROR);
4026 	u32 ent_inst_len_save = vmcs_read(ENT_INST_LEN);
4027 	u32 primary_save = vmcs_read(CPU_EXEC_CTRL0);
4028 	u32 secondary_save = vmcs_read(CPU_EXEC_CTRL1);
4029 	u64 guest_cr0_save = vmcs_read(GUEST_CR0);
4030 	u32 ent_intr_info_base = INTR_INFO_VALID_MASK;
4031 	u32 ent_intr_info, ent_intr_err, ent_intr_len;
4032 	u32 cnt;
4033 
4034 	/* Setup */
4035 	report_prefix_push("invalid event injection");
4036 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4037 	vmcs_write(ENT_INST_LEN, 0x00000001);
4038 
4039 	/* The field’s interruption type is not set to a reserved value. */
4040 	ent_intr_info = ent_intr_info_base | INTR_TYPE_RESERVED | DE_VECTOR;
4041 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4042 			    "RESERVED interruption type invalid [-]",
4043 			    ent_intr_info);
4044 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4045 	test_vmx_controls(false, false);
4046 	report_prefix_pop();
4047 
4048 	ent_intr_info = ent_intr_info_base | INTR_TYPE_EXT_INTR |
4049 			DE_VECTOR;
4050 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4051 			    "RESERVED interruption type invalid [+]",
4052 			    ent_intr_info);
4053 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4054 	test_vmx_controls(true, false);
4055 	report_prefix_pop();
4056 
4057 	/* If the interruption type is other event, the vector is 0. */
4058 	ent_intr_info = ent_intr_info_base | INTR_TYPE_OTHER_EVENT | DB_VECTOR;
4059 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4060 			    "(OTHER EVENT && vector != 0) invalid [-]",
4061 			    ent_intr_info);
4062 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4063 	test_vmx_controls(false, false);
4064 	report_prefix_pop();
4065 
4066 	/* If the interruption type is NMI, the vector is 2 (negative case). */
4067 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | DE_VECTOR;
4068 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4069 			    "(NMI && vector != 2) invalid [-]", ent_intr_info);
4070 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4071 	test_vmx_controls(false, false);
4072 	report_prefix_pop();
4073 
4074 	/* If the interruption type is NMI, the vector is 2 (positive case). */
4075 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | NMI_VECTOR;
4076 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4077 			    "(NMI && vector == 2) valid [+]", ent_intr_info);
4078 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4079 	test_vmx_controls(true, false);
4080 	report_prefix_pop();
4081 
4082 	/*
4083 	 * If the interruption type
4084 	 * is HW exception, the vector is at most 31.
4085 	 */
4086 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION | 0x20;
4087 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4088 			    "(HW exception && vector > 31) invalid [-]",
4089 			    ent_intr_info);
4090 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4091 	test_vmx_controls(false, false);
4092 	report_prefix_pop();
4093 
4094 	/*
4095 	 * deliver-error-code is 1 iff either
4096 	 * (a) the "unrestricted guest" VM-execution control is 0
4097 	 * (b) CR0.PE is set.
4098 	 */
4099 
4100 	/* Assert that unrestricted guest is disabled or unsupported */
4101 	assert(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
4102 	       !(secondary_save & CPU_URG));
4103 
4104 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4105 			GP_VECTOR;
4106 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4107 			    "error code <-> (!URG || prot_mode) [-]",
4108 			    ent_intr_info);
4109 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4110 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4111 	test_vmx_controls(false, false);
4112 	report_prefix_pop();
4113 
4114 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4115 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4116 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4117 			    "error code <-> (!URG || prot_mode) [+]",
4118 			    ent_intr_info);
4119 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4120 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4121 	test_vmx_controls(true, false);
4122 	report_prefix_pop();
4123 
4124 	if (enable_unrestricted_guest())
4125 		goto skip_unrestricted_guest;
4126 
4127 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4128 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4129 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4130 			    "error code <-> (!URG || prot_mode) [-]",
4131 			    ent_intr_info);
4132 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4133 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4134 	test_vmx_controls(false, false);
4135 	report_prefix_pop();
4136 
4137 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4138 			GP_VECTOR;
4139 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4140 			    "error code <-> (!URG || prot_mode) [-]",
4141 			    ent_intr_info);
4142 	vmcs_write(GUEST_CR0, guest_cr0_save | X86_CR0_PE);
4143 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4144 	test_vmx_controls(false, false);
4145 	report_prefix_pop();
4146 
4147 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4148 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4149 
4150 skip_unrestricted_guest:
4151 	vmcs_write(GUEST_CR0, guest_cr0_save);
4152 
4153 	/* deliver-error-code is 1 iff the interruption type is HW exception */
4154 	report_prefix_push("error code <-> HW exception");
4155 	for (cnt = 0; cnt < 8; cnt++) {
4156 		u32 exception_type_mask = cnt << 8;
4157 		u32 deliver_error_code_mask =
4158 			exception_type_mask != INTR_TYPE_HARD_EXCEPTION ?
4159 			INTR_INFO_DELIVER_CODE_MASK : 0;
4160 
4161 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4162 				exception_type_mask | GP_VECTOR;
4163 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4164 				    ent_intr_info);
4165 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4166 		test_vmx_controls(false, false);
4167 		report_prefix_pop();
4168 	}
4169 	report_prefix_pop();
4170 
4171 	/*
4172 	 * deliver-error-code is 1 iff the the vector
4173 	 * indicates an exception that would normally deliver an error code
4174 	 */
4175 	report_prefix_push("error code <-> vector delivers error code");
4176 	for (cnt = 0; cnt < 32; cnt++) {
4177 		bool has_error_code = false;
4178 		u32 deliver_error_code_mask;
4179 
4180 		switch (cnt) {
4181 		case DF_VECTOR:
4182 		case TS_VECTOR:
4183 		case NP_VECTOR:
4184 		case SS_VECTOR:
4185 		case GP_VECTOR:
4186 		case PF_VECTOR:
4187 		case AC_VECTOR:
4188 			has_error_code = true;
4189 		}
4190 
4191 		/* Negative case */
4192 		deliver_error_code_mask = has_error_code ?
4193 						0 :
4194 						INTR_INFO_DELIVER_CODE_MASK;
4195 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4196 				INTR_TYPE_HARD_EXCEPTION | cnt;
4197 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4198 				    ent_intr_info);
4199 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4200 		test_vmx_controls(false, false);
4201 		report_prefix_pop();
4202 
4203 		/* Positive case */
4204 		deliver_error_code_mask = has_error_code ?
4205 						INTR_INFO_DELIVER_CODE_MASK :
4206 						0;
4207 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4208 				INTR_TYPE_HARD_EXCEPTION | cnt;
4209 		report_prefix_pushf("VM-entry intr info=0x%x [+]",
4210 				    ent_intr_info);
4211 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4212 		test_vmx_controls(true, false);
4213 		report_prefix_pop();
4214 	}
4215 	report_prefix_pop();
4216 
4217 	/* Reserved bits in the field (30:12) are 0. */
4218 	report_prefix_push("reserved bits clear");
4219 	for (cnt = 12; cnt <= 30; cnt++) {
4220 		ent_intr_info = ent_intr_info_base |
4221 				INTR_INFO_DELIVER_CODE_MASK |
4222 				INTR_TYPE_HARD_EXCEPTION | GP_VECTOR |
4223 				(1U << cnt);
4224 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4225 				    ent_intr_info);
4226 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4227 		test_vmx_controls(false, false);
4228 		report_prefix_pop();
4229 	}
4230 	report_prefix_pop();
4231 
4232 	/*
4233 	 * If deliver-error-code is 1
4234 	 * bits 31:15 of the VM-entry exception error-code field are 0.
4235 	 */
4236 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4237 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4238 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4239 			    "VM-entry exception error code[31:15] clear",
4240 			    ent_intr_info);
4241 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4242 	for (cnt = 15; cnt <= 31; cnt++) {
4243 		ent_intr_err = 1U << cnt;
4244 		report_prefix_pushf("VM-entry intr error=0x%x [-]",
4245 				    ent_intr_err);
4246 		vmcs_write(ENT_INTR_ERROR, ent_intr_err);
4247 		test_vmx_controls(false, false);
4248 		report_prefix_pop();
4249 	}
4250 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4251 	report_prefix_pop();
4252 
4253 	/*
4254 	 * If the interruption type is software interrupt, software exception,
4255 	 * or privileged software exception, the VM-entry instruction-length
4256 	 * field is in the range 0–15.
4257 	 */
4258 
4259 	for (cnt = 0; cnt < 3; cnt++) {
4260 		switch (cnt) {
4261 		case 0:
4262 			ent_intr_info = ent_intr_info_base |
4263 					INTR_TYPE_SOFT_INTR;
4264 			break;
4265 		case 1:
4266 			ent_intr_info = ent_intr_info_base |
4267 					INTR_TYPE_SOFT_EXCEPTION;
4268 			break;
4269 		case 2:
4270 			ent_intr_info = ent_intr_info_base |
4271 					INTR_TYPE_PRIV_SW_EXCEPTION;
4272 			break;
4273 		}
4274 		report_prefix_pushf("%s, VM-entry intr info=0x%x",
4275 				    "VM-entry instruction-length check",
4276 				    ent_intr_info);
4277 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4278 
4279 		/* Instruction length set to -1 (0xFFFFFFFF) should fail */
4280 		ent_intr_len = -1;
4281 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4282 				    ent_intr_len);
4283 		vmcs_write(ENT_INST_LEN, ent_intr_len);
4284 		test_vmx_controls(false, false);
4285 		report_prefix_pop();
4286 
4287 		/* Instruction length set to 16 should fail */
4288 		ent_intr_len = 0x00000010;
4289 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4290 				    ent_intr_len);
4291 		vmcs_write(ENT_INST_LEN, 0x00000010);
4292 		test_vmx_controls(false, false);
4293 		report_prefix_pop();
4294 
4295 		report_prefix_pop();
4296 	}
4297 
4298 	/* Cleanup */
4299 	vmcs_write(ENT_INTR_INFO, ent_intr_info_save);
4300 	vmcs_write(ENT_INTR_ERROR, ent_intr_error_save);
4301 	vmcs_write(ENT_INST_LEN, ent_inst_len_save);
4302 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4303 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4304 	vmcs_write(GUEST_CR0, guest_cr0_save);
4305 	report_prefix_pop();
4306 }
4307 
4308 /*
4309  * Test interesting vTPR values for a given TPR threshold.
4310  */
4311 static void test_vtpr_values(unsigned threshold)
4312 {
4313 	try_tpr_threshold_and_vtpr(threshold, (threshold - 1) << 4);
4314 	try_tpr_threshold_and_vtpr(threshold, threshold << 4);
4315 	try_tpr_threshold_and_vtpr(threshold, (threshold + 1) << 4);
4316 }
4317 
4318 static void try_tpr_threshold(unsigned threshold)
4319 {
4320 	bool valid = true;
4321 
4322 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4323 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4324 
4325 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
4326 	    (secondary & CPU_VINTD)))
4327 		valid = !(threshold >> 4);
4328 
4329 	set_vtpr(-1);
4330 	vmcs_write(TPR_THRESHOLD, threshold);
4331 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
4332 	test_vmx_controls(valid, false);
4333 	report_prefix_pop();
4334 
4335 	if (valid)
4336 		test_vtpr_values(threshold);
4337 }
4338 
4339 /*
4340  * Test interesting TPR threshold values.
4341  */
4342 static void test_tpr_threshold_values(void)
4343 {
4344 	unsigned i;
4345 
4346 	for (i = 0; i < 0x10; i++)
4347 		try_tpr_threshold(i);
4348 	for (i = 4; i < 32; i++)
4349 		try_tpr_threshold(1u << i);
4350 	try_tpr_threshold(-1u);
4351 	try_tpr_threshold(0x7fffffff);
4352 }
4353 
4354 /*
4355  * This test covers the following two VM entry checks:
4356  *
4357  *      i) If the "use TPR shadow" VM-execution control is 1 and the
4358  *         "virtual-interrupt delivery" VM-execution control is 0, bits
4359  *         31:4 of the TPR threshold VM-execution control field must
4360 	   be 0.
4361  *         [Intel SDM]
4362  *
4363  *      ii) If the "use TPR shadow" VM-execution control is 1, the
4364  *          "virtual-interrupt delivery" VM-execution control is 0
4365  *          and the "virtualize APIC accesses" VM-execution control
4366  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
4367  *          control field must not be greater than the value of bits
4368  *          7:4 of VTPR.
4369  *          [Intel SDM]
4370  */
4371 static void test_tpr_threshold(void)
4372 {
4373 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4374 	void *virtual_apic_page;
4375 
4376 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
4377 		return;
4378 
4379 	virtual_apic_page = alloc_page();
4380 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
4381 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
4382 
4383 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
4384 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
4385 	test_tpr_threshold_values();
4386 	report_prefix_pop();
4387 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
4388 	report_prefix_pushf("Use TPR shadow enabled, secondary controls disabled");
4389 	test_tpr_threshold_values();
4390 	report_prefix_pop();
4391 
4392 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4393 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES)))) {
4394 		vmcs_write(CPU_EXEC_CTRL0, primary);
4395 		return;
4396 	}
4397 
4398 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4399 
4400 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
4401 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
4402 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4403 		test_tpr_threshold_values();
4404 		report_prefix_pop();
4405 
4406 		vmcs_write(CPU_EXEC_CTRL0,
4407 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4408 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4409 		test_tpr_threshold_values();
4410 		report_prefix_pop();
4411 	}
4412 
4413 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
4414 		vmcs_write(CPU_EXEC_CTRL0,
4415 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4416 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
4417 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4418 		test_tpr_threshold_values();
4419 		report_prefix_pop();
4420 
4421 		vmcs_write(CPU_EXEC_CTRL0,
4422 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4423 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4424 		test_tpr_threshold_values();
4425 		report_prefix_pop();
4426 	}
4427 
4428 	if ((ctrl_cpu_rev[1].clr &
4429 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
4430 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
4431 		vmcs_write(CPU_EXEC_CTRL0,
4432 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4433 		vmcs_write(CPU_EXEC_CTRL1,
4434 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
4435 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4436 		test_tpr_threshold_values();
4437 		report_prefix_pop();
4438 
4439 		vmcs_write(CPU_EXEC_CTRL0,
4440 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4441 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4442 		test_tpr_threshold_values();
4443 		report_prefix_pop();
4444 	}
4445 
4446 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4447 	vmcs_write(CPU_EXEC_CTRL0, primary);
4448 }
4449 
4450 /*
4451  * This test verifies the following two vmentry checks:
4452  *
4453  *  If the "NMI exiting" VM-execution control is 0, "Virtual NMIs"
4454  *  VM-execution control must be 0.
4455  *  [Intel SDM]
4456  *
4457  *  If the “virtual NMIs” VM-execution control is 0, the “NMI-window
4458  *  exiting” VM-execution control must be 0.
4459  *  [Intel SDM]
4460  */
4461 static void test_nmi_ctrls(void)
4462 {
4463 	u32 pin_ctrls, cpu_ctrls0, test_pin_ctrls, test_cpu_ctrls0;
4464 
4465 	if ((ctrl_pin_rev.clr & (PIN_NMI | PIN_VIRT_NMI)) !=
4466 	    (PIN_NMI | PIN_VIRT_NMI)) {
4467 		test_skip("NMI exiting and Virtual NMIs are not supported !");
4468 		return;
4469 	}
4470 
4471 	/* Save the controls so that we can restore them after our tests */
4472 	pin_ctrls = vmcs_read(PIN_CONTROLS);
4473 	cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
4474 
4475 	test_pin_ctrls = pin_ctrls & ~(PIN_NMI | PIN_VIRT_NMI);
4476 	test_cpu_ctrls0 = cpu_ctrls0 & ~CPU_NMI_WINDOW;
4477 
4478 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4479 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs disabled");
4480 	test_vmx_controls(true, false);
4481 	report_prefix_pop();
4482 
4483 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_VIRT_NMI);
4484 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs enabled");
4485 	test_vmx_controls(false, false);
4486 	report_prefix_pop();
4487 
4488 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4489 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs enabled");
4490 	test_vmx_controls(true, false);
4491 	report_prefix_pop();
4492 
4493 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_NMI);
4494 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs disabled");
4495 	test_vmx_controls(true, false);
4496 	report_prefix_pop();
4497 
4498 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
4499 		report_info("NMI-window exiting is not supported, skipping...");
4500 		goto done;
4501 	}
4502 
4503 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4504 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4505 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting enabled");
4506 	test_vmx_controls(false, false);
4507 	report_prefix_pop();
4508 
4509 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4510 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4511 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting disabled");
4512 	test_vmx_controls(true, false);
4513 	report_prefix_pop();
4514 
4515 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4516 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4517 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting enabled");
4518 	test_vmx_controls(true, false);
4519 	report_prefix_pop();
4520 
4521 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4522 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4523 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting disabled");
4524 	test_vmx_controls(true, false);
4525 	report_prefix_pop();
4526 
4527 	/* Restore the controls to their original values */
4528 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
4529 done:
4530 	vmcs_write(PIN_CONTROLS, pin_ctrls);
4531 }
4532 
4533 static void test_eptp_ad_bit(u64 eptp, bool ctrl)
4534 {
4535 	vmcs_write(EPTP, eptp);
4536 	report_prefix_pushf("Enable-EPT enabled; EPT accessed and dirty flag %s",
4537 	    (eptp & EPTP_AD_FLAG) ? "1": "0");
4538 	test_vmx_controls(ctrl, false);
4539 	report_prefix_pop();
4540 
4541 }
4542 
4543 /*
4544  * 1. If the "enable EPT" VM-execution control is 1, the "EPTP VM-execution"
4545  *    control field must satisfy the following checks:
4546  *
4547  *     - The EPT memory type (bits 2:0) must be a value supported by the
4548  *	 processor as indicated in the IA32_VMX_EPT_VPID_CAP MSR.
4549  *     - Bits 5:3 (1 less than the EPT page-walk length) must be 3,
4550  *	 indicating an EPT page-walk length of 4.
4551  *     - Bit 6 (enable bit for accessed and dirty flags for EPT) must be
4552  *	 0 if bit 21 of the IA32_VMX_EPT_VPID_CAP MSR is read as 0,
4553  *	 indicating that the processor does not support accessed and dirty
4554  *	 dirty flags for EPT.
4555  *     - Reserved bits 11:7 and 63:N (where N is the processor's
4556  *	 physical-address width) must all be 0.
4557  *
4558  * 2. If the "unrestricted guest" VM-execution control is 1, the
4559  *    "enable EPT" VM-execution control must also be 1.
4560  */
4561 static void test_ept_eptp(void)
4562 {
4563 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4564 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4565 	u64 eptp_saved = vmcs_read(EPTP);
4566 	u32 primary = primary_saved;
4567 	u32 secondary = secondary_saved;
4568 	u64 msr, eptp = eptp_saved;
4569 	bool un_cache = false;
4570 	bool wr_bk = false;
4571 	bool ctrl;
4572 	u32 i, maxphysaddr;
4573 	u64 j, resv_bits_mask = 0;
4574 
4575 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4576 	    (ctrl_cpu_rev[1].clr & CPU_EPT))) {
4577 		test_skip("\"CPU secondary\" and/or \"enable EPT\" execution controls are not supported !");
4578 		return;
4579 	}
4580 
4581 	/*
4582 	 * Memory type (bits 2:0)
4583 	 */
4584 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
4585 	if (msr & EPT_CAP_UC)
4586 		un_cache = true;
4587 	if (msr & EPT_CAP_WB)
4588 		wr_bk = true;
4589 
4590 	primary |= CPU_SECONDARY;
4591 	vmcs_write(CPU_EXEC_CTRL0, primary);
4592 	secondary |= CPU_EPT;
4593 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4594 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4595 	    (3ul << EPTP_PG_WALK_LEN_SHIFT);
4596 	vmcs_write(EPTP, eptp);
4597 
4598 	for (i = 0; i < 8; i++) {
4599 		if (i == 0) {
4600 			if (un_cache) {
4601 				report_info("EPT paging structure memory-type is Un-cacheable\n");
4602 				ctrl = true;
4603 			} else {
4604 				ctrl = false;
4605 			}
4606 		} else if (i == 6) {
4607 			if (wr_bk) {
4608 				report_info("EPT paging structure memory-type is Write-back\n");
4609 				ctrl = true;
4610 			} else {
4611 				ctrl = false;
4612 			}
4613 		} else {
4614 			ctrl = false;
4615 		}
4616 
4617 		eptp = (eptp & ~EPT_MEM_TYPE_MASK) | i;
4618 		vmcs_write(EPTP, eptp);
4619 		report_prefix_pushf("Enable-EPT enabled; EPT memory type %lu",
4620 		    eptp & EPT_MEM_TYPE_MASK);
4621 		test_vmx_controls(ctrl, false);
4622 		report_prefix_pop();
4623 	}
4624 
4625 	eptp = (eptp & ~EPT_MEM_TYPE_MASK) | 6ul;
4626 
4627 	/*
4628 	 * Page walk length (bits 5:3)
4629 	 */
4630 	for (i = 0; i < 8; i++) {
4631 		eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4632 		    (i << EPTP_PG_WALK_LEN_SHIFT);
4633 		if (i == 3)
4634 			ctrl = true;
4635 		else
4636 			ctrl = false;
4637 
4638 		vmcs_write(EPTP, eptp);
4639 		report_prefix_pushf("Enable-EPT enabled; EPT page walk length %lu",
4640 		    eptp & EPTP_PG_WALK_LEN_MASK);
4641 		test_vmx_controls(ctrl, false);
4642 		report_prefix_pop();
4643 	}
4644 
4645 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4646 	    3ul << EPTP_PG_WALK_LEN_SHIFT;
4647 
4648 	/*
4649 	 * Accessed and dirty flag (bit 6)
4650 	 */
4651 	if (msr & EPT_CAP_AD_FLAG) {
4652 		report_info("Processor supports accessed and dirty flag");
4653 		eptp &= ~EPTP_AD_FLAG;
4654 		test_eptp_ad_bit(eptp, true);
4655 
4656 		eptp |= EPTP_AD_FLAG;
4657 		test_eptp_ad_bit(eptp, true);
4658 	} else {
4659 		report_info("Processor does not supports accessed and dirty flag");
4660 		eptp &= ~EPTP_AD_FLAG;
4661 		test_eptp_ad_bit(eptp, true);
4662 
4663 		eptp |= EPTP_AD_FLAG;
4664 		test_eptp_ad_bit(eptp, false);
4665 	}
4666 
4667 	/*
4668 	 * Reserved bits [11:7] and [63:N]
4669 	 */
4670 	for (i = 0; i < 32; i++) {
4671 		if (i  == 0)
4672 			ctrl = true;
4673 		else
4674 			ctrl = false;
4675 
4676 		eptp = (eptp &
4677 		    ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT)) |
4678 		    (i << EPTP_RESERV_BITS_SHIFT);
4679 		vmcs_write(EPTP, eptp);
4680 		report_prefix_pushf("Enable-EPT enabled; reserved bits [11:7] %lu",
4681 		    (eptp >> EPTP_RESERV_BITS_SHIFT) &
4682 		    EPTP_RESERV_BITS_MASK);
4683 		test_vmx_controls(ctrl, false);
4684 		report_prefix_pop();
4685 	}
4686 
4687 	eptp = (eptp & ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT));
4688 
4689 	maxphysaddr = cpuid_maxphyaddr();
4690 	for (i = 0; i < (63 - maxphysaddr + 1); i++) {
4691 		resv_bits_mask |= 1ul << i;
4692 	}
4693 
4694 	for (j = 0; j < (63 - maxphysaddr + 1); j++) {
4695 		if (j  == 0)
4696 			ctrl = true;
4697 		else
4698 			ctrl = false;
4699 
4700 		eptp = (eptp & ~(resv_bits_mask << maxphysaddr)) |
4701 		    (j << maxphysaddr);
4702 		vmcs_write(EPTP, eptp);
4703 		report_prefix_pushf("Enable-EPT enabled; reserved bits [63:N] %lu",
4704 		    (eptp >> maxphysaddr) & resv_bits_mask);
4705 		test_vmx_controls(ctrl, false);
4706 		report_prefix_pop();
4707 	}
4708 
4709 	secondary &= ~(CPU_EPT | CPU_URG);
4710 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4711 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest disabled");
4712 	test_vmx_controls(true, false);
4713 	report_prefix_pop();
4714 
4715 	secondary |= CPU_URG;
4716 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4717 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest enabled");
4718 	test_vmx_controls(false, false);
4719 	report_prefix_pop();
4720 
4721 	secondary |= CPU_EPT;
4722 	enable_ept();
4723 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest enabled");
4724 	test_vmx_controls(true, false);
4725 	report_prefix_pop();
4726 
4727 	secondary &= ~CPU_URG;
4728 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4729 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest disabled");
4730 	test_vmx_controls(true, false);
4731 	report_prefix_pop();
4732 
4733 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4734 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4735 	vmcs_write(EPTP, eptp_saved);
4736 }
4737 
4738 /*
4739  * If the 'enable PML' VM-execution control is 1, the 'enable EPT'
4740  * VM-execution control must also be 1. In addition, the PML address
4741  * must satisfy the following checks:
4742  *
4743  *    * Bits 11:0 of the address must be 0.
4744  *    * The address should not set any bits beyond the processor's
4745  *	physical-address width.
4746  *
4747  *  [Intel SDM]
4748  */
4749 static void test_pml(void)
4750 {
4751 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4752 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4753 	u32 primary = primary_saved;
4754 	u32 secondary = secondary_saved;
4755 
4756 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4757 	    (ctrl_cpu_rev[1].clr & CPU_EPT) && (ctrl_cpu_rev[1].clr & CPU_PML))) {
4758 		test_skip("\"Secondary execution\" control or \"enable EPT\" control or \"enable PML\" control is not supported !");
4759 		return;
4760 	}
4761 
4762 	primary |= CPU_SECONDARY;
4763 	vmcs_write(CPU_EXEC_CTRL0, primary);
4764 	secondary &= ~(CPU_PML | CPU_EPT);
4765 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4766 	report_prefix_pushf("enable-PML disabled, enable-EPT disabled");
4767 	test_vmx_controls(true, false);
4768 	report_prefix_pop();
4769 
4770 	secondary |= CPU_PML;
4771 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4772 	report_prefix_pushf("enable-PML enabled, enable-EPT disabled");
4773 	test_vmx_controls(false, false);
4774 	report_prefix_pop();
4775 
4776 	secondary |= CPU_EPT;
4777 	enable_ept();
4778 	report_prefix_pushf("enable-PML enabled, enable-EPT enabled");
4779 	test_vmx_controls(true, false);
4780 	report_prefix_pop();
4781 
4782 	secondary &= ~CPU_PML;
4783 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4784 	report_prefix_pushf("enable-PML disabled, enable EPT enabled");
4785 	test_vmx_controls(true, false);
4786 	report_prefix_pop();
4787 
4788 	test_vmcs_addr_reference(CPU_PML, PMLADDR, "PML address", "PML",
4789 				 PAGE_SIZE, false, false);
4790 
4791 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4792 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4793 }
4794 
4795  /*
4796  * If the "activate VMX-preemption timer" VM-execution control is 0, the
4797  * the "save VMX-preemption timer value" VM-exit control must also be 0.
4798  *
4799  *  [Intel SDM]
4800  */
4801 static void test_vmx_preemption_timer(void)
4802 {
4803 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4804 	u32 saved_exit = vmcs_read(EXI_CONTROLS);
4805 	u32 pin = saved_pin;
4806 	u32 exit = saved_exit;
4807 
4808 	if (!((ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) ||
4809 	    (ctrl_pin_rev.clr & PIN_PREEMPT))) {
4810 		printf("\"Save-VMX-preemption-timer\" control and/or \"Enable-VMX-preemption-timer\" control is not supported\n");
4811 		return;
4812 	}
4813 
4814 	pin |= PIN_PREEMPT;
4815 	vmcs_write(PIN_CONTROLS, pin);
4816 	exit &= ~EXI_SAVE_PREEMPT;
4817 	vmcs_write(EXI_CONTROLS, exit);
4818 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer disabled");
4819 	test_vmx_controls(true, false);
4820 	report_prefix_pop();
4821 
4822 	exit |= EXI_SAVE_PREEMPT;
4823 	vmcs_write(EXI_CONTROLS, exit);
4824 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer enabled");
4825 	test_vmx_controls(true, false);
4826 	report_prefix_pop();
4827 
4828 	pin &= ~PIN_PREEMPT;
4829 	vmcs_write(PIN_CONTROLS, pin);
4830 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer enabled");
4831 	test_vmx_controls(false, false);
4832 	report_prefix_pop();
4833 
4834 	exit &= ~EXI_SAVE_PREEMPT;
4835 	vmcs_write(EXI_CONTROLS, exit);
4836 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer disabled");
4837 	test_vmx_controls(true, false);
4838 	report_prefix_pop();
4839 
4840 	vmcs_write(PIN_CONTROLS, saved_pin);
4841 	vmcs_write(EXI_CONTROLS, saved_exit);
4842 }
4843 
4844 /*
4845  * Tests for VM-execution control fields
4846  */
4847 static void test_vm_execution_ctls(void)
4848 {
4849 	test_pin_based_ctls();
4850 	test_primary_processor_based_ctls();
4851 	test_secondary_processor_based_ctls();
4852 	test_cr3_targets();
4853 	test_io_bitmaps();
4854 	test_msr_bitmap();
4855 	test_apic_ctls();
4856 	test_tpr_threshold();
4857 	test_nmi_ctrls();
4858 	test_pml();
4859 	test_vpid();
4860 	test_ept_eptp();
4861 	test_vmx_preemption_timer();
4862 }
4863 
4864  /*
4865   * The following checks are performed for the VM-entry MSR-load address if
4866   * the VM-entry MSR-load count field is non-zero:
4867   *
4868   *    - The lower 4 bits of the VM-entry MSR-load address must be 0.
4869   *      The address should not set any bits beyond the processor’s
4870   *      physical-address width.
4871   *
4872   *    - The address of the last byte in the VM-entry MSR-load area
4873   *      should not set any bits beyond the processor’s physical-address
4874   *      width. The address of this last byte is VM-entry MSR-load address
4875   *      + (MSR count * 16) - 1. (The arithmetic used for the computation
4876   *      uses more bits than the processor’s physical-address width.)
4877   *
4878   *
4879   *  [Intel SDM]
4880   */
4881 static void test_entry_msr_load(void)
4882 {
4883 	entry_msr_load = alloc_page();
4884 	u64 tmp;
4885 	u32 entry_msr_ld_cnt = 1;
4886 	int i;
4887 	u32 addr_len = 64;
4888 
4889 	vmcs_write(ENT_MSR_LD_CNT, entry_msr_ld_cnt);
4890 
4891 	/* Check first 4 bits of VM-entry MSR-load address */
4892 	for (i = 0; i < 4; i++) {
4893 		tmp = (u64)entry_msr_load | 1ull << i;
4894 		vmcs_write(ENTER_MSR_LD_ADDR, tmp);
4895 		report_prefix_pushf("VM-entry MSR-load addr [4:0] %lx",
4896 				    tmp & 0xf);
4897 		test_vmx_controls(false, false);
4898 		report_prefix_pop();
4899 	}
4900 
4901 	if (basic.val & (1ul << 48))
4902 		addr_len = 32;
4903 
4904 	test_vmcs_addr_values("VM-entry-MSR-load address",
4905 				ENTER_MSR_LD_ADDR, 16, false, false,
4906 				4, addr_len - 1);
4907 
4908 	/*
4909 	 * Check last byte of VM-entry MSR-load address
4910 	 */
4911 	entry_msr_load = (struct vmx_msr_entry *)((u64)entry_msr_load & ~0xf);
4912 
4913 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
4914 							i < 64; i++) {
4915 		tmp = ((u64)entry_msr_load + entry_msr_ld_cnt * 16 - 1) |
4916 			1ul << i;
4917 		vmcs_write(ENTER_MSR_LD_ADDR,
4918 			   tmp - (entry_msr_ld_cnt * 16 - 1));
4919 		test_vmx_controls(false, false);
4920 	}
4921 
4922 	vmcs_write(ENT_MSR_LD_CNT, 2);
4923 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
4924 	test_vmx_controls(false, false);
4925 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
4926 	test_vmx_controls(true, false);
4927 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
4928 	test_vmx_controls(true, false);
4929 }
4930 
4931 /*
4932  * Tests for VM-entry control fields
4933  */
4934 static void test_vm_entry_ctls(void)
4935 {
4936 	test_invalid_event_injection();
4937 	test_entry_msr_load();
4938 }
4939 
4940 /*
4941  * The following checks are performed for the VM-exit MSR-store address if
4942  * the VM-exit MSR-store count field is non-zero:
4943  *
4944  *    - The lower 4 bits of the VM-exit MSR-store address must be 0.
4945  *      The address should not set any bits beyond the processor’s
4946  *      physical-address width.
4947  *
4948  *    - The address of the last byte in the VM-exit MSR-store area
4949  *      should not set any bits beyond the processor’s physical-address
4950  *      width. The address of this last byte is VM-exit MSR-store address
4951  *      + (MSR count * 16) - 1. (The arithmetic used for the computation
4952  *      uses more bits than the processor’s physical-address width.)
4953  *
4954  * If IA32_VMX_BASIC[48] is read as 1, neither address should set any bits
4955  * in the range 63:32.
4956  *
4957  *  [Intel SDM]
4958  */
4959 static void test_exit_msr_store(void)
4960 {
4961 	exit_msr_store = alloc_page();
4962 	u64 tmp;
4963 	u32 exit_msr_st_cnt = 1;
4964 	int i;
4965 	u32 addr_len = 64;
4966 
4967 	vmcs_write(EXI_MSR_ST_CNT, exit_msr_st_cnt);
4968 
4969 	/* Check first 4 bits of VM-exit MSR-store address */
4970 	for (i = 0; i < 4; i++) {
4971 		tmp = (u64)exit_msr_store | 1ull << i;
4972 		vmcs_write(EXIT_MSR_ST_ADDR, tmp);
4973 		report_prefix_pushf("VM-exit MSR-store addr [4:0] %lx",
4974 				    tmp & 0xf);
4975 		test_vmx_controls(false, false);
4976 		report_prefix_pop();
4977 	}
4978 
4979 	if (basic.val & (1ul << 48))
4980 		addr_len = 32;
4981 
4982 	test_vmcs_addr_values("VM-exit-MSR-store address",
4983 				EXIT_MSR_ST_ADDR, 16, false, false,
4984 				4, addr_len - 1);
4985 
4986 	/*
4987 	 * Check last byte of VM-exit MSR-store address
4988 	 */
4989 	exit_msr_store = (struct vmx_msr_entry *)((u64)exit_msr_store & ~0xf);
4990 
4991 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
4992 							i < 64; i++) {
4993 		tmp = ((u64)exit_msr_store + exit_msr_st_cnt * 16 - 1) |
4994 			1ul << i;
4995 		vmcs_write(EXIT_MSR_ST_ADDR,
4996 			   tmp - (exit_msr_st_cnt * 16 - 1));
4997                 test_vmx_controls(false, false);
4998 	}
4999 
5000 	vmcs_write(EXI_MSR_ST_CNT, 2);
5001 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5002 	test_vmx_controls(false, false);
5003 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5004 	test_vmx_controls(true, false);
5005 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5006 	test_vmx_controls(true, false);
5007 }
5008 
5009 /*
5010  * Tests for VM-exit controls
5011  */
5012 static void test_vm_exit_ctls(void)
5013 {
5014 	test_exit_msr_store();
5015 }
5016 
5017 /*
5018  * Check that the virtual CPU checks all of the VMX controls as
5019  * documented in the Intel SDM.
5020  */
5021 static void vmx_controls_test(void)
5022 {
5023 	/*
5024 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
5025 	 * fail due to invalid guest state, should we make it that
5026 	 * far.
5027 	 */
5028 	vmcs_write(GUEST_RFLAGS, 0);
5029 
5030 	test_vm_execution_ctls();
5031 	test_vm_entry_ctls();
5032 	test_vm_exit_ctls();
5033 }
5034 
5035 static bool valid_vmcs_for_vmentry(void)
5036 {
5037 	struct vmcs *current_vmcs = NULL;
5038 
5039 	if (vmcs_save(&current_vmcs))
5040 		return false;
5041 
5042 	return current_vmcs && !current_vmcs->hdr.shadow_vmcs;
5043 }
5044 
5045 static void try_vmentry_in_movss_shadow(void)
5046 {
5047 	u32 vm_inst_err;
5048 	u32 flags;
5049 	bool early_failure = false;
5050 	u32 expected_flags = X86_EFLAGS_FIXED;
5051 	bool valid_vmcs = valid_vmcs_for_vmentry();
5052 
5053 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
5054 
5055 	/*
5056 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
5057 	 * unsupported VMCS component").
5058 	 */
5059 	vmcs_write(~0u, 0);
5060 
5061 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
5062 			      "vmwrite %%rsp, %%rdx;"
5063 			      "mov 0f, %%rax;"
5064 			      "mov %[host_rip], %%edx;"
5065 			      "vmwrite %%rax, %%rdx;"
5066 			      "mov $-1, %%ah;"
5067 			      "sahf;"
5068 			      "mov %%ss, %%ax;"
5069 			      "mov %%ax, %%ss;"
5070 			      "vmlaunch;"
5071 			      "mov $1, %[early_failure];"
5072 			      "0: lahf;"
5073 			      "movzbl %%ah, %[flags]"
5074 			      : [early_failure] "+r" (early_failure),
5075 				[flags] "=&a" (flags)
5076 			      : [host_rsp] "i" (HOST_RSP),
5077 				[host_rip] "i" (HOST_RIP)
5078 			      : "rdx", "cc", "memory");
5079 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
5080 
5081 	report("Early VM-entry failure", early_failure);
5082 	report("RFLAGS[8:0] is %x (actual %x)", flags == expected_flags,
5083 	       expected_flags, flags);
5084 	if (valid_vmcs)
5085 		report("VM-instruction error is %d (actual %d)",
5086 		       vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
5087 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
5088 }
5089 
5090 static void vmentry_movss_shadow_test(void)
5091 {
5092 	struct vmcs *orig_vmcs;
5093 
5094 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
5095 
5096 	/*
5097 	 * Set the launched flag on the current VMCS to verify the correct
5098 	 * error priority, below.
5099 	 */
5100 	test_set_guest(v2_null_test_guest);
5101 	enter_guest();
5102 
5103 	/*
5104 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
5105 	 * fail due to invalid guest state (if we make it that far).
5106 	 */
5107 	vmcs_write(GUEST_RFLAGS, 0);
5108 
5109 	/*
5110 	 * "VM entry with events blocked by MOV SS" takes precedence over
5111 	 * "VMLAUNCH with non-clear VMCS."
5112 	 */
5113 	report_prefix_push("valid current-VMCS");
5114 	try_vmentry_in_movss_shadow();
5115 	report_prefix_pop();
5116 
5117 	/*
5118 	 * VMfailInvalid takes precedence over "VM entry with events
5119 	 * blocked by MOV SS."
5120 	 */
5121 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
5122 	report_prefix_push("no current-VMCS");
5123 	try_vmentry_in_movss_shadow();
5124 	report_prefix_pop();
5125 
5126 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
5127 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5128 }
5129 
5130 #define X86_FEATURE_PCID       (1 << 17)
5131 #define X86_FEATURE_MCE        (1 << 7)
5132 
5133 static int write_cr4_checking(unsigned long val)
5134 {
5135 	asm volatile(ASM_TRY("1f")
5136 		     "mov %0, %%cr4\n\t"
5137 		     "1:": : "r" (val));
5138 	return exception_vector();
5139 }
5140 
5141 static void vmx_cr_load_test(void)
5142 {
5143 	struct cpuid _cpuid = cpuid(1);
5144 	unsigned long cr4 = read_cr4(), cr3 = read_cr3();
5145 
5146 	if (!(_cpuid.c & X86_FEATURE_PCID)) {
5147 		report_skip("PCID not detected");
5148 		return;
5149 	}
5150 	if (!(_cpuid.d & X86_FEATURE_MCE)) {
5151 		report_skip("MCE not detected");
5152 		return;
5153 	}
5154 
5155 	TEST_ASSERT(!(cr4 & (X86_CR4_PCIDE | X86_CR4_MCE)));
5156 	TEST_ASSERT(!(cr3 & X86_CR3_PCID_MASK));
5157 
5158 	/* Enable PCID for L1. */
5159 	cr4 |= X86_CR4_PCIDE;
5160 	cr3 |= 0x1;
5161 	TEST_ASSERT(!write_cr4_checking(cr4));
5162 	write_cr3(cr3);
5163 
5164 	test_set_guest(v2_null_test_guest);
5165 	vmcs_write(HOST_CR4, cr4);
5166 	vmcs_write(HOST_CR3, cr3);
5167 	enter_guest();
5168 
5169 	/*
5170 	 * No exception is expected.
5171 	 *
5172 	 * NB. KVM loads the last guest write to CR4 into CR4 read
5173 	 *     shadow. In order to trigger an exit to KVM, we can set a
5174 	 *     bit that was zero in the above CR4 write and is owned by
5175 	 *     KVM. We choose to set CR4.MCE, which shall have no side
5176 	 *     effect because normally no guest MCE (e.g., as the result
5177 	 *     of bad memory) would happen during this test.
5178 	 */
5179 	TEST_ASSERT(!write_cr4_checking(cr4 | X86_CR4_MCE));
5180 
5181 	/* Cleanup L1 state: disable PCID. */
5182 	write_cr3(cr3 & ~X86_CR3_PCID_MASK);
5183 	TEST_ASSERT(!write_cr4_checking(cr4 & ~X86_CR4_PCIDE));
5184 }
5185 
5186 static void vmx_nm_test_guest(void)
5187 {
5188 	write_cr0(read_cr0() | X86_CR0_TS);
5189 	asm volatile("fnop");
5190 }
5191 
5192 static void check_nm_exit(const char *test)
5193 {
5194 	u32 reason = vmcs_read(EXI_REASON);
5195 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
5196 	const u32 expected = INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5197 		NM_VECTOR;
5198 
5199 	report("%s", reason == VMX_EXC_NMI && intr_info == expected, test);
5200 }
5201 
5202 /*
5203  * This test checks that:
5204  *
5205  * (a) If L2 launches with CR0.TS clear, but later sets CR0.TS, then
5206  *     a subsequent #NM VM-exit is reflected to L1.
5207  *
5208  * (b) If L2 launches with CR0.TS clear and CR0.EM set, then a
5209  *     subsequent #NM VM-exit is reflected to L1.
5210  */
5211 static void vmx_nm_test(void)
5212 {
5213 	unsigned long cr0 = read_cr0();
5214 
5215 	test_set_guest(vmx_nm_test_guest);
5216 
5217 	/*
5218 	 * L1 wants to intercept #NM exceptions encountered in L2.
5219 	 */
5220 	vmcs_write(EXC_BITMAP, 1 << NM_VECTOR);
5221 
5222 	/*
5223 	 * Launch L2 with CR0.TS clear, but don't claim host ownership of
5224 	 * any CR0 bits. L2 will set CR0.TS and then try to execute fnop,
5225 	 * which will raise #NM. L0 should reflect the #NM VM-exit to L1.
5226 	 */
5227 	vmcs_write(CR0_MASK, 0);
5228 	vmcs_write(GUEST_CR0, cr0 & ~X86_CR0_TS);
5229 	enter_guest();
5230 	check_nm_exit("fnop with CR0.TS set in L2 triggers #NM VM-exit to L1");
5231 
5232 	/*
5233 	 * Re-enter L2 at the fnop instruction, with CR0.TS clear but
5234 	 * CR0.EM set. The fnop will still raise #NM, and L0 should
5235 	 * reflect the #NM VM-exit to L1.
5236 	 */
5237 	vmcs_write(GUEST_CR0, (cr0 & ~X86_CR0_TS) | X86_CR0_EM);
5238 	enter_guest();
5239 	check_nm_exit("fnop with CR0.EM set in L2 triggers #NM VM-exit to L1");
5240 
5241 	/*
5242 	 * Re-enter L2 at the fnop instruction, with both CR0.TS and
5243 	 * CR0.EM clear. There will be no #NM, and the L2 guest should
5244 	 * exit normally.
5245 	 */
5246 	vmcs_write(GUEST_CR0, cr0 & ~(X86_CR0_TS | X86_CR0_EM));
5247 	enter_guest();
5248 }
5249 
5250 bool vmx_pending_event_ipi_fired;
5251 static void vmx_pending_event_ipi_isr(isr_regs_t *regs)
5252 {
5253 	vmx_pending_event_ipi_fired = true;
5254 	eoi();
5255 }
5256 
5257 bool vmx_pending_event_guest_run;
5258 static void vmx_pending_event_guest(void)
5259 {
5260 	vmcall();
5261 	vmx_pending_event_guest_run = true;
5262 }
5263 
5264 static void vmx_pending_event_test_core(bool guest_hlt)
5265 {
5266 	int ipi_vector = 0xf1;
5267 
5268 	vmx_pending_event_ipi_fired = false;
5269 	handle_irq(ipi_vector, vmx_pending_event_ipi_isr);
5270 
5271 	vmx_pending_event_guest_run = false;
5272 	test_set_guest(vmx_pending_event_guest);
5273 
5274 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
5275 
5276 	enter_guest();
5277 	skip_exit_vmcall();
5278 
5279 	if (guest_hlt)
5280 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5281 
5282 	irq_disable();
5283 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
5284 				   APIC_DM_FIXED | ipi_vector,
5285 				   0);
5286 
5287 	enter_guest();
5288 
5289 	assert_exit_reason(VMX_EXTINT);
5290 	report("Guest did not run before host received IPI",
5291 		   !vmx_pending_event_guest_run);
5292 
5293 	irq_enable();
5294 	asm volatile ("nop");
5295 	irq_disable();
5296 	report("Got pending interrupt after IRQ enabled",
5297 		   vmx_pending_event_ipi_fired);
5298 
5299 	if (guest_hlt)
5300 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
5301 
5302 	enter_guest();
5303 	report("Guest finished running when no interrupt",
5304 		   vmx_pending_event_guest_run);
5305 }
5306 
5307 static void vmx_pending_event_test(void)
5308 {
5309 	vmx_pending_event_test_core(false);
5310 }
5311 
5312 static void vmx_pending_event_hlt_test(void)
5313 {
5314 	vmx_pending_event_test_core(true);
5315 }
5316 
5317 static int vmx_window_test_ud_count;
5318 
5319 static void vmx_window_test_ud_handler(struct ex_regs *regs)
5320 {
5321 	vmx_window_test_ud_count++;
5322 }
5323 
5324 static void vmx_nmi_window_test_guest(void)
5325 {
5326 	handle_exception(UD_VECTOR, vmx_window_test_ud_handler);
5327 
5328 	asm volatile("vmcall\n\t"
5329 		     "nop\n\t");
5330 
5331 	handle_exception(UD_VECTOR, NULL);
5332 }
5333 
5334 static void verify_nmi_window_exit(u64 rip)
5335 {
5336 	u32 exit_reason = vmcs_read(EXI_REASON);
5337 
5338 	report("Exit reason (%d) is 'NMI window'",
5339 	       exit_reason == VMX_NMI_WINDOW, exit_reason);
5340 	report("RIP (%#lx) is %#lx", vmcs_read(GUEST_RIP) == rip,
5341 	       vmcs_read(GUEST_RIP), rip);
5342 	report("Activity state (%ld) is 'ACTIVE'",
5343 	       vmcs_read(GUEST_ACTV_STATE) == ACTV_ACTIVE,
5344 	       vmcs_read(GUEST_ACTV_STATE));
5345 }
5346 
5347 static void vmx_nmi_window_test(void)
5348 {
5349 	u64 nop_addr;
5350 	void *ud_fault_addr = get_idt_addr(&boot_idt[UD_VECTOR]);
5351 
5352 	if (!(ctrl_pin_rev.clr & PIN_VIRT_NMI)) {
5353 		report_skip("CPU does not support the \"Virtual NMIs\" VM-execution control.");
5354 		return;
5355 	}
5356 
5357 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
5358 		report_skip("CPU does not support the \"NMI-window exiting\" VM-execution control.");
5359 		return;
5360 	}
5361 
5362 	vmx_window_test_ud_count = 0;
5363 
5364 	report_prefix_push("NMI-window");
5365 	test_set_guest(vmx_nmi_window_test_guest);
5366 	vmcs_set_bits(PIN_CONTROLS, PIN_VIRT_NMI);
5367 	enter_guest();
5368 	skip_exit_vmcall();
5369 	nop_addr = vmcs_read(GUEST_RIP);
5370 
5371 	/*
5372 	 * Ask for "NMI-window exiting," and expect an immediate VM-exit.
5373 	 * RIP will not advance.
5374 	 */
5375 	report_prefix_push("active, no blocking");
5376 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
5377 	enter_guest();
5378 	verify_nmi_window_exit(nop_addr);
5379 	report_prefix_pop();
5380 
5381 	/*
5382 	 * Ask for "NMI-window exiting" in a MOV-SS shadow, and expect
5383 	 * a VM-exit on the next instruction after the nop. (The nop
5384 	 * is one byte.)
5385 	 */
5386 	report_prefix_push("active, blocking by MOV-SS");
5387 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5388 	enter_guest();
5389 	verify_nmi_window_exit(nop_addr + 1);
5390 	report_prefix_pop();
5391 
5392 	/*
5393 	 * Ask for "NMI-window exiting" (with event injection), and
5394 	 * expect a VM-exit after the event is injected. (RIP should
5395 	 * be at the address specified in the IDT entry for #UD.)
5396 	 */
5397 	report_prefix_push("active, no blocking, injecting #UD");
5398 	vmcs_write(ENT_INTR_INFO,
5399 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | UD_VECTOR);
5400 	enter_guest();
5401 	verify_nmi_window_exit((u64)ud_fault_addr);
5402 	report_prefix_pop();
5403 
5404 	/*
5405 	 * Ask for "NMI-window exiting" with NMI blocking, and expect
5406 	 * a VM-exit after the next IRET (i.e. after the #UD handler
5407 	 * returns). So, RIP should be back at one byte past the nop.
5408 	 */
5409 	report_prefix_push("active, blocking by NMI");
5410 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_NMI);
5411 	enter_guest();
5412 	verify_nmi_window_exit(nop_addr + 1);
5413 	report("#UD handler executed once (actual %d times)",
5414 	       vmx_window_test_ud_count == 1,
5415 	       vmx_window_test_ud_count);
5416 	report_prefix_pop();
5417 
5418 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
5419 		report_skip("CPU does not support activity state HLT.");
5420 	} else {
5421 		/*
5422 		 * Ask for "NMI-window exiting" when entering activity
5423 		 * state HLT, and expect an immediate VM-exit. RIP is
5424 		 * still one byte past the nop.
5425 		 */
5426 		report_prefix_push("halted, no blocking");
5427 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5428 		enter_guest();
5429 		verify_nmi_window_exit(nop_addr + 1);
5430 		report_prefix_pop();
5431 
5432 		/*
5433 		 * Ask for "NMI-window exiting" when entering activity
5434 		 * state HLT (with event injection), and expect a
5435 		 * VM-exit after the event is injected. (RIP should be
5436 		 * at the address specified in the IDT entry for #UD.)
5437 		 */
5438 		report_prefix_push("halted, no blocking, injecting #UD");
5439 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5440 		vmcs_write(ENT_INTR_INFO,
5441 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5442 			   UD_VECTOR);
5443 		enter_guest();
5444 		verify_nmi_window_exit((u64)ud_fault_addr);
5445 		report_prefix_pop();
5446 	}
5447 
5448 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
5449 	enter_guest();
5450 	report_prefix_pop();
5451 }
5452 
5453 static void vmx_intr_window_test_guest(void)
5454 {
5455 	handle_exception(UD_VECTOR, vmx_window_test_ud_handler);
5456 
5457 	/*
5458 	 * The two consecutive STIs are to ensure that only the first
5459 	 * one has a shadow. Note that NOP and STI are one byte
5460 	 * instructions.
5461 	 */
5462 	asm volatile("vmcall\n\t"
5463 		     "nop\n\t"
5464 		     "sti\n\t"
5465 		     "sti\n\t");
5466 
5467 	handle_exception(UD_VECTOR, NULL);
5468 }
5469 
5470 static void verify_intr_window_exit(u64 rip)
5471 {
5472 	u32 exit_reason = vmcs_read(EXI_REASON);
5473 
5474 	report("Exit reason (%d) is 'interrupt window'",
5475 	       exit_reason == VMX_INTR_WINDOW, exit_reason);
5476 	report("RIP (%#lx) is %#lx", vmcs_read(GUEST_RIP) == rip,
5477 	       vmcs_read(GUEST_RIP), rip);
5478 	report("Activity state (%ld) is 'ACTIVE'",
5479 	       vmcs_read(GUEST_ACTV_STATE) == ACTV_ACTIVE,
5480 	       vmcs_read(GUEST_ACTV_STATE));
5481 }
5482 
5483 static void vmx_intr_window_test(void)
5484 {
5485 	u64 vmcall_addr;
5486 	u64 nop_addr;
5487 	unsigned int orig_ud_gate_type;
5488 	void *ud_fault_addr = get_idt_addr(&boot_idt[UD_VECTOR]);
5489 
5490 	if (!(ctrl_cpu_rev[0].clr & CPU_INTR_WINDOW)) {
5491 		report_skip("CPU does not support the \"interrupt-window exiting\" VM-execution control.");
5492 		return;
5493 	}
5494 
5495 	/*
5496 	 * Change the IDT entry for #UD from interrupt gate to trap gate,
5497 	 * so that it won't clear RFLAGS.IF. We don't want interrupts to
5498 	 * be disabled after vectoring a #UD.
5499 	 */
5500 	orig_ud_gate_type = boot_idt[UD_VECTOR].type;
5501 	boot_idt[UD_VECTOR].type = 15;
5502 
5503 	report_prefix_push("interrupt-window");
5504 	test_set_guest(vmx_intr_window_test_guest);
5505 	enter_guest();
5506 	assert_exit_reason(VMX_VMCALL);
5507 	vmcall_addr = vmcs_read(GUEST_RIP);
5508 
5509 	/*
5510 	 * Ask for "interrupt-window exiting" with RFLAGS.IF set and
5511 	 * no blocking; expect an immediate VM-exit. Note that we have
5512 	 * not advanced past the vmcall instruction yet, so RIP should
5513 	 * point to the vmcall instruction.
5514 	 */
5515 	report_prefix_push("active, no blocking, RFLAGS.IF=1");
5516 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5517 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_IF);
5518 	enter_guest();
5519 	verify_intr_window_exit(vmcall_addr);
5520 	report_prefix_pop();
5521 
5522 	/*
5523 	 * Ask for "interrupt-window exiting" (with event injection)
5524 	 * with RFLAGS.IF set and no blocking; expect a VM-exit after
5525 	 * the event is injected. That is, RIP should should be at the
5526 	 * address specified in the IDT entry for #UD.
5527 	 */
5528 	report_prefix_push("active, no blocking, RFLAGS.IF=1, injecting #UD");
5529 	vmcs_write(ENT_INTR_INFO,
5530 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | UD_VECTOR);
5531 	vmcall_addr = vmcs_read(GUEST_RIP);
5532 	enter_guest();
5533 	verify_intr_window_exit((u64)ud_fault_addr);
5534 	report_prefix_pop();
5535 
5536 	/*
5537 	 * Let the L2 guest run through the IRET, back to the VMCALL.
5538 	 * We have to clear the "interrupt-window exiting"
5539 	 * VM-execution control, or it would just keep causing
5540 	 * VM-exits. Then, advance past the VMCALL and set the
5541 	 * "interrupt-window exiting" VM-execution control again.
5542 	 */
5543 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5544 	enter_guest();
5545 	skip_exit_vmcall();
5546 	nop_addr = vmcs_read(GUEST_RIP);
5547 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5548 
5549 	/*
5550 	 * Ask for "interrupt-window exiting" in a MOV-SS shadow with
5551 	 * RFLAGS.IF set, and expect a VM-exit on the next
5552 	 * instruction. (NOP is one byte.)
5553 	 */
5554 	report_prefix_push("active, blocking by MOV-SS, RFLAGS.IF=1");
5555 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5556 	enter_guest();
5557 	verify_intr_window_exit(nop_addr + 1);
5558 	report_prefix_pop();
5559 
5560 	/*
5561 	 * Back up to the NOP and ask for "interrupt-window exiting"
5562 	 * in an STI shadow with RFLAGS.IF set, and expect a VM-exit
5563 	 * on the next instruction. (NOP is one byte.)
5564 	 */
5565 	report_prefix_push("active, blocking by STI, RFLAGS.IF=1");
5566 	vmcs_write(GUEST_RIP, nop_addr);
5567 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_STI);
5568 	enter_guest();
5569 	verify_intr_window_exit(nop_addr + 1);
5570 	report_prefix_pop();
5571 
5572 	/*
5573 	 * Ask for "interrupt-window exiting" with RFLAGS.IF clear,
5574 	 * and expect a VM-exit on the instruction following the STI
5575 	 * shadow. Only the first STI (which is one byte past the NOP)
5576 	 * should have a shadow. The second STI (which is two bytes
5577 	 * past the NOP) has no shadow. Therefore, the interrupt
5578 	 * window opens at three bytes past the NOP.
5579 	 */
5580 	report_prefix_push("active, RFLAGS.IF = 0");
5581 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5582 	enter_guest();
5583 	verify_intr_window_exit(nop_addr + 3);
5584 	report_prefix_pop();
5585 
5586 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
5587 		report_skip("CPU does not support activity state HLT.");
5588 	} else {
5589 		/*
5590 		 * Ask for "interrupt-window exiting" when entering
5591 		 * activity state HLT, and expect an immediate
5592 		 * VM-exit. RIP is still three bytes past the nop.
5593 		 */
5594 		report_prefix_push("halted, no blocking");
5595 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5596 		enter_guest();
5597 		verify_intr_window_exit(nop_addr + 3);
5598 		report_prefix_pop();
5599 
5600 		/*
5601 		 * Ask for "interrupt-window exiting" when entering
5602 		 * activity state HLT (with event injection), and
5603 		 * expect a VM-exit after the event is injected. That
5604 		 * is, RIP should should be at the address specified
5605 		 * in the IDT entry for #UD.
5606 		 */
5607 		report_prefix_push("halted, no blocking, injecting #UD");
5608 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
5609 		vmcs_write(ENT_INTR_INFO,
5610 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
5611 			   UD_VECTOR);
5612 		enter_guest();
5613 		verify_intr_window_exit((u64)ud_fault_addr);
5614 		report_prefix_pop();
5615 	}
5616 
5617 	boot_idt[UD_VECTOR].type = orig_ud_gate_type;
5618 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
5619 	enter_guest();
5620 	report_prefix_pop();
5621 }
5622 
5623 #define GUEST_TSC_OFFSET (1u << 30)
5624 
5625 static u64 guest_tsc;
5626 
5627 static void vmx_store_tsc_test_guest(void)
5628 {
5629 	guest_tsc = rdtsc();
5630 }
5631 
5632 /*
5633  * This test ensures that when IA32_TSC is in the VM-exit MSR-store
5634  * list, the value saved is not subject to the TSC offset that is
5635  * applied to RDTSC/RDTSCP/RDMSR(IA32_TSC) in guest execution.
5636  */
5637 static void vmx_store_tsc_test(void)
5638 {
5639 	struct vmx_msr_entry msr_entry = { .index = MSR_IA32_TSC };
5640 	u64 low, high;
5641 
5642 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET)) {
5643 		report_skip("'Use TSC offsetting' not supported");
5644 		return;
5645 	}
5646 
5647 	test_set_guest(vmx_store_tsc_test_guest);
5648 
5649 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
5650 	vmcs_write(EXI_MSR_ST_CNT, 1);
5651 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(&msr_entry));
5652 	vmcs_write(TSC_OFFSET, GUEST_TSC_OFFSET);
5653 
5654 	low = rdtsc();
5655 	enter_guest();
5656 	high = rdtsc();
5657 
5658 	report("RDTSC value in the guest (%lu) is in range [%lu, %lu]",
5659 	       low + GUEST_TSC_OFFSET <= guest_tsc &&
5660 	       guest_tsc <= high + GUEST_TSC_OFFSET,
5661 	       guest_tsc, low + GUEST_TSC_OFFSET, high + GUEST_TSC_OFFSET);
5662 	report("IA32_TSC value saved in the VM-exit MSR-store list (%lu) is in range [%lu, %lu]",
5663 	       low <= msr_entry.value && msr_entry.value <= high,
5664 	       msr_entry.value, low, high);
5665 }
5666 
5667 static void vmx_db_test_guest(void)
5668 {
5669 	/*
5670 	 * For a hardware generated single-step #DB.
5671 	 */
5672 	asm volatile("vmcall;"
5673 		     "nop;"
5674 		     ".Lpost_nop:");
5675 	/*
5676 	 * ...in a MOVSS shadow, with pending debug exceptions.
5677 	 */
5678 	asm volatile("vmcall;"
5679 		     "nop;"
5680 		     ".Lpost_movss_nop:");
5681 	/*
5682 	 * For an L0 synthesized single-step #DB. (L0 intercepts WBINVD and
5683 	 * emulates it in software.)
5684 	 */
5685 	asm volatile("vmcall;"
5686 		     "wbinvd;"
5687 		     ".Lpost_wbinvd:");
5688 	/*
5689 	 * ...in a MOVSS shadow, with pending debug exceptions.
5690 	 */
5691 	asm volatile("vmcall;"
5692 		     "wbinvd;"
5693 		     ".Lpost_movss_wbinvd:");
5694 	/*
5695 	 * For a hardware generated single-step #DB in a transactional region.
5696 	 */
5697 	asm volatile("vmcall;"
5698 		     ".Lxbegin: xbegin .Lskip_rtm;"
5699 		     "xend;"
5700 		     ".Lskip_rtm:");
5701 }
5702 
5703 /*
5704  * Clear the pending debug exceptions and RFLAGS.TF and re-enter
5705  * L2. No #DB is delivered and L2 continues to the next point of
5706  * interest.
5707  */
5708 static void dismiss_db(void)
5709 {
5710 	vmcs_write(GUEST_PENDING_DEBUG, 0);
5711 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
5712 	enter_guest();
5713 }
5714 
5715 /*
5716  * Check a variety of VMCS fields relevant to an intercepted #DB exception.
5717  * Then throw away the #DB exception and resume L2.
5718  */
5719 static void check_db_exit(bool xfail_qual, bool xfail_dr6, bool xfail_pdbg,
5720 			  void *expected_rip, u64 expected_exit_qual,
5721 			  u64 expected_dr6)
5722 {
5723 	u32 reason = vmcs_read(EXI_REASON);
5724 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
5725 	u64 exit_qual = vmcs_read(EXI_QUALIFICATION);
5726 	u64 guest_rip = vmcs_read(GUEST_RIP);
5727 	u64 guest_pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
5728 	u64 dr6 = read_dr6();
5729 	const u32 expected_intr_info = INTR_INFO_VALID_MASK |
5730 		INTR_TYPE_HARD_EXCEPTION | DB_VECTOR;
5731 
5732 	report("Expected #DB VM-exit",
5733 	       reason == VMX_EXC_NMI && intr_info == expected_intr_info);
5734 	report("Expected RIP %p (actual %lx)", (u64)expected_rip == guest_rip,
5735 	       expected_rip, guest_rip);
5736 	report_xfail("Expected pending debug exceptions 0 (actual %lx)",
5737 		     xfail_pdbg, 0 == guest_pending_dbg, guest_pending_dbg);
5738 	report_xfail("Expected exit qualification %lx (actual %lx)", xfail_qual,
5739 		     expected_exit_qual == exit_qual,
5740 		     expected_exit_qual, exit_qual);
5741 	report_xfail("Expected DR6 %lx (actual %lx)", xfail_dr6,
5742 		     expected_dr6 == dr6, expected_dr6, dr6);
5743 	dismiss_db();
5744 }
5745 
5746 /*
5747  * Assuming the guest has just exited on a VMCALL instruction, skip
5748  * over the vmcall, and set the guest's RFLAGS.TF in the VMCS. If
5749  * pending debug exceptions are non-zero, set the VMCS up as if the
5750  * previous instruction was a MOVSS that generated the indicated
5751  * pending debug exceptions. Then enter L2.
5752  */
5753 static void single_step_guest(const char *test_name, u64 starting_dr6,
5754 			      u64 pending_debug_exceptions)
5755 {
5756 	printf("\n%s\n", test_name);
5757 	skip_exit_vmcall();
5758 	write_dr6(starting_dr6);
5759 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
5760 	if (pending_debug_exceptions) {
5761 		vmcs_write(GUEST_PENDING_DEBUG, pending_debug_exceptions);
5762 		vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
5763 	}
5764 	enter_guest();
5765 }
5766 
5767 /*
5768  * When L1 intercepts #DB, verify that a single-step trap clears
5769  * pending debug exceptions, populates the exit qualification field
5770  * properly, and that DR6 is not prematurely clobbered. In a
5771  * (simulated) MOVSS shadow, make sure that the pending debug
5772  * exception bits are properly accumulated into the exit qualification
5773  * field.
5774  */
5775 static void vmx_db_test(void)
5776 {
5777 	/*
5778 	 * We are going to set a few arbitrary bits in DR6 to verify that
5779 	 * (a) DR6 is not modified by an intercepted #DB, and
5780 	 * (b) stale bits in DR6 (DR6.BD, in particular) don't leak into
5781          *     the exit qualification field for a subsequent #DB exception.
5782 	 */
5783 	const u64 starting_dr6 = DR6_RESERVED | BIT(13) | DR_TRAP3 | DR_TRAP1;
5784 	extern char post_nop asm(".Lpost_nop");
5785 	extern char post_movss_nop asm(".Lpost_movss_nop");
5786 	extern char post_wbinvd asm(".Lpost_wbinvd");
5787 	extern char post_movss_wbinvd asm(".Lpost_movss_wbinvd");
5788 	extern char xbegin asm(".Lxbegin");
5789 	extern char skip_rtm asm(".Lskip_rtm");
5790 
5791 	/*
5792 	 * L1 wants to intercept #DB exceptions encountered in L2.
5793 	 */
5794 	vmcs_write(EXC_BITMAP, BIT(DB_VECTOR));
5795 
5796 	/*
5797 	 * Start L2 and run it up to the first point of interest.
5798 	 */
5799 	test_set_guest(vmx_db_test_guest);
5800 	enter_guest();
5801 
5802 	/*
5803 	 * Hardware-delivered #DB trap for single-step sets the
5804 	 * standard that L0 has to follow for emulated instructions.
5805 	 */
5806 	single_step_guest("Hardware delivered single-step", starting_dr6, 0);
5807 	check_db_exit(false, false, false, &post_nop, DR_STEP, starting_dr6);
5808 
5809 	/*
5810 	 * Hardware-delivered #DB trap for single-step in MOVSS shadow
5811 	 * also sets the standard that L0 has to follow for emulated
5812 	 * instructions. Here, we establish the VMCS pending debug
5813 	 * exceptions to indicate that the simulated MOVSS triggered a
5814 	 * data breakpoint as well as the single-step trap.
5815 	 */
5816 	single_step_guest("Hardware delivered single-step in MOVSS shadow",
5817 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0 );
5818 	check_db_exit(false, false, false, &post_movss_nop, DR_STEP | DR_TRAP0,
5819 		      starting_dr6);
5820 
5821 	/*
5822 	 * L0 synthesized #DB trap for single-step is buggy, because
5823 	 * kvm (a) clobbers DR6 too early, and (b) tries its best to
5824 	 * reconstitute the exit qualification from the prematurely
5825 	 * modified DR6, but fails miserably.
5826 	 */
5827 	single_step_guest("Software synthesized single-step", starting_dr6, 0);
5828 	check_db_exit(true, true, false, &post_wbinvd, DR_STEP, starting_dr6);
5829 
5830 	/*
5831 	 * L0 synthesized #DB trap for single-step in MOVSS shadow is
5832 	 * even worse, because L0 also leaves the pending debug
5833 	 * exceptions in the VMCS instead of accumulating them into
5834 	 * the exit qualification field for the #DB exception.
5835 	 */
5836 	single_step_guest("Software synthesized single-step in MOVSS shadow",
5837 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0);
5838 	check_db_exit(true, true, true, &post_movss_wbinvd, DR_STEP | DR_TRAP0,
5839 		      starting_dr6);
5840 
5841 	/*
5842 	 * Optional RTM test for hardware that supports RTM, to
5843 	 * demonstrate that the current volume 3 of the SDM
5844 	 * (325384-067US), table 27-1 is incorrect. Bit 16 of the exit
5845 	 * qualification for debug exceptions is not reserved. It is
5846 	 * set to 1 if a debug exception (#DB) or a breakpoint
5847 	 * exception (#BP) occurs inside an RTM region while advanced
5848 	 * debugging of RTM transactional regions is enabled.
5849 	 */
5850 	if (cpuid(7).b & BIT(11)) {
5851 		vmcs_write(ENT_CONTROLS,
5852 			   vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
5853 		/*
5854 		 * Set DR7.RTM[bit 11] and IA32_DEBUGCTL.RTM[bit 15]
5855 		 * in the guest to enable advanced debugging of RTM
5856 		 * transactional regions.
5857 		 */
5858 		vmcs_write(GUEST_DR7, BIT(11));
5859 		vmcs_write(GUEST_DEBUGCTL, BIT(15));
5860 		single_step_guest("Hardware delivered single-step in "
5861 				  "transactional region", starting_dr6, 0);
5862 		check_db_exit(false, false, false, &xbegin, BIT(16),
5863 			      starting_dr6);
5864 	} else {
5865 		vmcs_write(GUEST_RIP, (u64)&skip_rtm);
5866 		enter_guest();
5867 	}
5868 }
5869 
5870 static bool cpu_has_apicv(void)
5871 {
5872 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
5873 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
5874 		(ctrl_pin_rev.clr & PIN_POST_INTR));
5875 }
5876 
5877 static void enable_vid(void)
5878 {
5879 	void *virtual_apic_page;
5880 
5881 	assert(cpu_has_apicv());
5882 
5883 	disable_intercept_for_x2apic_msrs();
5884 
5885 	virtual_apic_page = alloc_page();
5886 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
5887 
5888 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
5889 
5890 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
5891 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
5892 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
5893 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
5894 
5895 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY | CPU_TPR_SHADOW);
5896 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VINTD | CPU_VIRT_X2APIC);
5897 }
5898 
5899 static void trigger_ioapic_scan_thread(void *data)
5900 {
5901 	/* Wait until other CPU entered L2 */
5902 	while (vmx_get_test_stage() != 1)
5903 		;
5904 
5905 	/* Trigger ioapic scan */
5906 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
5907 	vmx_set_test_stage(2);
5908 }
5909 
5910 static void irq_79_handler_guest(isr_regs_t *regs)
5911 {
5912 	eoi();
5913 
5914 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
5915 	vmcall();
5916 }
5917 
5918 /*
5919  * Constant for num of busy-loop iterations after which
5920  * a timer interrupt should have happened in host
5921  */
5922 #define TIMER_INTERRUPT_DELAY 100000000
5923 
5924 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
5925 {
5926 	handle_irq(0x79, irq_79_handler_guest);
5927 	irq_enable();
5928 
5929 	/* Signal to L1 CPU to trigger ioapic scan */
5930 	vmx_set_test_stage(1);
5931 	/* Wait until L1 CPU to trigger ioapic scan */
5932 	while (vmx_get_test_stage() != 2)
5933 		;
5934 
5935 	/*
5936 	 * Wait for L0 timer interrupt to be raised while we run in L2
5937 	 * such that L0 will process the IOAPIC scan request before
5938 	 * resuming L2
5939 	 */
5940 	delay(TIMER_INTERRUPT_DELAY);
5941 
5942 	asm volatile ("int $0x79");
5943 }
5944 
5945 static void vmx_eoi_bitmap_ioapic_scan_test(void)
5946 {
5947 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
5948 		report_skip(__func__);
5949 		return;
5950 	}
5951 
5952 	enable_vid();
5953 
5954 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
5955 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
5956 
5957 	/*
5958 	 * Launch L2.
5959 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
5960 	 * In case the reason isn't VMX_VMCALL, the asserion inside
5961 	 * skip_exit_vmcall() will fail.
5962 	 */
5963 	enter_guest();
5964 	skip_exit_vmcall();
5965 
5966 	/* Let L2 finish */
5967 	enter_guest();
5968 	report(__func__, 1);
5969 }
5970 
5971 #define HLT_WITH_RVI_VECTOR		(0xf1)
5972 
5973 bool vmx_hlt_with_rvi_guest_isr_fired;
5974 static void vmx_hlt_with_rvi_guest_isr(isr_regs_t *regs)
5975 {
5976 	vmx_hlt_with_rvi_guest_isr_fired = true;
5977 	eoi();
5978 }
5979 
5980 static void vmx_hlt_with_rvi_guest(void)
5981 {
5982 	handle_irq(HLT_WITH_RVI_VECTOR, vmx_hlt_with_rvi_guest_isr);
5983 
5984 	irq_enable();
5985 	asm volatile ("nop");
5986 
5987 	vmcall();
5988 }
5989 
5990 static void vmx_hlt_with_rvi_test(void)
5991 {
5992 	if (!cpu_has_apicv()) {
5993 		report_skip(__func__);
5994 		return;
5995 	}
5996 
5997 	enable_vid();
5998 
5999 	vmx_hlt_with_rvi_guest_isr_fired = false;
6000 	test_set_guest(vmx_hlt_with_rvi_guest);
6001 
6002 	enter_guest();
6003 	skip_exit_vmcall();
6004 
6005 	vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
6006 	vmcs_write(GUEST_INT_STATUS, HLT_WITH_RVI_VECTOR);
6007 	enter_guest();
6008 
6009 	report("Interrupt raised in guest", vmx_hlt_with_rvi_guest_isr_fired);
6010 }
6011 
6012 static void set_irq_line_thread(void *data)
6013 {
6014 	/* Wait until other CPU entered L2 */
6015 	while (vmx_get_test_stage() != 1)
6016 		;
6017 
6018 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
6019 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
6020 	vmx_set_test_stage(2);
6021 }
6022 
6023 static bool irq_78_handler_vmcall_before_eoi;
6024 static void irq_78_handler_guest(isr_regs_t *regs)
6025 {
6026 	set_irq_line(0xf, 0);
6027 	if (irq_78_handler_vmcall_before_eoi)
6028 		vmcall();
6029 	eoi();
6030 	vmcall();
6031 }
6032 
6033 static void vmx_apic_passthrough_guest(void)
6034 {
6035 	handle_irq(0x78, irq_78_handler_guest);
6036 	irq_enable();
6037 
6038 	/* If requested, wait for other CPU to trigger ioapic scan */
6039 	if (vmx_get_test_stage() < 1) {
6040 		vmx_set_test_stage(1);
6041 		while (vmx_get_test_stage() != 2)
6042 			;
6043 	}
6044 
6045 	set_irq_line(0xf, 1);
6046 }
6047 
6048 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
6049 {
6050 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
6051 		report_skip(__func__);
6052 		return;
6053 	}
6054 
6055 	u64 cpu_ctrl_0 = CPU_SECONDARY;
6056 	u64 cpu_ctrl_1 = 0;
6057 
6058 	disable_intercept_for_x2apic_msrs();
6059 
6060 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
6061 
6062 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
6063 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
6064 
6065 	if (set_irq_line_from_thread) {
6066 		irq_78_handler_vmcall_before_eoi = false;
6067 		on_cpu_async(1, set_irq_line_thread, NULL);
6068 	} else {
6069 		irq_78_handler_vmcall_before_eoi = true;
6070 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
6071 		vmx_set_test_stage(2);
6072 	}
6073 	test_set_guest(vmx_apic_passthrough_guest);
6074 
6075 	if (irq_78_handler_vmcall_before_eoi) {
6076 		/* Before EOI remote_irr should still be set */
6077 		enter_guest();
6078 		skip_exit_vmcall();
6079 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
6080 			"IOAPIC pass-through: remote_irr=1 before EOI");
6081 	}
6082 
6083 	/* After EOI remote_irr should be cleared */
6084 	enter_guest();
6085 	skip_exit_vmcall();
6086 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
6087 		"IOAPIC pass-through: remote_irr=0 after EOI");
6088 
6089 	/* Let L2 finish */
6090 	enter_guest();
6091 	report(__func__, 1);
6092 }
6093 
6094 static void vmx_apic_passthrough_test(void)
6095 {
6096 	vmx_apic_passthrough(false);
6097 }
6098 
6099 static void vmx_apic_passthrough_thread_test(void)
6100 {
6101 	vmx_apic_passthrough(true);
6102 }
6103 
6104 enum vmcs_access {
6105 	ACCESS_VMREAD,
6106 	ACCESS_VMWRITE,
6107 	ACCESS_NONE,
6108 };
6109 
6110 struct vmcs_shadow_test_common {
6111 	enum vmcs_access op;
6112 	enum Reason reason;
6113 	u64 field;
6114 	u64 value;
6115 	u64 flags;
6116 	u64 time;
6117 } l1_l2_common;
6118 
6119 static inline u64 vmread_flags(u64 field, u64 *val)
6120 {
6121 	u64 flags;
6122 
6123 	asm volatile ("vmread %2, %1; pushf; pop %0"
6124 		      : "=r" (flags), "=rm" (*val) : "r" (field) : "cc");
6125 	return flags & X86_EFLAGS_ALU;
6126 }
6127 
6128 static inline u64 vmwrite_flags(u64 field, u64 val)
6129 {
6130 	u64 flags;
6131 
6132 	asm volatile ("vmwrite %1, %2; pushf; pop %0"
6133 		      : "=r"(flags) : "rm" (val), "r" (field) : "cc");
6134 	return flags & X86_EFLAGS_ALU;
6135 }
6136 
6137 static void vmx_vmcs_shadow_test_guest(void)
6138 {
6139 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6140 	u64 start;
6141 
6142 	while (c->op != ACCESS_NONE) {
6143 		start = rdtsc();
6144 		switch (c->op) {
6145 		default:
6146 			c->flags = -1ull;
6147 			break;
6148 		case ACCESS_VMREAD:
6149 			c->flags = vmread_flags(c->field, &c->value);
6150 			break;
6151 		case ACCESS_VMWRITE:
6152 			c->flags = vmwrite_flags(c->field, 0);
6153 			break;
6154 		}
6155 		c->time = rdtsc() - start;
6156 		vmcall();
6157 	}
6158 }
6159 
6160 static u64 vmread_from_shadow(u64 field)
6161 {
6162 	struct vmcs *primary;
6163 	struct vmcs *shadow;
6164 	u64 value;
6165 
6166 	TEST_ASSERT(!vmcs_save(&primary));
6167 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6168 	TEST_ASSERT(!make_vmcs_current(shadow));
6169 	value = vmcs_read(field);
6170 	TEST_ASSERT(!make_vmcs_current(primary));
6171 	return value;
6172 }
6173 
6174 static u64 vmwrite_to_shadow(u64 field, u64 value)
6175 {
6176 	struct vmcs *primary;
6177 	struct vmcs *shadow;
6178 
6179 	TEST_ASSERT(!vmcs_save(&primary));
6180 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6181 	TEST_ASSERT(!make_vmcs_current(shadow));
6182 	vmcs_write(field, value);
6183 	value = vmcs_read(field);
6184 	TEST_ASSERT(!make_vmcs_current(primary));
6185 	return value;
6186 }
6187 
6188 static void vmcs_shadow_test_access(u8 *bitmap[2], enum vmcs_access access)
6189 {
6190 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6191 
6192 	c->op = access;
6193 	vmcs_write(VMX_INST_ERROR, 0);
6194 	enter_guest();
6195 	c->reason = vmcs_read(EXI_REASON) & 0xffff;
6196 	if (c->reason != VMX_VMCALL) {
6197 		skip_exit_insn();
6198 		enter_guest();
6199 	}
6200 	skip_exit_vmcall();
6201 }
6202 
6203 static void vmcs_shadow_test_field(u8 *bitmap[2], u64 field)
6204 {
6205 	struct vmcs_shadow_test_common *c = &l1_l2_common;
6206 	struct vmcs *shadow;
6207 	u64 value;
6208 	uintptr_t flags[2];
6209 	bool good_shadow;
6210 	u32 vmx_inst_error;
6211 
6212 	report_prefix_pushf("field %lx", field);
6213 	c->field = field;
6214 
6215 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
6216 	if (shadow != (struct vmcs *)-1ull) {
6217 		flags[ACCESS_VMREAD] = vmread_flags(field, &value);
6218 		flags[ACCESS_VMWRITE] = vmwrite_flags(field, value);
6219 		good_shadow = !flags[ACCESS_VMREAD] && !flags[ACCESS_VMWRITE];
6220 	} else {
6221 		/*
6222 		 * When VMCS link pointer is -1ull, VMWRITE/VMREAD on
6223 		 * shadowed-fields should fail with setting RFLAGS.CF.
6224 		 */
6225 		flags[ACCESS_VMREAD] = X86_EFLAGS_CF;
6226 		flags[ACCESS_VMWRITE] = X86_EFLAGS_CF;
6227 		good_shadow = false;
6228 	}
6229 
6230 	/* Intercept both VMREAD and VMWRITE. */
6231 	report_prefix_push("no VMREAD/VMWRITE permission");
6232 	/* VMWRITE/VMREAD done on reserved-bit should always intercept */
6233 	if (!(field >> VMCS_FIELD_RESERVED_SHIFT)) {
6234 		set_bit(field, bitmap[ACCESS_VMREAD]);
6235 		set_bit(field, bitmap[ACCESS_VMWRITE]);
6236 	}
6237 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6238 	report("not shadowed for VMWRITE", c->reason == VMX_VMWRITE);
6239 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6240 	report("not shadowed for VMREAD", c->reason == VMX_VMREAD);
6241 	report_prefix_pop();
6242 
6243 	if (field >> VMCS_FIELD_RESERVED_SHIFT)
6244 		goto out;
6245 
6246 	/* Permit shadowed VMREAD. */
6247 	report_prefix_push("VMREAD permission only");
6248 	clear_bit(field, bitmap[ACCESS_VMREAD]);
6249 	set_bit(field, bitmap[ACCESS_VMWRITE]);
6250 	if (good_shadow)
6251 		value = vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6252 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6253 	report("not shadowed for VMWRITE", c->reason == VMX_VMWRITE);
6254 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6255 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6256 	report("shadowed for VMREAD (in %ld cycles)", c->reason == VMX_VMCALL,
6257 	       c->time);
6258 	report("ALU flags after VMREAD (%lx) are as expected (%lx)",
6259 	       c->flags == flags[ACCESS_VMREAD],
6260 	       c->flags, flags[ACCESS_VMREAD]);
6261 	if (good_shadow)
6262 		report("value read from shadow (%lx) is as expected (%lx)",
6263 		       c->value == value, c->value, value);
6264 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
6265 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6266 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6267 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6268 	report_prefix_pop();
6269 
6270 	/* Permit shadowed VMWRITE. */
6271 	report_prefix_push("VMWRITE permission only");
6272 	set_bit(field, bitmap[ACCESS_VMREAD]);
6273 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
6274 	if (good_shadow)
6275 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6276 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6277 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6278 	report("shadowed for VMWRITE (in %ld cycles)", c->reason == VMX_VMCALL,
6279 		c->time);
6280 	report("ALU flags after VMWRITE (%lx) are as expected (%lx)",
6281 	       c->flags == flags[ACCESS_VMREAD],
6282 	       c->flags, flags[ACCESS_VMREAD]);
6283 	if (good_shadow) {
6284 		value = vmread_from_shadow(field);
6285 		report("shadow VMCS value (%lx) is as expected (%lx)",
6286 		       value == 0, value, 0ul);
6287 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
6288 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6289 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6290 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6291 	}
6292 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6293 	report("not shadowed for VMREAD", c->reason == VMX_VMREAD);
6294 	report_prefix_pop();
6295 
6296 	/* Permit shadowed VMREAD and VMWRITE. */
6297 	report_prefix_push("VMREAD and VMWRITE permission");
6298 	clear_bit(field, bitmap[ACCESS_VMREAD]);
6299 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
6300 	if (good_shadow)
6301 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
6302 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
6303 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6304 	report("shadowed for VMWRITE (in %ld cycles)", c->reason == VMX_VMCALL,
6305 		c->time);
6306 	report("ALU flags after VMWRITE (%lx) are as expected (%lx)",
6307 	       c->flags == flags[ACCESS_VMREAD],
6308 	       c->flags, flags[ACCESS_VMREAD]);
6309 	if (good_shadow) {
6310 		value = vmread_from_shadow(field);
6311 		report("shadow VMCS value (%lx) is as expected (%lx)",
6312 		       value == 0, value, 0ul);
6313 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
6314 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6315 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6316 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6317 	}
6318 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
6319 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
6320 	report("shadowed for VMREAD (in %ld cycles)", c->reason == VMX_VMCALL,
6321 	       c->time);
6322 	report("ALU flags after VMREAD (%lx) are as expected (%lx)",
6323 	       c->flags == flags[ACCESS_VMREAD],
6324 	       c->flags, flags[ACCESS_VMREAD]);
6325 	if (good_shadow)
6326 		report("value read from shadow (%lx) is as expected (%lx)",
6327 		       c->value == 0, c->value, 0ul);
6328 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
6329 		report("VMX_INST_ERROR (%d) is as expected (%d)",
6330 		       vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
6331 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
6332 	report_prefix_pop();
6333 
6334 out:
6335 	report_prefix_pop();
6336 }
6337 
6338 static void vmx_vmcs_shadow_test_body(u8 *bitmap[2])
6339 {
6340 	unsigned base;
6341 	unsigned index;
6342 	unsigned bit;
6343 	unsigned highest_index = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
6344 
6345 	/* Run test on all possible valid VMCS fields */
6346 	for (base = 0;
6347 	     base < (1 << VMCS_FIELD_RESERVED_SHIFT);
6348 	     base += (1 << VMCS_FIELD_TYPE_SHIFT))
6349 		for (index = 0; index <= highest_index; index++)
6350 			vmcs_shadow_test_field(bitmap, base + index);
6351 
6352 	/*
6353 	 * Run tests on some invalid VMCS fields
6354 	 * (Have reserved bit set).
6355 	 */
6356 	for (bit = VMCS_FIELD_RESERVED_SHIFT; bit < VMCS_FIELD_BIT_SIZE; bit++)
6357 		vmcs_shadow_test_field(bitmap, (1ull << bit));
6358 }
6359 
6360 static void vmx_vmcs_shadow_test(void)
6361 {
6362 	u8 *bitmap[2];
6363 	struct vmcs *shadow;
6364 
6365 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
6366 		printf("\t'Activate secondary controls' not supported.\n");
6367 		return;
6368 	}
6369 
6370 	if (!(ctrl_cpu_rev[1].clr & CPU_SHADOW_VMCS)) {
6371 		printf("\t'VMCS shadowing' not supported.\n");
6372 		return;
6373 	}
6374 
6375 	if (!(rdmsr(MSR_IA32_VMX_MISC) &
6376 	      MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) {
6377 		printf("\tVMWRITE can't modify VM-exit information fields.\n");
6378 		return;
6379 	}
6380 
6381 	test_set_guest(vmx_vmcs_shadow_test_guest);
6382 
6383 	bitmap[ACCESS_VMREAD] = alloc_page();
6384 	bitmap[ACCESS_VMWRITE] = alloc_page();
6385 
6386 	vmcs_write(VMREAD_BITMAP, virt_to_phys(bitmap[ACCESS_VMREAD]));
6387 	vmcs_write(VMWRITE_BITMAP, virt_to_phys(bitmap[ACCESS_VMWRITE]));
6388 
6389 	shadow = alloc_page();
6390 	shadow->hdr.revision_id = basic.revision;
6391 	shadow->hdr.shadow_vmcs = 1;
6392 	TEST_ASSERT(!vmcs_clear(shadow));
6393 
6394 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_RDTSC);
6395 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
6396 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_SHADOW_VMCS);
6397 
6398 	vmcs_write(VMCS_LINK_PTR, virt_to_phys(shadow));
6399 	report_prefix_push("valid link pointer");
6400 	vmx_vmcs_shadow_test_body(bitmap);
6401 	report_prefix_pop();
6402 
6403 	vmcs_write(VMCS_LINK_PTR, -1ull);
6404 	report_prefix_push("invalid link pointer");
6405 	vmx_vmcs_shadow_test_body(bitmap);
6406 	report_prefix_pop();
6407 
6408 	l1_l2_common.op = ACCESS_NONE;
6409 	enter_guest();
6410 }
6411 
6412 
6413 
6414 static int invalid_msr_init(struct vmcs *vmcs)
6415 {
6416 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
6417 		printf("\tPreemption timer is not supported\n");
6418 		return VMX_TEST_EXIT;
6419 	}
6420 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
6421 	preempt_val = 10000000;
6422 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
6423 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
6424 
6425 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
6426 		printf("\tSave preemption value is not supported\n");
6427 
6428 	vmcs_write(ENT_MSR_LD_CNT, 1);
6429 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)0x13370000);
6430 
6431 	return VMX_TEST_START;
6432 }
6433 
6434 
6435 static void invalid_msr_main(void)
6436 {
6437 	report("Invalid MSR load", 0);
6438 }
6439 
6440 static int invalid_msr_exit_handler(void)
6441 {
6442 	report("Invalid MSR load", 0);
6443 	print_vmexit_info();
6444 	return VMX_TEST_EXIT;
6445 }
6446 
6447 static int invalid_msr_entry_failure(struct vmentry_failure *failure)
6448 {
6449 	ulong reason;
6450 
6451 	reason = vmcs_read(EXI_REASON);
6452 	report("Invalid MSR load", reason == (0x80000000u | VMX_FAIL_MSR));
6453 	return VMX_TEST_VMEXIT;
6454 }
6455 
6456 
6457 #define TEST(name) { #name, .v2 = name }
6458 
6459 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
6460 struct vmx_test vmx_tests[] = {
6461 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
6462 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
6463 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
6464 		preemption_timer_exit_handler, NULL, {0} },
6465 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
6466 		test_ctrl_pat_exit_handler, NULL, {0} },
6467 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
6468 		test_ctrl_efer_exit_handler, NULL, {0} },
6469 	{ "CR shadowing", NULL, cr_shadowing_main,
6470 		cr_shadowing_exit_handler, NULL, {0} },
6471 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
6472 		NULL, {0} },
6473 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
6474 		insn_intercept_exit_handler, NULL, {0} },
6475 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
6476 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
6477 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
6478 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
6479 	{ "interrupt", interrupt_init, interrupt_main,
6480 		interrupt_exit_handler, NULL, {0} },
6481 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
6482 		NULL, {0} },
6483 	{ "MSR switch", msr_switch_init, msr_switch_main,
6484 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
6485 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
6486 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
6487 		disable_rdtscp_exit_handler, NULL, {0} },
6488 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
6489 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
6490 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
6491 		exit_monitor_from_l2_handler, NULL, {0} },
6492 	{ "invalid_msr", invalid_msr_init, invalid_msr_main,
6493 		invalid_msr_exit_handler, NULL, {0}, invalid_msr_entry_failure},
6494 	/* Basic V2 tests. */
6495 	TEST(v2_null_test),
6496 	TEST(v2_multiple_entries_test),
6497 	TEST(fixture_test_case1),
6498 	TEST(fixture_test_case2),
6499 	/* Opcode tests. */
6500 	TEST(invvpid_test_v2),
6501 	/* VM-entry tests */
6502 	TEST(vmx_controls_test),
6503 	TEST(vmentry_movss_shadow_test),
6504 	/* APICv tests */
6505 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
6506 	TEST(vmx_hlt_with_rvi_test),
6507 	/* APIC pass-through tests */
6508 	TEST(vmx_apic_passthrough_test),
6509 	TEST(vmx_apic_passthrough_thread_test),
6510 	/* VMCS Shadowing tests */
6511 	TEST(vmx_vmcs_shadow_test),
6512 	/* Regression tests */
6513 	TEST(vmx_cr_load_test),
6514 	TEST(vmx_nm_test),
6515 	TEST(vmx_db_test),
6516 	TEST(vmx_nmi_window_test),
6517 	TEST(vmx_intr_window_test),
6518 	TEST(vmx_pending_event_test),
6519 	TEST(vmx_pending_event_hlt_test),
6520 	TEST(vmx_store_tsc_test),
6521 	/* EPT access tests. */
6522 	TEST(ept_access_test_not_present),
6523 	TEST(ept_access_test_read_only),
6524 	TEST(ept_access_test_write_only),
6525 	TEST(ept_access_test_read_write),
6526 	TEST(ept_access_test_execute_only),
6527 	TEST(ept_access_test_read_execute),
6528 	TEST(ept_access_test_write_execute),
6529 	TEST(ept_access_test_read_write_execute),
6530 	TEST(ept_access_test_reserved_bits),
6531 	TEST(ept_access_test_ignored_bits),
6532 	TEST(ept_access_test_paddr_not_present_ad_disabled),
6533 	TEST(ept_access_test_paddr_not_present_ad_enabled),
6534 	TEST(ept_access_test_paddr_read_only_ad_disabled),
6535 	TEST(ept_access_test_paddr_read_only_ad_enabled),
6536 	TEST(ept_access_test_paddr_read_write),
6537 	TEST(ept_access_test_paddr_read_write_execute),
6538 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
6539 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
6540 	TEST(ept_access_test_paddr_not_present_page_fault),
6541 	TEST(ept_access_test_force_2m_page),
6542 	{ NULL, NULL, NULL, NULL, NULL, {0} },
6543 };
6544