xref: /kvm-unit-tests/x86/vmx_tests.c (revision 31efef0893d672e2788d0c83779caa4cd593a834)
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(1, "Basic VMX test");
59 }
60 
61 static int basic_exit_handler(union exit_reason exit_reason)
62 {
63 	report(0, "Basic VMX test");
64 	print_vmexit_info(exit_reason);
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(1, "test vmlaunch");
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((rax == 0xFFFF) && (rsp == resume_rsp), "test vmresume");
84 }
85 
86 static int vmenter_exit_handler(union exit_reason exit_reason)
87 {
88 	u64 guest_rip = vmcs_read(GUEST_RIP);
89 
90 	switch (exit_reason.basic) {
91 	case VMX_VMCALL:
92 		if (regs.rax != 0xABCD) {
93 			report(0, "test vmresume");
94 			return VMX_TEST_VMEXIT;
95 		}
96 		regs.rax = 0xFFFF;
97 		vmcs_write(GUEST_RIP, guest_rip + 3);
98 		return VMX_TEST_RESUME;
99 	default:
100 		report(0, "test vmresume");
101 		print_vmexit_info(exit_reason);
102 	}
103 	return VMX_TEST_VMEXIT;
104 }
105 
106 u32 preempt_scale;
107 volatile unsigned long long tsc_val;
108 volatile u32 preempt_val;
109 u64 saved_rip;
110 
111 static int preemption_timer_init(struct vmcs *vmcs)
112 {
113 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
114 		printf("\tPreemption timer is not supported\n");
115 		return VMX_TEST_EXIT;
116 	}
117 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
118 	preempt_val = 10000000;
119 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
120 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
121 
122 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
123 		printf("\tSave preemption value is not supported\n");
124 
125 	return VMX_TEST_START;
126 }
127 
128 static void preemption_timer_main(void)
129 {
130 	tsc_val = rdtsc();
131 	if (ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) {
132 		vmx_set_test_stage(0);
133 		vmcall();
134 		if (vmx_get_test_stage() == 1)
135 			vmcall();
136 	}
137 	vmx_set_test_stage(1);
138 	while (vmx_get_test_stage() == 1) {
139 		if (((rdtsc() - tsc_val) >> preempt_scale)
140 				> 10 * preempt_val) {
141 			vmx_set_test_stage(2);
142 			vmcall();
143 		}
144 	}
145 	tsc_val = rdtsc();
146 	asm volatile ("hlt");
147 	vmcall();
148 	vmx_set_test_stage(5);
149 	vmcall();
150 }
151 
152 static int preemption_timer_exit_handler(union exit_reason exit_reason)
153 {
154 	bool guest_halted;
155 	u64 guest_rip;
156 	u32 insn_len;
157 	u32 ctrl_exit;
158 
159 	guest_rip = vmcs_read(GUEST_RIP);
160 	insn_len = vmcs_read(EXI_INST_LEN);
161 	switch (exit_reason.basic) {
162 	case VMX_PREEMPT:
163 		switch (vmx_get_test_stage()) {
164 		case 1:
165 		case 2:
166 			report(((rdtsc() - tsc_val) >> preempt_scale) >= preempt_val,
167 			       "busy-wait for preemption timer");
168 			vmx_set_test_stage(3);
169 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
170 			return VMX_TEST_RESUME;
171 		case 3:
172 			guest_halted =
173 				(vmcs_read(GUEST_ACTV_STATE) == ACTV_HLT);
174 			report(((rdtsc() - tsc_val) >> preempt_scale) >= preempt_val
175 			        && guest_halted,
176 			       "preemption timer during hlt");
177 			vmx_set_test_stage(4);
178 			vmcs_write(PIN_CONTROLS,
179 				   vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
180 			vmcs_write(EXI_CONTROLS,
181 				   vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_PREEMPT);
182 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
183 			return VMX_TEST_RESUME;
184 		case 4:
185 			report(saved_rip == guest_rip,
186 			       "preemption timer with 0 value");
187 			break;
188 		default:
189 			report(false, "Invalid stage.");
190 			print_vmexit_info(exit_reason);
191 			break;
192 		}
193 		break;
194 	case VMX_VMCALL:
195 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
196 		switch (vmx_get_test_stage()) {
197 		case 0:
198 			report(vmcs_read(PREEMPT_TIMER_VALUE) == preempt_val,
199 			       "Keep preemption value");
200 			vmx_set_test_stage(1);
201 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
202 			ctrl_exit = (vmcs_read(EXI_CONTROLS) |
203 				EXI_SAVE_PREEMPT) & ctrl_exit_rev.clr;
204 			vmcs_write(EXI_CONTROLS, ctrl_exit);
205 			return VMX_TEST_RESUME;
206 		case 1:
207 			report(vmcs_read(PREEMPT_TIMER_VALUE) < preempt_val,
208 			       "Save preemption value");
209 			return VMX_TEST_RESUME;
210 		case 2:
211 			report(0, "busy-wait for preemption timer");
212 			vmx_set_test_stage(3);
213 			vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
214 			return VMX_TEST_RESUME;
215 		case 3:
216 			report(0, "preemption timer during hlt");
217 			vmx_set_test_stage(4);
218 			/* fall through */
219 		case 4:
220 			vmcs_write(PIN_CONTROLS,
221 				   vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
222 			vmcs_write(PREEMPT_TIMER_VALUE, 0);
223 			saved_rip = guest_rip + insn_len;
224 			return VMX_TEST_RESUME;
225 		case 5:
226 			report(0,
227 			       "preemption timer with 0 value (vmcall stage 5)");
228 			break;
229 		default:
230 			// Should not reach here
231 			report(false, "unexpected stage, %d",
232 			       vmx_get_test_stage());
233 			print_vmexit_info(exit_reason);
234 			return VMX_TEST_VMEXIT;
235 		}
236 		break;
237 	default:
238 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
239 		print_vmexit_info(exit_reason);
240 	}
241 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_PREEMPT);
242 	return VMX_TEST_VMEXIT;
243 }
244 
245 static void msr_bmp_init(void)
246 {
247 	void *msr_bitmap;
248 	u32 ctrl_cpu0;
249 
250 	msr_bitmap = alloc_page();
251 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
252 	ctrl_cpu0 |= CPU_MSR_BITMAP;
253 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
254 	vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
255 }
256 
257 static void *get_msr_bitmap(void)
258 {
259 	void *msr_bitmap;
260 
261 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_MSR_BITMAP) {
262 		msr_bitmap = (void *)vmcs_read(MSR_BITMAP);
263 	} else {
264 		msr_bitmap = alloc_page();
265 		memset(msr_bitmap, 0xff, PAGE_SIZE);
266 		vmcs_write(MSR_BITMAP, (u64)msr_bitmap);
267 		vmcs_set_bits(CPU_EXEC_CTRL0, CPU_MSR_BITMAP);
268 	}
269 
270 	return msr_bitmap;
271 }
272 
273 static void disable_intercept_for_x2apic_msrs(void)
274 {
275 	unsigned long *msr_bitmap = (unsigned long *)get_msr_bitmap();
276 	u32 msr;
277 
278 	for (msr = APIC_BASE_MSR;
279 		 msr < (APIC_BASE_MSR+0xff);
280 		 msr += BITS_PER_LONG) {
281 		unsigned int word = msr / BITS_PER_LONG;
282 
283 		msr_bitmap[word] = 0;
284 		msr_bitmap[word + (0x800 / sizeof(long))] = 0;
285 	}
286 }
287 
288 static int test_ctrl_pat_init(struct vmcs *vmcs)
289 {
290 	u64 ctrl_ent;
291 	u64 ctrl_exi;
292 
293 	msr_bmp_init();
294 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT) &&
295 	    !(ctrl_exit_rev.clr & EXI_LOAD_PAT) &&
296 	    !(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
297 		printf("\tSave/load PAT is not supported\n");
298 		return 1;
299 	}
300 
301 	ctrl_ent = vmcs_read(ENT_CONTROLS);
302 	ctrl_exi = vmcs_read(EXI_CONTROLS);
303 	ctrl_ent |= ctrl_enter_rev.clr & ENT_LOAD_PAT;
304 	ctrl_exi |= ctrl_exit_rev.clr & (EXI_SAVE_PAT | EXI_LOAD_PAT);
305 	vmcs_write(ENT_CONTROLS, ctrl_ent);
306 	vmcs_write(EXI_CONTROLS, ctrl_exi);
307 	ia32_pat = rdmsr(MSR_IA32_CR_PAT);
308 	vmcs_write(GUEST_PAT, 0x0);
309 	vmcs_write(HOST_PAT, ia32_pat);
310 	return VMX_TEST_START;
311 }
312 
313 static void test_ctrl_pat_main(void)
314 {
315 	u64 guest_ia32_pat;
316 
317 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
318 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT))
319 		printf("\tENT_LOAD_PAT is not supported.\n");
320 	else {
321 		if (guest_ia32_pat != 0) {
322 			report(0, "Entry load PAT");
323 			return;
324 		}
325 	}
326 	wrmsr(MSR_IA32_CR_PAT, 0x6);
327 	vmcall();
328 	guest_ia32_pat = rdmsr(MSR_IA32_CR_PAT);
329 	if (ctrl_enter_rev.clr & ENT_LOAD_PAT)
330 		report(guest_ia32_pat == ia32_pat, "Entry load PAT");
331 }
332 
333 static int test_ctrl_pat_exit_handler(union exit_reason exit_reason)
334 {
335 	u64 guest_rip;
336 	u64 guest_pat;
337 
338 	guest_rip = vmcs_read(GUEST_RIP);
339 	switch (exit_reason.basic) {
340 	case VMX_VMCALL:
341 		guest_pat = vmcs_read(GUEST_PAT);
342 		if (!(ctrl_exit_rev.clr & EXI_SAVE_PAT)) {
343 			printf("\tEXI_SAVE_PAT is not supported\n");
344 			vmcs_write(GUEST_PAT, 0x6);
345 		} else {
346 			report(guest_pat == 0x6, "Exit save PAT");
347 		}
348 		if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
349 			printf("\tEXI_LOAD_PAT is not supported\n");
350 		else
351 			report(rdmsr(MSR_IA32_CR_PAT) == ia32_pat,
352 			       "Exit load PAT");
353 		vmcs_write(GUEST_PAT, ia32_pat);
354 		vmcs_write(GUEST_RIP, guest_rip + 3);
355 		return VMX_TEST_RESUME;
356 	default:
357 		printf("ERROR : Unknown exit reason, 0x%x.\n", exit_reason.full);
358 		break;
359 	}
360 	return VMX_TEST_VMEXIT;
361 }
362 
363 static int test_ctrl_efer_init(struct vmcs *vmcs)
364 {
365 	u64 ctrl_ent;
366 	u64 ctrl_exi;
367 
368 	msr_bmp_init();
369 	ctrl_ent = vmcs_read(ENT_CONTROLS) | ENT_LOAD_EFER;
370 	ctrl_exi = vmcs_read(EXI_CONTROLS) | EXI_SAVE_EFER | EXI_LOAD_EFER;
371 	vmcs_write(ENT_CONTROLS, ctrl_ent & ctrl_enter_rev.clr);
372 	vmcs_write(EXI_CONTROLS, ctrl_exi & ctrl_exit_rev.clr);
373 	ia32_efer = rdmsr(MSR_EFER);
374 	vmcs_write(GUEST_EFER, ia32_efer ^ EFER_NX);
375 	vmcs_write(HOST_EFER, ia32_efer ^ EFER_NX);
376 	return VMX_TEST_START;
377 }
378 
379 static void test_ctrl_efer_main(void)
380 {
381 	u64 guest_ia32_efer;
382 
383 	guest_ia32_efer = rdmsr(MSR_EFER);
384 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER))
385 		printf("\tENT_LOAD_EFER is not supported.\n");
386 	else {
387 		if (guest_ia32_efer != (ia32_efer ^ EFER_NX)) {
388 			report(0, "Entry load EFER");
389 			return;
390 		}
391 	}
392 	wrmsr(MSR_EFER, ia32_efer);
393 	vmcall();
394 	guest_ia32_efer = rdmsr(MSR_EFER);
395 	if (ctrl_enter_rev.clr & ENT_LOAD_EFER)
396 		report(guest_ia32_efer == ia32_efer, "Entry load EFER");
397 }
398 
399 static int test_ctrl_efer_exit_handler(union exit_reason exit_reason)
400 {
401 	u64 guest_rip;
402 	u64 guest_efer;
403 
404 	guest_rip = vmcs_read(GUEST_RIP);
405 	switch (exit_reason.basic) {
406 	case VMX_VMCALL:
407 		guest_efer = vmcs_read(GUEST_EFER);
408 		if (!(ctrl_exit_rev.clr & EXI_SAVE_EFER)) {
409 			printf("\tEXI_SAVE_EFER is not supported\n");
410 			vmcs_write(GUEST_EFER, ia32_efer);
411 		} else {
412 			report(guest_efer == ia32_efer, "Exit save EFER");
413 		}
414 		if (!(ctrl_exit_rev.clr & EXI_LOAD_EFER)) {
415 			printf("\tEXI_LOAD_EFER is not supported\n");
416 			wrmsr(MSR_EFER, ia32_efer ^ EFER_NX);
417 		} else {
418 			report(rdmsr(MSR_EFER) == (ia32_efer ^ EFER_NX),
419 			       "Exit load EFER");
420 		}
421 		vmcs_write(GUEST_PAT, ia32_efer);
422 		vmcs_write(GUEST_RIP, guest_rip + 3);
423 		return VMX_TEST_RESUME;
424 	default:
425 		printf("ERROR : Unknown exit reason, 0x%x.\n", exit_reason.full);
426 		break;
427 	}
428 	return VMX_TEST_VMEXIT;
429 }
430 
431 u32 guest_cr0, guest_cr4;
432 
433 static void cr_shadowing_main(void)
434 {
435 	u32 cr0, cr4, tmp;
436 
437 	// Test read through
438 	vmx_set_test_stage(0);
439 	guest_cr0 = read_cr0();
440 	if (vmx_get_test_stage() == 1)
441 		report(0, "Read through CR0");
442 	else
443 		vmcall();
444 	vmx_set_test_stage(1);
445 	guest_cr4 = read_cr4();
446 	if (vmx_get_test_stage() == 2)
447 		report(0, "Read through CR4");
448 	else
449 		vmcall();
450 	// Test write through
451 	guest_cr0 = guest_cr0 ^ (X86_CR0_TS | X86_CR0_MP);
452 	guest_cr4 = guest_cr4 ^ (X86_CR4_TSD | X86_CR4_DE);
453 	vmx_set_test_stage(2);
454 	write_cr0(guest_cr0);
455 	if (vmx_get_test_stage() == 3)
456 		report(0, "Write throuth CR0");
457 	else
458 		vmcall();
459 	vmx_set_test_stage(3);
460 	write_cr4(guest_cr4);
461 	if (vmx_get_test_stage() == 4)
462 		report(0, "Write through CR4");
463 	else
464 		vmcall();
465 	// Test read shadow
466 	vmx_set_test_stage(4);
467 	vmcall();
468 	cr0 = read_cr0();
469 	if (vmx_get_test_stage() != 5)
470 		report(cr0 == guest_cr0, "Read shadowing CR0");
471 	vmx_set_test_stage(5);
472 	cr4 = read_cr4();
473 	if (vmx_get_test_stage() != 6)
474 		report(cr4 == guest_cr4, "Read shadowing CR4");
475 	// Test write shadow (same value with shadow)
476 	vmx_set_test_stage(6);
477 	write_cr0(guest_cr0);
478 	if (vmx_get_test_stage() == 7)
479 		report(0, "Write shadowing CR0 (same value with shadow)");
480 	else
481 		vmcall();
482 	vmx_set_test_stage(7);
483 	write_cr4(guest_cr4);
484 	if (vmx_get_test_stage() == 8)
485 		report(0, "Write shadowing CR4 (same value with shadow)");
486 	else
487 		vmcall();
488 	// Test write shadow (different value)
489 	vmx_set_test_stage(8);
490 	tmp = guest_cr0 ^ X86_CR0_TS;
491 	asm volatile("mov %0, %%rsi\n\t"
492 		"mov %%rsi, %%cr0\n\t"
493 		::"m"(tmp)
494 		:"rsi", "memory", "cc");
495 	report(vmx_get_test_stage() == 9,
496 	       "Write shadowing different X86_CR0_TS");
497 	vmx_set_test_stage(9);
498 	tmp = guest_cr0 ^ X86_CR0_MP;
499 	asm volatile("mov %0, %%rsi\n\t"
500 		"mov %%rsi, %%cr0\n\t"
501 		::"m"(tmp)
502 		:"rsi", "memory", "cc");
503 	report(vmx_get_test_stage() == 10,
504 	       "Write shadowing different X86_CR0_MP");
505 	vmx_set_test_stage(10);
506 	tmp = guest_cr4 ^ X86_CR4_TSD;
507 	asm volatile("mov %0, %%rsi\n\t"
508 		"mov %%rsi, %%cr4\n\t"
509 		::"m"(tmp)
510 		:"rsi", "memory", "cc");
511 	report(vmx_get_test_stage() == 11,
512 	       "Write shadowing different X86_CR4_TSD");
513 	vmx_set_test_stage(11);
514 	tmp = guest_cr4 ^ X86_CR4_DE;
515 	asm volatile("mov %0, %%rsi\n\t"
516 		"mov %%rsi, %%cr4\n\t"
517 		::"m"(tmp)
518 		:"rsi", "memory", "cc");
519 	report(vmx_get_test_stage() == 12,
520 	       "Write shadowing different X86_CR4_DE");
521 }
522 
523 static int cr_shadowing_exit_handler(union exit_reason exit_reason)
524 {
525 	u64 guest_rip;
526 	u32 insn_len;
527 	u32 exit_qual;
528 
529 	guest_rip = vmcs_read(GUEST_RIP);
530 	insn_len = vmcs_read(EXI_INST_LEN);
531 	exit_qual = vmcs_read(EXI_QUALIFICATION);
532 	switch (exit_reason.basic) {
533 	case VMX_VMCALL:
534 		switch (vmx_get_test_stage()) {
535 		case 0:
536 			report(guest_cr0 == vmcs_read(GUEST_CR0),
537 			       "Read through CR0");
538 			break;
539 		case 1:
540 			report(guest_cr4 == vmcs_read(GUEST_CR4),
541 			       "Read through CR4");
542 			break;
543 		case 2:
544 			report(guest_cr0 == vmcs_read(GUEST_CR0),
545 			       "Write through CR0");
546 			break;
547 		case 3:
548 			report(guest_cr4 == vmcs_read(GUEST_CR4),
549 			       "Write through CR4");
550 			break;
551 		case 4:
552 			guest_cr0 = vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP);
553 			guest_cr4 = vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE);
554 			vmcs_write(CR0_MASK, X86_CR0_TS | X86_CR0_MP);
555 			vmcs_write(CR0_READ_SHADOW, guest_cr0 & (X86_CR0_TS | X86_CR0_MP));
556 			vmcs_write(CR4_MASK, X86_CR4_TSD | X86_CR4_DE);
557 			vmcs_write(CR4_READ_SHADOW, guest_cr4 & (X86_CR4_TSD | X86_CR4_DE));
558 			break;
559 		case 6:
560 			report(guest_cr0 == (vmcs_read(GUEST_CR0) ^ (X86_CR0_TS | X86_CR0_MP)),
561 			       "Write shadowing CR0 (same value)");
562 			break;
563 		case 7:
564 			report(guest_cr4 == (vmcs_read(GUEST_CR4) ^ (X86_CR4_TSD | X86_CR4_DE)),
565 			       "Write shadowing CR4 (same value)");
566 			break;
567 		default:
568 			// Should not reach here
569 			report(false, "unexpected stage, %d",
570 			       vmx_get_test_stage());
571 			print_vmexit_info(exit_reason);
572 			return VMX_TEST_VMEXIT;
573 		}
574 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
575 		return VMX_TEST_RESUME;
576 	case VMX_CR:
577 		switch (vmx_get_test_stage()) {
578 		case 4:
579 			report(0, "Read shadowing CR0");
580 			vmx_inc_test_stage();
581 			break;
582 		case 5:
583 			report(0, "Read shadowing CR4");
584 			vmx_inc_test_stage();
585 			break;
586 		case 6:
587 			report(0, "Write shadowing CR0 (same value)");
588 			vmx_inc_test_stage();
589 			break;
590 		case 7:
591 			report(0, "Write shadowing CR4 (same value)");
592 			vmx_inc_test_stage();
593 			break;
594 		case 8:
595 		case 9:
596 			// 0x600 encodes "mov %esi, %cr0"
597 			if (exit_qual == 0x600)
598 				vmx_inc_test_stage();
599 			break;
600 		case 10:
601 		case 11:
602 			// 0x604 encodes "mov %esi, %cr4"
603 			if (exit_qual == 0x604)
604 				vmx_inc_test_stage();
605 			break;
606 		default:
607 			// Should not reach here
608 			report(false, "unexpected stage, %d",
609 			       vmx_get_test_stage());
610 			print_vmexit_info(exit_reason);
611 			return VMX_TEST_VMEXIT;
612 		}
613 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
614 		return VMX_TEST_RESUME;
615 	default:
616 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
617 		print_vmexit_info(exit_reason);
618 	}
619 	return VMX_TEST_VMEXIT;
620 }
621 
622 static int iobmp_init(struct vmcs *vmcs)
623 {
624 	u32 ctrl_cpu0;
625 
626 	io_bitmap_a = alloc_page();
627 	io_bitmap_b = alloc_page();
628 	ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
629 	ctrl_cpu0 |= CPU_IO_BITMAP;
630 	ctrl_cpu0 &= (~CPU_IO);
631 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
632 	vmcs_write(IO_BITMAP_A, (u64)io_bitmap_a);
633 	vmcs_write(IO_BITMAP_B, (u64)io_bitmap_b);
634 	return VMX_TEST_START;
635 }
636 
637 static void iobmp_main(void)
638 {
639 	// stage 0, test IO pass
640 	vmx_set_test_stage(0);
641 	inb(0x5000);
642 	outb(0x0, 0x5000);
643 	report(vmx_get_test_stage() == 0, "I/O bitmap - I/O pass");
644 	// test IO width, in/out
645 	((u8 *)io_bitmap_a)[0] = 0xFF;
646 	vmx_set_test_stage(2);
647 	inb(0x0);
648 	report(vmx_get_test_stage() == 3, "I/O bitmap - trap in");
649 	vmx_set_test_stage(3);
650 	outw(0x0, 0x0);
651 	report(vmx_get_test_stage() == 4, "I/O bitmap - trap out");
652 	vmx_set_test_stage(4);
653 	inl(0x0);
654 	report(vmx_get_test_stage() == 5, "I/O bitmap - I/O width, long");
655 	// test low/high IO port
656 	vmx_set_test_stage(5);
657 	((u8 *)io_bitmap_a)[0x5000 / 8] = (1 << (0x5000 % 8));
658 	inb(0x5000);
659 	report(vmx_get_test_stage() == 6, "I/O bitmap - I/O port, low part");
660 	vmx_set_test_stage(6);
661 	((u8 *)io_bitmap_b)[0x1000 / 8] = (1 << (0x1000 % 8));
662 	inb(0x9000);
663 	report(vmx_get_test_stage() == 7, "I/O bitmap - I/O port, high part");
664 	// test partial pass
665 	vmx_set_test_stage(7);
666 	inl(0x4FFF);
667 	report(vmx_get_test_stage() == 8, "I/O bitmap - partial pass");
668 	// test overrun
669 	vmx_set_test_stage(8);
670 	memset(io_bitmap_a, 0x0, PAGE_SIZE);
671 	memset(io_bitmap_b, 0x0, PAGE_SIZE);
672 	inl(0xFFFF);
673 	report(vmx_get_test_stage() == 9, "I/O bitmap - overrun");
674 	vmx_set_test_stage(9);
675 	vmcall();
676 	outb(0x0, 0x0);
677 	report(vmx_get_test_stage() == 9,
678 	       "I/O bitmap - ignore unconditional exiting");
679 	vmx_set_test_stage(10);
680 	vmcall();
681 	outb(0x0, 0x0);
682 	report(vmx_get_test_stage() == 11,
683 	       "I/O bitmap - unconditional exiting");
684 }
685 
686 static int iobmp_exit_handler(union exit_reason exit_reason)
687 {
688 	u64 guest_rip;
689 	ulong exit_qual;
690 	u32 insn_len, ctrl_cpu0;
691 
692 	guest_rip = vmcs_read(GUEST_RIP);
693 	exit_qual = vmcs_read(EXI_QUALIFICATION);
694 	insn_len = vmcs_read(EXI_INST_LEN);
695 	switch (exit_reason.basic) {
696 	case VMX_IO:
697 		switch (vmx_get_test_stage()) {
698 		case 0:
699 		case 1:
700 			vmx_inc_test_stage();
701 			break;
702 		case 2:
703 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_BYTE,
704 			       "I/O bitmap - I/O width, byte");
705 			report(exit_qual & VMX_IO_IN,
706 			       "I/O bitmap - I/O direction, in");
707 			vmx_inc_test_stage();
708 			break;
709 		case 3:
710 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_WORD,
711 			       "I/O bitmap - I/O width, word");
712 			report(!(exit_qual & VMX_IO_IN),
713 			       "I/O bitmap - I/O direction, out");
714 			vmx_inc_test_stage();
715 			break;
716 		case 4:
717 			report((exit_qual & VMX_IO_SIZE_MASK) == _VMX_IO_LONG,
718 			       "I/O bitmap - I/O width, long");
719 			vmx_inc_test_stage();
720 			break;
721 		case 5:
722 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x5000)
723 				vmx_inc_test_stage();
724 			break;
725 		case 6:
726 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x9000)
727 				vmx_inc_test_stage();
728 			break;
729 		case 7:
730 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0x4FFF)
731 				vmx_inc_test_stage();
732 			break;
733 		case 8:
734 			if (((exit_qual & VMX_IO_PORT_MASK) >> VMX_IO_PORT_SHIFT) == 0xFFFF)
735 				vmx_inc_test_stage();
736 			break;
737 		case 9:
738 		case 10:
739 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
740 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0 & ~CPU_IO);
741 			vmx_inc_test_stage();
742 			break;
743 		default:
744 			// Should not reach here
745 			report(false, "unexpected stage, %d",
746 			       vmx_get_test_stage());
747 			print_vmexit_info(exit_reason);
748 			return VMX_TEST_VMEXIT;
749 		}
750 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
751 		return VMX_TEST_RESUME;
752 	case VMX_VMCALL:
753 		switch (vmx_get_test_stage()) {
754 		case 9:
755 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
756 			ctrl_cpu0 |= CPU_IO | CPU_IO_BITMAP;
757 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
758 			break;
759 		case 10:
760 			ctrl_cpu0 = vmcs_read(CPU_EXEC_CTRL0);
761 			ctrl_cpu0 = (ctrl_cpu0 & ~CPU_IO_BITMAP) | CPU_IO;
762 			vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu0);
763 			break;
764 		default:
765 			// Should not reach here
766 			report(false, "unexpected stage, %d",
767 			       vmx_get_test_stage());
768 			print_vmexit_info(exit_reason);
769 			return VMX_TEST_VMEXIT;
770 		}
771 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
772 		return VMX_TEST_RESUME;
773 	default:
774 		printf("guest_rip = %#lx\n", guest_rip);
775 		printf("\tERROR : Unknown exit reason, 0x%x\n", exit_reason.full);
776 		break;
777 	}
778 	return VMX_TEST_VMEXIT;
779 }
780 
781 #define INSN_CPU0		0
782 #define INSN_CPU1		1
783 #define INSN_ALWAYS_TRAP	2
784 
785 #define FIELD_EXIT_QUAL		(1 << 0)
786 #define FIELD_INSN_INFO		(1 << 1)
787 
788 asm(
789 	"insn_hlt: hlt;ret\n\t"
790 	"insn_invlpg: invlpg 0x12345678;ret\n\t"
791 	"insn_mwait: xor %eax, %eax; xor %ecx, %ecx; mwait;ret\n\t"
792 	"insn_rdpmc: xor %ecx, %ecx; rdpmc;ret\n\t"
793 	"insn_rdtsc: rdtsc;ret\n\t"
794 	"insn_cr3_load: mov cr3,%rax; mov %rax,%cr3;ret\n\t"
795 	"insn_cr3_store: mov %cr3,%rax;ret\n\t"
796 	"insn_cr8_load: xor %eax, %eax; mov %rax,%cr8;ret\n\t"
797 	"insn_cr8_store: mov %cr8,%rax;ret\n\t"
798 	"insn_monitor: xor %eax, %eax; xor %ecx, %ecx; xor %edx, %edx; monitor;ret\n\t"
799 	"insn_pause: pause;ret\n\t"
800 	"insn_wbinvd: wbinvd;ret\n\t"
801 	"insn_cpuid: mov $10, %eax; cpuid;ret\n\t"
802 	"insn_invd: invd;ret\n\t"
803 	"insn_sgdt: sgdt gdt64_desc;ret\n\t"
804 	"insn_lgdt: lgdt gdt64_desc;ret\n\t"
805 	"insn_sidt: sidt idt_descr;ret\n\t"
806 	"insn_lidt: lidt idt_descr;ret\n\t"
807 	"insn_sldt: sldt %ax;ret\n\t"
808 	"insn_lldt: xor %eax, %eax; lldt %ax;ret\n\t"
809 	"insn_str: str %ax;ret\n\t"
810 	"insn_rdrand: rdrand %rax;ret\n\t"
811 	"insn_rdseed: rdseed %rax;ret\n\t"
812 );
813 extern void insn_hlt(void);
814 extern void insn_invlpg(void);
815 extern void insn_mwait(void);
816 extern void insn_rdpmc(void);
817 extern void insn_rdtsc(void);
818 extern void insn_cr3_load(void);
819 extern void insn_cr3_store(void);
820 extern void insn_cr8_load(void);
821 extern void insn_cr8_store(void);
822 extern void insn_monitor(void);
823 extern void insn_pause(void);
824 extern void insn_wbinvd(void);
825 extern void insn_sgdt(void);
826 extern void insn_lgdt(void);
827 extern void insn_sidt(void);
828 extern void insn_lidt(void);
829 extern void insn_sldt(void);
830 extern void insn_lldt(void);
831 extern void insn_str(void);
832 extern void insn_cpuid(void);
833 extern void insn_invd(void);
834 extern void insn_rdrand(void);
835 extern void insn_rdseed(void);
836 
837 u32 cur_insn;
838 u64 cr3;
839 
840 #define X86_FEATURE_MONITOR	(1 << 3)
841 
842 typedef bool (*supported_fn)(void);
843 
844 static bool monitor_supported(void)
845 {
846 	return this_cpu_has(X86_FEATURE_MWAIT);
847 }
848 
849 struct insn_table {
850 	const char *name;
851 	u32 flag;
852 	void (*insn_func)(void);
853 	u32 type;
854 	u32 reason;
855 	ulong exit_qual;
856 	u32 insn_info;
857 	// Use FIELD_EXIT_QUAL and FIELD_INSN_INFO to define
858 	// which field need to be tested, reason is always tested
859 	u32 test_field;
860 	const supported_fn supported_fn;
861 	u8 disabled;
862 };
863 
864 /*
865  * Add more test cases of instruction intercept here. Elements in this
866  * table is:
867  *	name/control flag/insn function/type/exit reason/exit qulification/
868  *	instruction info/field to test
869  * The last field defines which fields (exit_qual and insn_info) need to be
870  * tested in exit handler. If set to 0, only "reason" is checked.
871  */
872 static struct insn_table insn_table[] = {
873 	// Flags for Primary Processor-Based VM-Execution Controls
874 	{"HLT",  CPU_HLT, insn_hlt, INSN_CPU0, 12, 0, 0, 0},
875 	{"INVLPG", CPU_INVLPG, insn_invlpg, INSN_CPU0, 14,
876 		0x12345678, 0, FIELD_EXIT_QUAL},
877 	{"MWAIT", CPU_MWAIT, insn_mwait, INSN_CPU0, 36, 0, 0, 0, &monitor_supported},
878 	{"RDPMC", CPU_RDPMC, insn_rdpmc, INSN_CPU0, 15, 0, 0, 0},
879 	{"RDTSC", CPU_RDTSC, insn_rdtsc, INSN_CPU0, 16, 0, 0, 0},
880 	{"CR3 load", CPU_CR3_LOAD, insn_cr3_load, INSN_CPU0, 28, 0x3, 0,
881 		FIELD_EXIT_QUAL},
882 	{"CR3 store", CPU_CR3_STORE, insn_cr3_store, INSN_CPU0, 28, 0x13, 0,
883 		FIELD_EXIT_QUAL},
884 	{"CR8 load", CPU_CR8_LOAD, insn_cr8_load, INSN_CPU0, 28, 0x8, 0,
885 		FIELD_EXIT_QUAL},
886 	{"CR8 store", CPU_CR8_STORE, insn_cr8_store, INSN_CPU0, 28, 0x18, 0,
887 		FIELD_EXIT_QUAL},
888 	{"MONITOR", CPU_MONITOR, insn_monitor, INSN_CPU0, 39, 0, 0, 0, &monitor_supported},
889 	{"PAUSE", CPU_PAUSE, insn_pause, INSN_CPU0, 40, 0, 0, 0},
890 	// Flags for Secondary Processor-Based VM-Execution Controls
891 	{"WBINVD", CPU_WBINVD, insn_wbinvd, INSN_CPU1, 54, 0, 0, 0},
892 	{"DESC_TABLE (SGDT)", CPU_DESC_TABLE, insn_sgdt, INSN_CPU1, 46, 0, 0, 0},
893 	{"DESC_TABLE (LGDT)", CPU_DESC_TABLE, insn_lgdt, INSN_CPU1, 46, 0, 0, 0},
894 	{"DESC_TABLE (SIDT)", CPU_DESC_TABLE, insn_sidt, INSN_CPU1, 46, 0, 0, 0},
895 	{"DESC_TABLE (LIDT)", CPU_DESC_TABLE, insn_lidt, INSN_CPU1, 46, 0, 0, 0},
896 	{"DESC_TABLE (SLDT)", CPU_DESC_TABLE, insn_sldt, INSN_CPU1, 47, 0, 0, 0},
897 	{"DESC_TABLE (LLDT)", CPU_DESC_TABLE, insn_lldt, INSN_CPU1, 47, 0, 0, 0},
898 	{"DESC_TABLE (STR)", CPU_DESC_TABLE, insn_str, INSN_CPU1, 47, 0, 0, 0},
899 	/* LTR causes a #GP if done with a busy selector, so it is not tested.  */
900 	{"RDRAND", CPU_RDRAND, insn_rdrand, INSN_CPU1, VMX_RDRAND, 0, 0, 0},
901 	{"RDSEED", CPU_RDSEED, insn_rdseed, INSN_CPU1, VMX_RDSEED, 0, 0, 0},
902 	// Instructions always trap
903 	{"CPUID", 0, insn_cpuid, INSN_ALWAYS_TRAP, 10, 0, 0, 0},
904 	{"INVD", 0, insn_invd, INSN_ALWAYS_TRAP, 13, 0, 0, 0},
905 	// Instructions never trap
906 	{NULL},
907 };
908 
909 static int insn_intercept_init(struct vmcs *vmcs)
910 {
911 	u32 ctrl_cpu, cur_insn;
912 
913 	ctrl_cpu = ctrl_cpu_rev[0].set | CPU_SECONDARY;
914 	ctrl_cpu &= ctrl_cpu_rev[0].clr;
915 	vmcs_write(CPU_EXEC_CTRL0, ctrl_cpu);
916 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu_rev[1].set);
917 	cr3 = read_cr3();
918 
919 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
920 		if (insn_table[cur_insn].supported_fn == NULL)
921 			continue;
922 		insn_table[cur_insn].disabled = !insn_table[cur_insn].supported_fn();
923 	}
924 	return VMX_TEST_START;
925 }
926 
927 static void insn_intercept_main(void)
928 {
929 	for (cur_insn = 0; insn_table[cur_insn].name != NULL; cur_insn++) {
930 		vmx_set_test_stage(cur_insn * 2);
931 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
932 		     !(ctrl_cpu_rev[0].clr & insn_table[cur_insn].flag)) ||
933 		    (insn_table[cur_insn].type == INSN_CPU1 &&
934 		     !(ctrl_cpu_rev[1].clr & insn_table[cur_insn].flag))) {
935 			printf("\tCPU_CTRL%d.CPU_%s is not supported.\n",
936 			       insn_table[cur_insn].type - INSN_CPU0,
937 			       insn_table[cur_insn].name);
938 			continue;
939 		}
940 
941 		if (insn_table[cur_insn].disabled) {
942 			printf("\tFeature required for %s is not supported.\n",
943 			       insn_table[cur_insn].name);
944 			continue;
945 		}
946 
947 		if ((insn_table[cur_insn].type == INSN_CPU0 &&
948 		     !(ctrl_cpu_rev[0].set & insn_table[cur_insn].flag)) ||
949 		    (insn_table[cur_insn].type == INSN_CPU1 &&
950 		     !(ctrl_cpu_rev[1].set & insn_table[cur_insn].flag))) {
951 			/* skip hlt, it stalls the guest and is tested below */
952 			if (insn_table[cur_insn].insn_func != insn_hlt)
953 				insn_table[cur_insn].insn_func();
954 			report(vmx_get_test_stage() == cur_insn * 2,
955 					"execute %s",
956 					insn_table[cur_insn].name);
957 		} else if (insn_table[cur_insn].type != INSN_ALWAYS_TRAP)
958 			printf("\tCPU_CTRL%d.CPU_%s always traps.\n",
959 			       insn_table[cur_insn].type - INSN_CPU0,
960 			       insn_table[cur_insn].name);
961 
962 		vmcall();
963 
964 		insn_table[cur_insn].insn_func();
965 		report(vmx_get_test_stage() == cur_insn * 2 + 1,
966 				"intercept %s",
967 				insn_table[cur_insn].name);
968 
969 		vmx_set_test_stage(cur_insn * 2 + 1);
970 		vmcall();
971 	}
972 }
973 
974 static int insn_intercept_exit_handler(union exit_reason exit_reason)
975 {
976 	u64 guest_rip;
977 	ulong exit_qual;
978 	u32 insn_len;
979 	u32 insn_info;
980 	bool pass;
981 
982 	guest_rip = vmcs_read(GUEST_RIP);
983 	exit_qual = vmcs_read(EXI_QUALIFICATION);
984 	insn_len = vmcs_read(EXI_INST_LEN);
985 	insn_info = vmcs_read(EXI_INST_INFO);
986 
987 	if (exit_reason.basic == VMX_VMCALL) {
988 		u32 val = 0;
989 
990 		if (insn_table[cur_insn].type == INSN_CPU0)
991 			val = vmcs_read(CPU_EXEC_CTRL0);
992 		else if (insn_table[cur_insn].type == INSN_CPU1)
993 			val = vmcs_read(CPU_EXEC_CTRL1);
994 
995 		if (vmx_get_test_stage() & 1)
996 			val &= ~insn_table[cur_insn].flag;
997 		else
998 			val |= insn_table[cur_insn].flag;
999 
1000 		if (insn_table[cur_insn].type == INSN_CPU0)
1001 			vmcs_write(CPU_EXEC_CTRL0, val | ctrl_cpu_rev[0].set);
1002 		else if (insn_table[cur_insn].type == INSN_CPU1)
1003 			vmcs_write(CPU_EXEC_CTRL1, val | ctrl_cpu_rev[1].set);
1004 	} else {
1005 		pass = (cur_insn * 2 == vmx_get_test_stage()) &&
1006 			insn_table[cur_insn].reason == exit_reason.full;
1007 		if (insn_table[cur_insn].test_field & FIELD_EXIT_QUAL &&
1008 		    insn_table[cur_insn].exit_qual != exit_qual)
1009 			pass = false;
1010 		if (insn_table[cur_insn].test_field & FIELD_INSN_INFO &&
1011 		    insn_table[cur_insn].insn_info != insn_info)
1012 			pass = false;
1013 		if (pass)
1014 			vmx_inc_test_stage();
1015 	}
1016 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
1017 	return VMX_TEST_RESUME;
1018 }
1019 
1020 /**
1021  * __setup_ept - Setup the VMCS fields to enable Extended Page Tables (EPT)
1022  * @hpa:	Host physical address of the top-level, a.k.a. root, EPT table
1023  * @enable_ad:	Whether or not to enable Access/Dirty bits for EPT entries
1024  *
1025  * Returns 0 on success, 1 on failure.
1026  *
1027  * Note that @hpa doesn't need to point at actual memory if VM-Launch is
1028  * expected to fail, e.g. setup_dummy_ept() arbitrarily passes '0' to satisfy
1029  * the various EPTP consistency checks, but doesn't ensure backing for HPA '0'.
1030  */
1031 static int __setup_ept(u64 hpa, bool enable_ad)
1032 {
1033 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1034 	    !(ctrl_cpu_rev[1].clr & CPU_EPT)) {
1035 		printf("\tEPT is not supported");
1036 		return 1;
1037 	}
1038 	if (!(ept_vpid.val & EPT_CAP_WB)) {
1039 		printf("WB memtype for EPT walks not supported\n");
1040 		return 1;
1041 	}
1042 	if (!(ept_vpid.val & EPT_CAP_PWL4)) {
1043 		printf("\tPWL4 is not supported\n");
1044 		return 1;
1045 	}
1046 
1047 	eptp = EPT_MEM_TYPE_WB;
1048 	eptp |= (3 << EPTP_PG_WALK_LEN_SHIFT);
1049 	eptp |= hpa;
1050 	if (enable_ad)
1051 		eptp |= EPTP_AD_FLAG;
1052 
1053 	vmcs_write(EPTP, eptp);
1054 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0)| CPU_SECONDARY);
1055 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1)| CPU_EPT);
1056 
1057 	return 0;
1058 }
1059 
1060 /**
1061  * setup_ept - Enable Extended Page Tables (EPT) and setup an identity map
1062  * @enable_ad:	Whether or not to enable Access/Dirty bits for EPT entries
1063  *
1064  * Returns 0 on success, 1 on failure.
1065  *
1066  * This is the "real" function for setting up EPT tables, i.e. use this for
1067  * tests that need to run code in the guest with EPT enabled.
1068  */
1069 static int setup_ept(bool enable_ad)
1070 {
1071 	unsigned long end_of_memory;
1072 
1073 	pml4 = alloc_page();
1074 
1075 	if (__setup_ept(virt_to_phys(pml4), enable_ad))
1076 		return 1;
1077 
1078 	end_of_memory = fwcfg_get_u64(FW_CFG_RAM_SIZE);
1079 	if (end_of_memory < (1ul << 32))
1080 		end_of_memory = (1ul << 32);
1081 	/* Cannot use large EPT pages if we need to track EPT
1082 	 * accessed/dirty bits at 4K granularity.
1083 	 */
1084 	setup_ept_range(pml4, 0, end_of_memory, 0,
1085 			!enable_ad && ept_2m_supported(),
1086 			EPT_WA | EPT_RA | EPT_EA);
1087 	return 0;
1088 }
1089 
1090 /**
1091  * setup_dummy_ept - Enable Extended Page Tables (EPT) with a dummy root HPA
1092  *
1093  * Setup EPT using a semi-arbitrary dummy root HPA.  This function is intended
1094  * for use by tests that need EPT enabled to verify dependent VMCS controls
1095  * but never expect to fully enter the guest, i.e. don't need setup the actual
1096  * EPT tables.
1097  */
1098 static void setup_dummy_ept(void)
1099 {
1100 	if (__setup_ept(0, false))
1101 		report_abort("EPT setup unexpectedly failed");
1102 }
1103 
1104 static int enable_unrestricted_guest(void)
1105 {
1106 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1107 	    !(ctrl_cpu_rev[1].clr & CPU_URG) ||
1108 	    !(ctrl_cpu_rev[1].clr & CPU_EPT))
1109 		return 1;
1110 
1111 	setup_dummy_ept();
1112 
1113 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
1114 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | CPU_URG);
1115 
1116 	return 0;
1117 }
1118 
1119 static void ept_enable_ad_bits(void)
1120 {
1121 	eptp |= EPTP_AD_FLAG;
1122 	vmcs_write(EPTP, eptp);
1123 }
1124 
1125 static void ept_disable_ad_bits(void)
1126 {
1127 	eptp &= ~EPTP_AD_FLAG;
1128 	vmcs_write(EPTP, eptp);
1129 }
1130 
1131 static int ept_ad_enabled(void)
1132 {
1133 	return eptp & EPTP_AD_FLAG;
1134 }
1135 
1136 static void ept_enable_ad_bits_or_skip_test(void)
1137 {
1138 	if (!ept_ad_bits_supported())
1139 		test_skip("EPT AD bits not supported.");
1140 	ept_enable_ad_bits();
1141 }
1142 
1143 static int apic_version;
1144 
1145 static int ept_init_common(bool have_ad)
1146 {
1147 	int ret;
1148 	struct pci_dev pcidev;
1149 
1150 	if (setup_ept(have_ad))
1151 		return VMX_TEST_EXIT;
1152 	data_page1 = alloc_page();
1153 	data_page2 = alloc_page();
1154 	*((u32 *)data_page1) = MAGIC_VAL_1;
1155 	*((u32 *)data_page2) = MAGIC_VAL_2;
1156 	install_ept(pml4, (unsigned long)data_page1, (unsigned long)data_page2,
1157 			EPT_RA | EPT_WA | EPT_EA);
1158 
1159 	apic_version = apic_read(APIC_LVR);
1160 
1161 	ret = pci_find_dev(PCI_VENDOR_ID_REDHAT, PCI_DEVICE_ID_REDHAT_TEST);
1162 	if (ret != PCIDEVADDR_INVALID) {
1163 		pci_dev_init(&pcidev, ret);
1164 		pci_physaddr = pcidev.resource[PCI_TESTDEV_BAR_MEM];
1165 	}
1166 
1167 	return VMX_TEST_START;
1168 }
1169 
1170 static int ept_init(struct vmcs *vmcs)
1171 {
1172 	return ept_init_common(false);
1173 }
1174 
1175 static void ept_common(void)
1176 {
1177 	vmx_set_test_stage(0);
1178 	if (*((u32 *)data_page2) != MAGIC_VAL_1 ||
1179 			*((u32 *)data_page1) != MAGIC_VAL_1)
1180 		report(0, "EPT basic framework - read");
1181 	else {
1182 		*((u32 *)data_page2) = MAGIC_VAL_3;
1183 		vmcall();
1184 		if (vmx_get_test_stage() == 1) {
1185 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1186 					*((u32 *)data_page2) == MAGIC_VAL_2)
1187 				report(1, "EPT basic framework");
1188 			else
1189 				report(1, "EPT basic framework - remap");
1190 		}
1191 	}
1192 	// Test EPT Misconfigurations
1193 	vmx_set_test_stage(1);
1194 	vmcall();
1195 	*((u32 *)data_page1) = MAGIC_VAL_1;
1196 	if (vmx_get_test_stage() != 2) {
1197 		report(0, "EPT misconfigurations");
1198 		goto t1;
1199 	}
1200 	vmx_set_test_stage(2);
1201 	vmcall();
1202 	*((u32 *)data_page1) = MAGIC_VAL_1;
1203 	report(vmx_get_test_stage() == 3, "EPT misconfigurations");
1204 t1:
1205 	// Test EPT violation
1206 	vmx_set_test_stage(3);
1207 	vmcall();
1208 	*((u32 *)data_page1) = MAGIC_VAL_1;
1209 	report(vmx_get_test_stage() == 4, "EPT violation - page permission");
1210 	// Violation caused by EPT paging structure
1211 	vmx_set_test_stage(4);
1212 	vmcall();
1213 	*((u32 *)data_page1) = MAGIC_VAL_2;
1214 	report(vmx_get_test_stage() == 5, "EPT violation - paging structure");
1215 
1216 	// MMIO Read/Write
1217 	vmx_set_test_stage(5);
1218 	vmcall();
1219 
1220 	*(u32 volatile *)pci_physaddr;
1221 	report(vmx_get_test_stage() == 6, "MMIO EPT violation - read");
1222 
1223 	*(u32 volatile *)pci_physaddr = MAGIC_VAL_1;
1224 	report(vmx_get_test_stage() == 7, "MMIO EPT violation - write");
1225 }
1226 
1227 static void ept_main(void)
1228 {
1229 	ept_common();
1230 
1231 	// Test EPT access to L1 MMIO
1232 	vmx_set_test_stage(7);
1233 	report(*((u32 *)0xfee00030UL) == apic_version, "EPT - MMIO access");
1234 
1235 	// Test invalid operand for INVEPT
1236 	vmcall();
1237 	report(vmx_get_test_stage() == 8, "EPT - unsupported INVEPT");
1238 }
1239 
1240 static bool invept_test(int type, u64 eptp)
1241 {
1242 	bool ret, supported;
1243 
1244 	supported = ept_vpid.val & (EPT_CAP_INVEPT_SINGLE >> INVEPT_SINGLE << type);
1245 	ret = invept(type, eptp);
1246 
1247 	if (ret == !supported)
1248 		return false;
1249 
1250 	if (!supported)
1251 		printf("WARNING: unsupported invept passed!\n");
1252 	else
1253 		printf("WARNING: invept failed!\n");
1254 
1255 	return true;
1256 }
1257 
1258 static int pml_exit_handler(union exit_reason exit_reason)
1259 {
1260 	u16 index, count;
1261 	u64 *pmlbuf = pml_log;
1262 	u64 guest_rip = vmcs_read(GUEST_RIP);;
1263 	u64 guest_cr3 = vmcs_read(GUEST_CR3);
1264 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1265 
1266 	switch (exit_reason.basic) {
1267 	case VMX_VMCALL:
1268 		switch (vmx_get_test_stage()) {
1269 		case 0:
1270 			index = vmcs_read(GUEST_PML_INDEX);
1271 			for (count = index + 1; count < PML_INDEX; count++) {
1272 				if (pmlbuf[count] == (u64)data_page2) {
1273 					vmx_inc_test_stage();
1274 					clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1275 					break;
1276 				}
1277 			}
1278 			break;
1279 		case 1:
1280 			index = vmcs_read(GUEST_PML_INDEX);
1281 			/* Keep clearing the dirty bit till a overflow */
1282 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1283 			break;
1284 		default:
1285 			report(false, "unexpected stage, %d.",
1286 			       vmx_get_test_stage());
1287 			print_vmexit_info(exit_reason);
1288 			return VMX_TEST_VMEXIT;
1289 		}
1290 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1291 		return VMX_TEST_RESUME;
1292 	case VMX_PML_FULL:
1293 		vmx_inc_test_stage();
1294 		vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1295 		return VMX_TEST_RESUME;
1296 	default:
1297 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1298 		print_vmexit_info(exit_reason);
1299 	}
1300 	return VMX_TEST_VMEXIT;
1301 }
1302 
1303 static int ept_exit_handler_common(union exit_reason exit_reason, bool have_ad)
1304 {
1305 	u64 guest_rip;
1306 	u64 guest_cr3;
1307 	u32 insn_len;
1308 	u32 exit_qual;
1309 	static unsigned long data_page1_pte, data_page1_pte_pte, memaddr_pte,
1310 			     guest_pte_addr;
1311 
1312 	guest_rip = vmcs_read(GUEST_RIP);
1313 	guest_cr3 = vmcs_read(GUEST_CR3);
1314 	insn_len = vmcs_read(EXI_INST_LEN);
1315 	exit_qual = vmcs_read(EXI_QUALIFICATION);
1316 	pteval_t *ptep;
1317 	switch (exit_reason.basic) {
1318 	case VMX_VMCALL:
1319 		switch (vmx_get_test_stage()) {
1320 		case 0:
1321 			check_ept_ad(pml4, guest_cr3,
1322 				     (unsigned long)data_page1,
1323 				     have_ad ? EPT_ACCESS_FLAG : 0,
1324 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1325 			check_ept_ad(pml4, guest_cr3,
1326 				     (unsigned long)data_page2,
1327 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0,
1328 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1329 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1330 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page2);
1331 			if (have_ad)
1332 				ept_sync(INVEPT_SINGLE, eptp);;
1333 			if (*((u32 *)data_page1) == MAGIC_VAL_3 &&
1334 					*((u32 *)data_page2) == MAGIC_VAL_2) {
1335 				vmx_inc_test_stage();
1336 				install_ept(pml4, (unsigned long)data_page2,
1337 						(unsigned long)data_page2,
1338 						EPT_RA | EPT_WA | EPT_EA);
1339 			} else
1340 				report(0, "EPT basic framework - write");
1341 			break;
1342 		case 1:
1343 			install_ept(pml4, (unsigned long)data_page1,
1344  				(unsigned long)data_page1, EPT_WA);
1345 			ept_sync(INVEPT_SINGLE, eptp);
1346 			break;
1347 		case 2:
1348 			install_ept(pml4, (unsigned long)data_page1,
1349  				(unsigned long)data_page1,
1350  				EPT_RA | EPT_WA | EPT_EA |
1351  				(2 << EPT_MEM_TYPE_SHIFT));
1352 			ept_sync(INVEPT_SINGLE, eptp);
1353 			break;
1354 		case 3:
1355 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1356 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)data_page1,
1357 						1, &data_page1_pte));
1358 			set_ept_pte(pml4, (unsigned long)data_page1,
1359 				1, data_page1_pte & ~EPT_PRESENT);
1360 			ept_sync(INVEPT_SINGLE, eptp);
1361 			break;
1362 		case 4:
1363 			ptep = get_pte_level((pgd_t *)guest_cr3, data_page1, /*level=*/2);
1364 			guest_pte_addr = virt_to_phys(ptep) & PAGE_MASK;
1365 
1366 			TEST_ASSERT(get_ept_pte(pml4, guest_pte_addr, 2, &data_page1_pte_pte));
1367 			set_ept_pte(pml4, guest_pte_addr, 2,
1368 				data_page1_pte_pte & ~EPT_PRESENT);
1369 			ept_sync(INVEPT_SINGLE, eptp);
1370 			break;
1371 		case 5:
1372 			install_ept(pml4, (unsigned long)pci_physaddr,
1373 				(unsigned long)pci_physaddr, 0);
1374 			ept_sync(INVEPT_SINGLE, eptp);
1375 			break;
1376 		case 7:
1377 			if (!invept_test(0, eptp))
1378 				vmx_inc_test_stage();
1379 			break;
1380 		// Should not reach here
1381 		default:
1382 			report(false, "ERROR - unexpected stage, %d.",
1383 			       vmx_get_test_stage());
1384 			print_vmexit_info(exit_reason);
1385 			return VMX_TEST_VMEXIT;
1386 		}
1387 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1388 		return VMX_TEST_RESUME;
1389 	case VMX_EPT_MISCONFIG:
1390 		switch (vmx_get_test_stage()) {
1391 		case 1:
1392 		case 2:
1393 			vmx_inc_test_stage();
1394 			install_ept(pml4, (unsigned long)data_page1,
1395  				(unsigned long)data_page1,
1396  				EPT_RA | EPT_WA | EPT_EA);
1397 			ept_sync(INVEPT_SINGLE, eptp);
1398 			break;
1399 		// Should not reach here
1400 		default:
1401 			report(false, "ERROR - unexpected stage, %d.",
1402 			       vmx_get_test_stage());
1403 			print_vmexit_info(exit_reason);
1404 			return VMX_TEST_VMEXIT;
1405 		}
1406 		return VMX_TEST_RESUME;
1407 	case VMX_EPT_VIOLATION:
1408 		/*
1409 		 * Exit-qualifications are masked not to account for advanced
1410 		 * VM-exit information. Once KVM supports this feature, this
1411 		 * masking should be removed.
1412 		 */
1413 		exit_qual &= ~EPT_VLT_GUEST_MASK;
1414 
1415 		switch(vmx_get_test_stage()) {
1416 		case 3:
1417 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1418 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1419 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1420 			if (exit_qual == (EPT_VLT_WR | EPT_VLT_LADDR_VLD |
1421 					EPT_VLT_PADDR))
1422 				vmx_inc_test_stage();
1423 			set_ept_pte(pml4, (unsigned long)data_page1,
1424 				1, data_page1_pte | (EPT_PRESENT));
1425 			ept_sync(INVEPT_SINGLE, eptp);
1426 			break;
1427 		case 4:
1428 			check_ept_ad(pml4, guest_cr3, (unsigned long)data_page1, 0,
1429 				     have_ad ? EPT_ACCESS_FLAG | EPT_DIRTY_FLAG : 0);
1430 			clear_ept_ad(pml4, guest_cr3, (unsigned long)data_page1);
1431 			if (exit_qual == (EPT_VLT_RD |
1432 					  (have_ad ? EPT_VLT_WR : 0) |
1433 					  EPT_VLT_LADDR_VLD))
1434 				vmx_inc_test_stage();
1435 			set_ept_pte(pml4, guest_pte_addr, 2,
1436 				data_page1_pte_pte | (EPT_PRESENT));
1437 			ept_sync(INVEPT_SINGLE, eptp);
1438 			break;
1439 		case 5:
1440 			if (exit_qual & EPT_VLT_RD)
1441 				vmx_inc_test_stage();
1442 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1443 						1, &memaddr_pte));
1444 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA);
1445 			ept_sync(INVEPT_SINGLE, eptp);
1446 			break;
1447 		case 6:
1448 			if (exit_qual & EPT_VLT_WR)
1449 				vmx_inc_test_stage();
1450 			TEST_ASSERT(get_ept_pte(pml4, (unsigned long)pci_physaddr,
1451 						1, &memaddr_pte));
1452 			set_ept_pte(pml4, memaddr_pte, 1, memaddr_pte | EPT_RA | EPT_WA);
1453 			ept_sync(INVEPT_SINGLE, eptp);
1454 			break;
1455 		default:
1456 			// Should not reach here
1457 			report(false, "ERROR : unexpected stage, %d",
1458 			       vmx_get_test_stage());
1459 			print_vmexit_info(exit_reason);
1460 			return VMX_TEST_VMEXIT;
1461 		}
1462 		return VMX_TEST_RESUME;
1463 	default:
1464 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1465 		print_vmexit_info(exit_reason);
1466 	}
1467 	return VMX_TEST_VMEXIT;
1468 }
1469 
1470 static int ept_exit_handler(union exit_reason exit_reason)
1471 {
1472 	return ept_exit_handler_common(exit_reason, false);
1473 }
1474 
1475 static int eptad_init(struct vmcs *vmcs)
1476 {
1477 	int r = ept_init_common(true);
1478 
1479 	if (r == VMX_TEST_EXIT)
1480 		return r;
1481 
1482 	if ((rdmsr(MSR_IA32_VMX_EPT_VPID_CAP) & EPT_CAP_AD_FLAG) == 0) {
1483 		printf("\tEPT A/D bits are not supported");
1484 		return VMX_TEST_EXIT;
1485 	}
1486 
1487 	return r;
1488 }
1489 
1490 static int pml_init(struct vmcs *vmcs)
1491 {
1492 	u32 ctrl_cpu;
1493 	int r = eptad_init(vmcs);
1494 
1495 	if (r == VMX_TEST_EXIT)
1496 		return r;
1497 
1498 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1499 		!(ctrl_cpu_rev[1].clr & CPU_PML)) {
1500 		printf("\tPML is not supported");
1501 		return VMX_TEST_EXIT;
1502 	}
1503 
1504 	pml_log = alloc_page();
1505 	vmcs_write(PMLADDR, (u64)pml_log);
1506 	vmcs_write(GUEST_PML_INDEX, PML_INDEX - 1);
1507 
1508 	ctrl_cpu = vmcs_read(CPU_EXEC_CTRL1) | CPU_PML;
1509 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu);
1510 
1511 	return VMX_TEST_START;
1512 }
1513 
1514 static void pml_main(void)
1515 {
1516 	int count = 0;
1517 
1518 	vmx_set_test_stage(0);
1519 	*((u32 *)data_page2) = 0x1;
1520 	vmcall();
1521 	report(vmx_get_test_stage() == 1, "PML - Dirty GPA Logging");
1522 
1523 	while (vmx_get_test_stage() == 1) {
1524 		vmcall();
1525 		*((u32 *)data_page2) = 0x1;
1526 		if (count++ > PML_INDEX)
1527 			break;
1528 	}
1529 	report(vmx_get_test_stage() == 2, "PML Full Event");
1530 }
1531 
1532 static void eptad_main(void)
1533 {
1534 	ept_common();
1535 }
1536 
1537 static int eptad_exit_handler(union exit_reason exit_reason)
1538 {
1539 	return ept_exit_handler_common(exit_reason, true);
1540 }
1541 
1542 static bool invvpid_test(int type, u16 vpid)
1543 {
1544 	bool ret, supported;
1545 
1546 	supported = ept_vpid.val &
1547 		(VPID_CAP_INVVPID_ADDR >> INVVPID_ADDR << type);
1548 	ret = invvpid(type, vpid, 0);
1549 
1550 	if (ret == !supported)
1551 		return false;
1552 
1553 	if (!supported)
1554 		printf("WARNING: unsupported invvpid passed!\n");
1555 	else
1556 		printf("WARNING: invvpid failed!\n");
1557 
1558 	return true;
1559 }
1560 
1561 static int vpid_init(struct vmcs *vmcs)
1562 {
1563 	u32 ctrl_cpu1;
1564 
1565 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
1566 		!(ctrl_cpu_rev[1].clr & CPU_VPID)) {
1567 		printf("\tVPID is not supported");
1568 		return VMX_TEST_EXIT;
1569 	}
1570 
1571 	ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
1572 	ctrl_cpu1 |= CPU_VPID;
1573 	vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
1574 	return VMX_TEST_START;
1575 }
1576 
1577 static void vpid_main(void)
1578 {
1579 	vmx_set_test_stage(0);
1580 	vmcall();
1581 	report(vmx_get_test_stage() == 1, "INVVPID SINGLE ADDRESS");
1582 	vmx_set_test_stage(2);
1583 	vmcall();
1584 	report(vmx_get_test_stage() == 3, "INVVPID SINGLE");
1585 	vmx_set_test_stage(4);
1586 	vmcall();
1587 	report(vmx_get_test_stage() == 5, "INVVPID ALL");
1588 }
1589 
1590 static int vpid_exit_handler(union exit_reason exit_reason)
1591 {
1592 	u64 guest_rip;
1593 	u32 insn_len;
1594 
1595 	guest_rip = vmcs_read(GUEST_RIP);
1596 	insn_len = vmcs_read(EXI_INST_LEN);
1597 
1598 	switch (exit_reason.basic) {
1599 	case VMX_VMCALL:
1600 		switch(vmx_get_test_stage()) {
1601 		case 0:
1602 			if (!invvpid_test(INVVPID_ADDR, 1))
1603 				vmx_inc_test_stage();
1604 			break;
1605 		case 2:
1606 			if (!invvpid_test(INVVPID_CONTEXT_GLOBAL, 1))
1607 				vmx_inc_test_stage();
1608 			break;
1609 		case 4:
1610 			if (!invvpid_test(INVVPID_ALL, 1))
1611 				vmx_inc_test_stage();
1612 			break;
1613 		default:
1614 			report(false, "ERROR: unexpected stage, %d",
1615 					vmx_get_test_stage());
1616 			print_vmexit_info(exit_reason);
1617 			return VMX_TEST_VMEXIT;
1618 		}
1619 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1620 		return VMX_TEST_RESUME;
1621 	default:
1622 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1623 		print_vmexit_info(exit_reason);
1624 	}
1625 	return VMX_TEST_VMEXIT;
1626 }
1627 
1628 #define TIMER_VECTOR	222
1629 
1630 static volatile bool timer_fired;
1631 
1632 static void timer_isr(isr_regs_t *regs)
1633 {
1634 	timer_fired = true;
1635 	apic_write(APIC_EOI, 0);
1636 }
1637 
1638 static int interrupt_init(struct vmcs *vmcs)
1639 {
1640 	msr_bmp_init();
1641 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1642 	handle_irq(TIMER_VECTOR, timer_isr);
1643 	return VMX_TEST_START;
1644 }
1645 
1646 static void interrupt_main(void)
1647 {
1648 	long long start, loops;
1649 
1650 	vmx_set_test_stage(0);
1651 
1652 	apic_write(APIC_LVTT, TIMER_VECTOR);
1653 	irq_enable();
1654 
1655 	apic_write(APIC_TMICT, 1);
1656 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1657 		asm volatile ("nop");
1658 	report(timer_fired, "direct interrupt while running guest");
1659 
1660 	apic_write(APIC_TMICT, 0);
1661 	irq_disable();
1662 	vmcall();
1663 	timer_fired = false;
1664 	apic_write(APIC_TMICT, 1);
1665 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1666 		asm volatile ("nop");
1667 	report(timer_fired, "intercepted interrupt while running guest");
1668 
1669 	irq_enable();
1670 	apic_write(APIC_TMICT, 0);
1671 	irq_disable();
1672 	vmcall();
1673 	timer_fired = false;
1674 	start = rdtsc();
1675 	apic_write(APIC_TMICT, 1000000);
1676 
1677 	asm volatile ("sti; hlt");
1678 
1679 	report(rdtsc() - start > 1000000 && timer_fired,
1680 	       "direct interrupt + hlt");
1681 
1682 	apic_write(APIC_TMICT, 0);
1683 	irq_disable();
1684 	vmcall();
1685 	timer_fired = false;
1686 	start = rdtsc();
1687 	apic_write(APIC_TMICT, 1000000);
1688 
1689 	asm volatile ("sti; hlt");
1690 
1691 	report(rdtsc() - start > 10000 && timer_fired,
1692 	       "intercepted interrupt + hlt");
1693 
1694 	apic_write(APIC_TMICT, 0);
1695 	irq_disable();
1696 	vmcall();
1697 	timer_fired = false;
1698 	start = rdtsc();
1699 	apic_write(APIC_TMICT, 1000000);
1700 
1701 	irq_enable();
1702 	asm volatile ("nop");
1703 	vmcall();
1704 
1705 	report(rdtsc() - start > 10000 && timer_fired,
1706 	       "direct interrupt + activity state hlt");
1707 
1708 	apic_write(APIC_TMICT, 0);
1709 	irq_disable();
1710 	vmcall();
1711 	timer_fired = false;
1712 	start = rdtsc();
1713 	apic_write(APIC_TMICT, 1000000);
1714 
1715 	irq_enable();
1716 	asm volatile ("nop");
1717 	vmcall();
1718 
1719 	report(rdtsc() - start > 10000 && timer_fired,
1720 	       "intercepted interrupt + activity state hlt");
1721 
1722 	apic_write(APIC_TMICT, 0);
1723 	irq_disable();
1724 	vmx_set_test_stage(7);
1725 	vmcall();
1726 	timer_fired = false;
1727 	apic_write(APIC_TMICT, 1);
1728 	for (loops = 0; loops < 10000000 && !timer_fired; loops++)
1729 		asm volatile ("nop");
1730 	report(timer_fired,
1731 	       "running a guest with interrupt acknowledgement set");
1732 
1733 	apic_write(APIC_TMICT, 0);
1734 	irq_enable();
1735 	timer_fired = false;
1736 	vmcall();
1737 	report(timer_fired, "Inject an event to a halted guest");
1738 }
1739 
1740 static int interrupt_exit_handler(union exit_reason exit_reason)
1741 {
1742 	u64 guest_rip = vmcs_read(GUEST_RIP);
1743 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1744 
1745 	switch (exit_reason.basic) {
1746 	case VMX_VMCALL:
1747 		switch (vmx_get_test_stage()) {
1748 		case 0:
1749 		case 2:
1750 		case 5:
1751 			vmcs_write(PIN_CONTROLS,
1752 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1753 			break;
1754 		case 7:
1755 			vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_INTA);
1756 			vmcs_write(PIN_CONTROLS,
1757 				   vmcs_read(PIN_CONTROLS) | PIN_EXTINT);
1758 			break;
1759 		case 1:
1760 		case 3:
1761 			vmcs_write(PIN_CONTROLS,
1762 				   vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
1763 			break;
1764 		case 4:
1765 		case 6:
1766 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1767 			break;
1768 
1769 		case 8:
1770 			vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
1771 			vmcs_write(ENT_INTR_INFO,
1772 				   TIMER_VECTOR |
1773 				   (VMX_INTR_TYPE_EXT_INTR << INTR_INFO_INTR_TYPE_SHIFT) |
1774 				   INTR_INFO_VALID_MASK);
1775 			break;
1776 		}
1777 		vmx_inc_test_stage();
1778 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
1779 		return VMX_TEST_RESUME;
1780 	case VMX_EXTINT:
1781 		if (vmcs_read(EXI_CONTROLS) & EXI_INTA) {
1782 			int vector = vmcs_read(EXI_INTR_INFO) & 0xff;
1783 			handle_external_interrupt(vector);
1784 		} else {
1785 			irq_enable();
1786 			asm volatile ("nop");
1787 			irq_disable();
1788 		}
1789 		if (vmx_get_test_stage() >= 2)
1790 			vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1791 		return VMX_TEST_RESUME;
1792 	default:
1793 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
1794 		print_vmexit_info(exit_reason);
1795 	}
1796 
1797 	return VMX_TEST_VMEXIT;
1798 }
1799 
1800 
1801 static volatile int nmi_fired;
1802 
1803 #define NMI_DELAY 100000000ULL
1804 
1805 static void nmi_isr(isr_regs_t *regs)
1806 {
1807 	nmi_fired = true;
1808 }
1809 
1810 static int nmi_hlt_init(struct vmcs *vmcs)
1811 {
1812 	msr_bmp_init();
1813 	handle_irq(NMI_VECTOR, nmi_isr);
1814 	vmcs_write(PIN_CONTROLS,
1815 		   vmcs_read(PIN_CONTROLS) & ~PIN_NMI);
1816 	vmcs_write(PIN_CONTROLS,
1817 		   vmcs_read(PIN_CONTROLS) & ~PIN_VIRT_NMI);
1818 	return VMX_TEST_START;
1819 }
1820 
1821 static void nmi_message_thread(void *data)
1822 {
1823     while (vmx_get_test_stage() != 1)
1824         pause();
1825 
1826     delay(NMI_DELAY);
1827     apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, id_map[0]);
1828 
1829     while (vmx_get_test_stage() != 2)
1830         pause();
1831 
1832     delay(NMI_DELAY);
1833     apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_NMI | APIC_INT_ASSERT, id_map[0]);
1834 }
1835 
1836 static void nmi_hlt_main(void)
1837 {
1838     long long start;
1839 
1840     if (cpu_count() < 2) {
1841         report_skip(__func__);
1842         vmx_set_test_stage(-1);
1843         return;
1844     }
1845 
1846     vmx_set_test_stage(0);
1847     on_cpu_async(1, nmi_message_thread, NULL);
1848     start = rdtsc();
1849     vmx_set_test_stage(1);
1850     asm volatile ("hlt");
1851     report((rdtsc() - start > NMI_DELAY) && nmi_fired,
1852             "direct NMI + hlt");
1853     if (!nmi_fired)
1854         vmx_set_test_stage(-1);
1855     nmi_fired = false;
1856 
1857     vmcall();
1858 
1859     start = rdtsc();
1860     vmx_set_test_stage(2);
1861     asm volatile ("hlt");
1862     report((rdtsc() - start > NMI_DELAY) && !nmi_fired,
1863             "intercepted NMI + hlt");
1864     if (nmi_fired) {
1865         report(!nmi_fired, "intercepted NMI was dispatched");
1866         vmx_set_test_stage(-1);
1867         return;
1868     }
1869     vmx_set_test_stage(3);
1870 }
1871 
1872 static int nmi_hlt_exit_handler(union exit_reason exit_reason)
1873 {
1874     u64 guest_rip = vmcs_read(GUEST_RIP);
1875     u32 insn_len = vmcs_read(EXI_INST_LEN);
1876 
1877     switch (vmx_get_test_stage()) {
1878     case 1:
1879         if (exit_reason.basic != VMX_VMCALL) {
1880             report(false, "VMEXIT not due to vmcall. Exit reason 0x%x",
1881                    exit_reason.full);
1882             print_vmexit_info(exit_reason);
1883             return VMX_TEST_VMEXIT;
1884         }
1885 
1886         vmcs_write(PIN_CONTROLS,
1887                vmcs_read(PIN_CONTROLS) | PIN_NMI);
1888         vmcs_write(PIN_CONTROLS,
1889                vmcs_read(PIN_CONTROLS) | PIN_VIRT_NMI);
1890         vmcs_write(GUEST_RIP, guest_rip + insn_len);
1891         break;
1892 
1893     case 2:
1894         if (exit_reason.basic != VMX_EXC_NMI) {
1895             report(false, "VMEXIT not due to NMI intercept. Exit reason 0x%x",
1896                    exit_reason.full);
1897             print_vmexit_info(exit_reason);
1898             return VMX_TEST_VMEXIT;
1899         }
1900         report(true, "NMI intercept while running guest");
1901         vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
1902         break;
1903 
1904     case 3:
1905         break;
1906 
1907     default:
1908         return VMX_TEST_VMEXIT;
1909     }
1910 
1911     if (vmx_get_test_stage() == 3)
1912         return VMX_TEST_VMEXIT;
1913 
1914     return VMX_TEST_RESUME;
1915 }
1916 
1917 
1918 static int dbgctls_init(struct vmcs *vmcs)
1919 {
1920 	u64 dr7 = 0x402;
1921 	u64 zero = 0;
1922 
1923 	msr_bmp_init();
1924 	asm volatile(
1925 		"mov %0,%%dr0\n\t"
1926 		"mov %0,%%dr1\n\t"
1927 		"mov %0,%%dr2\n\t"
1928 		"mov %1,%%dr7\n\t"
1929 		: : "r" (zero), "r" (dr7));
1930 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
1931 	vmcs_write(GUEST_DR7, 0x404);
1932 	vmcs_write(GUEST_DEBUGCTL, 0x2);
1933 
1934 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
1935 	vmcs_write(EXI_CONTROLS, vmcs_read(EXI_CONTROLS) | EXI_SAVE_DBGCTLS);
1936 
1937 	return VMX_TEST_START;
1938 }
1939 
1940 static void dbgctls_main(void)
1941 {
1942 	u64 dr7, debugctl;
1943 
1944 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1945 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1946 	/* Commented out: KVM does not support DEBUGCTL so far */
1947 	(void)debugctl;
1948 	report(dr7 == 0x404, "Load debug controls" /* && debugctl == 0x2 */);
1949 
1950 	dr7 = 0x408;
1951 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1952 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1953 
1954 	vmx_set_test_stage(0);
1955 	vmcall();
1956 	report(vmx_get_test_stage() == 1, "Save debug controls");
1957 
1958 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS ||
1959 	    ctrl_exit_rev.set & EXI_SAVE_DBGCTLS) {
1960 		printf("\tDebug controls are always loaded/saved\n");
1961 		return;
1962 	}
1963 	vmx_set_test_stage(2);
1964 	vmcall();
1965 
1966 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1967 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1968 	/* Commented out: KVM does not support DEBUGCTL so far */
1969 	(void)debugctl;
1970 	report(dr7 == 0x402,
1971 	       "Guest=host debug controls" /* && debugctl == 0x1 */);
1972 
1973 	dr7 = 0x408;
1974 	asm volatile("mov %0,%%dr7" : : "r" (dr7));
1975 	wrmsr(MSR_IA32_DEBUGCTLMSR, 0x3);
1976 
1977 	vmx_set_test_stage(3);
1978 	vmcall();
1979 	report(vmx_get_test_stage() == 4, "Don't save debug controls");
1980 }
1981 
1982 static int dbgctls_exit_handler(union exit_reason exit_reason)
1983 {
1984 	u32 insn_len = vmcs_read(EXI_INST_LEN);
1985 	u64 guest_rip = vmcs_read(GUEST_RIP);
1986 	u64 dr7, debugctl;
1987 
1988 	asm volatile("mov %%dr7,%0" : "=r" (dr7));
1989 	debugctl = rdmsr(MSR_IA32_DEBUGCTLMSR);
1990 
1991 	switch (exit_reason.basic) {
1992 	case VMX_VMCALL:
1993 		switch (vmx_get_test_stage()) {
1994 		case 0:
1995 			if (dr7 == 0x400 && debugctl == 0 &&
1996 			    vmcs_read(GUEST_DR7) == 0x408 /* &&
1997 			    Commented out: KVM does not support DEBUGCTL so far
1998 			    vmcs_read(GUEST_DEBUGCTL) == 0x3 */)
1999 				vmx_inc_test_stage();
2000 			break;
2001 		case 2:
2002 			dr7 = 0x402;
2003 			asm volatile("mov %0,%%dr7" : : "r" (dr7));
2004 			wrmsr(MSR_IA32_DEBUGCTLMSR, 0x1);
2005 			vmcs_write(GUEST_DR7, 0x404);
2006 			vmcs_write(GUEST_DEBUGCTL, 0x2);
2007 
2008 			vmcs_write(ENT_CONTROLS,
2009 				vmcs_read(ENT_CONTROLS) & ~ENT_LOAD_DBGCTLS);
2010 			vmcs_write(EXI_CONTROLS,
2011 				vmcs_read(EXI_CONTROLS) & ~EXI_SAVE_DBGCTLS);
2012 			break;
2013 		case 3:
2014 			if (dr7 == 0x400 && debugctl == 0 &&
2015 			    vmcs_read(GUEST_DR7) == 0x404 /* &&
2016 			    Commented out: KVM does not support DEBUGCTL so far
2017 			    vmcs_read(GUEST_DEBUGCTL) == 0x2 */)
2018 				vmx_inc_test_stage();
2019 			break;
2020 		}
2021 		vmcs_write(GUEST_RIP, guest_rip + insn_len);
2022 		return VMX_TEST_RESUME;
2023 	default:
2024 		report(false, "Unknown exit reason, %d", exit_reason.full);
2025 		print_vmexit_info(exit_reason);
2026 	}
2027 	return VMX_TEST_VMEXIT;
2028 }
2029 
2030 struct vmx_msr_entry {
2031 	u32 index;
2032 	u32 reserved;
2033 	u64 value;
2034 } __attribute__((packed));
2035 
2036 #define MSR_MAGIC 0x31415926
2037 struct vmx_msr_entry *exit_msr_store, *entry_msr_load, *exit_msr_load;
2038 
2039 static int msr_switch_init(struct vmcs *vmcs)
2040 {
2041 	msr_bmp_init();
2042 	exit_msr_store = alloc_page();
2043 	exit_msr_load = alloc_page();
2044 	entry_msr_load = alloc_page();
2045 	entry_msr_load[0].index = MSR_KERNEL_GS_BASE;
2046 	entry_msr_load[0].value = MSR_MAGIC;
2047 
2048 	vmx_set_test_stage(1);
2049 	vmcs_write(ENT_MSR_LD_CNT, 1);
2050 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)entry_msr_load);
2051 	vmcs_write(EXI_MSR_ST_CNT, 1);
2052 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)exit_msr_store);
2053 	vmcs_write(EXI_MSR_LD_CNT, 1);
2054 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)exit_msr_load);
2055 	return VMX_TEST_START;
2056 }
2057 
2058 static void msr_switch_main(void)
2059 {
2060 	if (vmx_get_test_stage() == 1) {
2061 		report(rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC,
2062 		       "VM entry MSR load");
2063 		vmx_set_test_stage(2);
2064 		wrmsr(MSR_KERNEL_GS_BASE, MSR_MAGIC + 1);
2065 		exit_msr_store[0].index = MSR_KERNEL_GS_BASE;
2066 		exit_msr_load[0].index = MSR_KERNEL_GS_BASE;
2067 		exit_msr_load[0].value = MSR_MAGIC + 2;
2068 	}
2069 	vmcall();
2070 }
2071 
2072 static int msr_switch_exit_handler(union exit_reason exit_reason)
2073 {
2074 	if (exit_reason.basic == VMX_VMCALL && vmx_get_test_stage() == 2) {
2075 		report(exit_msr_store[0].value == MSR_MAGIC + 1,
2076 		       "VM exit MSR store");
2077 		report(rdmsr(MSR_KERNEL_GS_BASE) == MSR_MAGIC + 2,
2078 		       "VM exit MSR load");
2079 		vmx_set_test_stage(3);
2080 		entry_msr_load[0].index = MSR_FS_BASE;
2081 		return VMX_TEST_RESUME;
2082 	}
2083 	printf("ERROR %s: unexpected stage=%u or reason=0x%x\n",
2084 		__func__, vmx_get_test_stage(), exit_reason.full);
2085 	return VMX_TEST_EXIT;
2086 }
2087 
2088 static int msr_switch_entry_failure(struct vmentry_result *result)
2089 {
2090 	if (result->vm_fail) {
2091 		printf("ERROR %s: VM-Fail on %s\n", __func__, result->instr);
2092 		return VMX_TEST_EXIT;
2093 	}
2094 
2095 	if (result->exit_reason.failed_vmentry &&
2096 	    result->exit_reason.basic == VMX_FAIL_MSR &&
2097 	    vmx_get_test_stage() == 3) {
2098 		report(vmcs_read(EXI_QUALIFICATION) == 1,
2099 		       "VM entry MSR load: try to load FS_BASE");
2100 		return VMX_TEST_VMEXIT;
2101 	}
2102 	printf("ERROR %s: unexpected stage=%u or reason=%x\n",
2103 		__func__, vmx_get_test_stage(), result->exit_reason.full);
2104 	return VMX_TEST_EXIT;
2105 }
2106 
2107 static int vmmcall_init(struct vmcs *vmcs)
2108 {
2109 	vmcs_write(EXC_BITMAP, 1 << UD_VECTOR);
2110 	return VMX_TEST_START;
2111 }
2112 
2113 static void vmmcall_main(void)
2114 {
2115 	asm volatile(
2116 		"mov $0xABCD, %%rax\n\t"
2117 		"vmmcall\n\t"
2118 		::: "rax");
2119 
2120 	report(0, "VMMCALL");
2121 }
2122 
2123 static int vmmcall_exit_handler(union exit_reason exit_reason)
2124 {
2125 	switch (exit_reason.basic) {
2126 	case VMX_VMCALL:
2127 		printf("here\n");
2128 		report(0, "VMMCALL triggers #UD");
2129 		break;
2130 	case VMX_EXC_NMI:
2131 		report((vmcs_read(EXI_INTR_INFO) & 0xff) == UD_VECTOR,
2132 		       "VMMCALL triggers #UD");
2133 		break;
2134 	default:
2135 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
2136 		print_vmexit_info(exit_reason);
2137 	}
2138 
2139 	return VMX_TEST_VMEXIT;
2140 }
2141 
2142 static int disable_rdtscp_init(struct vmcs *vmcs)
2143 {
2144 	u32 ctrl_cpu1;
2145 
2146 	if (ctrl_cpu_rev[0].clr & CPU_SECONDARY) {
2147 		ctrl_cpu1 = vmcs_read(CPU_EXEC_CTRL1);
2148 		ctrl_cpu1 &= ~CPU_RDTSCP;
2149 		vmcs_write(CPU_EXEC_CTRL1, ctrl_cpu1);
2150 	}
2151 
2152 	return VMX_TEST_START;
2153 }
2154 
2155 static void disable_rdtscp_ud_handler(struct ex_regs *regs)
2156 {
2157 	switch (vmx_get_test_stage()) {
2158 	case 0:
2159 		report(true, "RDTSCP triggers #UD");
2160 		vmx_inc_test_stage();
2161 		regs->rip += 3;
2162 		break;
2163 	case 2:
2164 		report(true, "RDPID triggers #UD");
2165 		vmx_inc_test_stage();
2166 		regs->rip += 4;
2167 		break;
2168 	}
2169 	return;
2170 
2171 }
2172 
2173 static void disable_rdtscp_main(void)
2174 {
2175 	/* Test that #UD is properly injected in L2.  */
2176 	handle_exception(UD_VECTOR, disable_rdtscp_ud_handler);
2177 
2178 	vmx_set_test_stage(0);
2179 	asm volatile("rdtscp" : : : "eax", "ecx", "edx");
2180 	vmcall();
2181 	asm volatile(".byte 0xf3, 0x0f, 0xc7, 0xf8" : : : "eax");
2182 
2183 	handle_exception(UD_VECTOR, 0);
2184 	vmcall();
2185 }
2186 
2187 static int disable_rdtscp_exit_handler(union exit_reason exit_reason)
2188 {
2189 	switch (exit_reason.basic) {
2190 	case VMX_VMCALL:
2191 		switch (vmx_get_test_stage()) {
2192 		case 0:
2193 			report(false, "RDTSCP triggers #UD");
2194 			vmx_inc_test_stage();
2195 			/* fallthrough */
2196 		case 1:
2197 			vmx_inc_test_stage();
2198 			vmcs_write(GUEST_RIP, vmcs_read(GUEST_RIP) + 3);
2199 			return VMX_TEST_RESUME;
2200 		case 2:
2201 			report(false, "RDPID triggers #UD");
2202 			break;
2203 		}
2204 		break;
2205 
2206 	default:
2207 		report(false, "Unknown exit reason, 0x%x", exit_reason.full);
2208 		print_vmexit_info(exit_reason);
2209 	}
2210 	return VMX_TEST_VMEXIT;
2211 }
2212 
2213 static int int3_init(struct vmcs *vmcs)
2214 {
2215 	vmcs_write(EXC_BITMAP, ~0u);
2216 	return VMX_TEST_START;
2217 }
2218 
2219 static void int3_guest_main(void)
2220 {
2221 	asm volatile ("int3");
2222 }
2223 
2224 static int int3_exit_handler(union exit_reason exit_reason)
2225 {
2226 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2227 
2228 	report(exit_reason.basic == VMX_EXC_NMI &&
2229 	       (intr_info & INTR_INFO_VALID_MASK) &&
2230 	       (intr_info & INTR_INFO_VECTOR_MASK) == BP_VECTOR &&
2231 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2232 	        INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION,
2233 	       "L1 intercepts #BP");
2234 
2235 	return VMX_TEST_VMEXIT;
2236 }
2237 
2238 static int into_init(struct vmcs *vmcs)
2239 {
2240 	vmcs_write(EXC_BITMAP, ~0u);
2241 	return VMX_TEST_START;
2242 }
2243 
2244 static void into_guest_main(void)
2245 {
2246 	struct far_pointer32 fp = {
2247 		.offset = (uintptr_t)&&into,
2248 		.selector = KERNEL_CS32,
2249 	};
2250 	uintptr_t rsp;
2251 
2252 	asm volatile ("mov %%rsp, %0" : "=r"(rsp));
2253 
2254 	if (fp.offset != (uintptr_t)&&into) {
2255 		printf("Code address too high.\n");
2256 		return;
2257 	}
2258 	if ((u32)rsp != rsp) {
2259 		printf("Stack address too high.\n");
2260 		return;
2261 	}
2262 
2263 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : into);
2264 	return;
2265 into:
2266 	asm volatile (".code32;"
2267 		      "movl $0x7fffffff, %eax;"
2268 		      "addl %eax, %eax;"
2269 		      "into;"
2270 		      "lret;"
2271 		      ".code64");
2272 	__builtin_unreachable();
2273 }
2274 
2275 static int into_exit_handler(union exit_reason exit_reason)
2276 {
2277 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
2278 
2279 	report(exit_reason.basic == VMX_EXC_NMI &&
2280 	       (intr_info & INTR_INFO_VALID_MASK) &&
2281 	       (intr_info & INTR_INFO_VECTOR_MASK) == OF_VECTOR &&
2282 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >>
2283 	        INTR_INFO_INTR_TYPE_SHIFT) == VMX_INTR_TYPE_SOFT_EXCEPTION,
2284 	       "L1 intercepts #OF");
2285 
2286 	return VMX_TEST_VMEXIT;
2287 }
2288 
2289 static void exit_monitor_from_l2_main(void)
2290 {
2291 	printf("Calling exit(0) from l2...\n");
2292 	exit(0);
2293 }
2294 
2295 static int exit_monitor_from_l2_handler(union exit_reason exit_reason)
2296 {
2297 	report(false, "The guest should have killed the VMM");
2298 	return VMX_TEST_EXIT;
2299 }
2300 
2301 static void assert_exit_reason(u64 expected)
2302 {
2303 	u64 actual = vmcs_read(EXI_REASON);
2304 
2305 	TEST_ASSERT_EQ_MSG(expected, actual, "Expected %s, got %s.",
2306 			   exit_reason_description(expected),
2307 			   exit_reason_description(actual));
2308 }
2309 
2310 static void skip_exit_insn(void)
2311 {
2312 	u64 guest_rip = vmcs_read(GUEST_RIP);
2313 	u32 insn_len = vmcs_read(EXI_INST_LEN);
2314 	vmcs_write(GUEST_RIP, guest_rip + insn_len);
2315 }
2316 
2317 static void skip_exit_vmcall(void)
2318 {
2319 	assert_exit_reason(VMX_VMCALL);
2320 	skip_exit_insn();
2321 }
2322 
2323 static void v2_null_test_guest(void)
2324 {
2325 }
2326 
2327 static void v2_null_test(void)
2328 {
2329 	test_set_guest(v2_null_test_guest);
2330 	enter_guest();
2331 	report(1, __func__);
2332 }
2333 
2334 static void v2_multiple_entries_test_guest(void)
2335 {
2336 	vmx_set_test_stage(1);
2337 	vmcall();
2338 	vmx_set_test_stage(2);
2339 }
2340 
2341 static void v2_multiple_entries_test(void)
2342 {
2343 	test_set_guest(v2_multiple_entries_test_guest);
2344 	enter_guest();
2345 	TEST_ASSERT_EQ(vmx_get_test_stage(), 1);
2346 	skip_exit_vmcall();
2347 	enter_guest();
2348 	TEST_ASSERT_EQ(vmx_get_test_stage(), 2);
2349 	report(1, __func__);
2350 }
2351 
2352 static int fixture_test_data = 1;
2353 
2354 static void fixture_test_teardown(void *data)
2355 {
2356 	*((int *) data) = 1;
2357 }
2358 
2359 static void fixture_test_guest(void)
2360 {
2361 	fixture_test_data++;
2362 }
2363 
2364 
2365 static void fixture_test_setup(void)
2366 {
2367 	TEST_ASSERT_EQ_MSG(1, fixture_test_data,
2368 			   "fixture_test_teardown didn't run?!");
2369 	fixture_test_data = 2;
2370 	test_add_teardown(fixture_test_teardown, &fixture_test_data);
2371 	test_set_guest(fixture_test_guest);
2372 }
2373 
2374 static void fixture_test_case1(void)
2375 {
2376 	fixture_test_setup();
2377 	TEST_ASSERT_EQ(2, fixture_test_data);
2378 	enter_guest();
2379 	TEST_ASSERT_EQ(3, fixture_test_data);
2380 	report(1, __func__);
2381 }
2382 
2383 static void fixture_test_case2(void)
2384 {
2385 	fixture_test_setup();
2386 	TEST_ASSERT_EQ(2, fixture_test_data);
2387 	enter_guest();
2388 	TEST_ASSERT_EQ(3, fixture_test_data);
2389 	report(1, __func__);
2390 }
2391 
2392 enum ept_access_op {
2393 	OP_READ,
2394 	OP_WRITE,
2395 	OP_EXEC,
2396 	OP_FLUSH_TLB,
2397 	OP_EXIT,
2398 };
2399 
2400 static struct ept_access_test_data {
2401 	unsigned long gpa;
2402 	unsigned long *gva;
2403 	unsigned long hpa;
2404 	unsigned long *hva;
2405 	enum ept_access_op op;
2406 } ept_access_test_data;
2407 
2408 extern unsigned char ret42_start;
2409 extern unsigned char ret42_end;
2410 
2411 /* Returns 42. */
2412 asm(
2413 	".align 64\n"
2414 	"ret42_start:\n"
2415 	"mov $42, %eax\n"
2416 	"ret\n"
2417 	"ret42_end:\n"
2418 );
2419 
2420 static void
2421 diagnose_ept_violation_qual(u64 expected, u64 actual)
2422 {
2423 
2424 #define DIAGNOSE(flag)							\
2425 do {									\
2426 	if ((expected & flag) != (actual & flag))			\
2427 		printf(#flag " %sexpected\n",				\
2428 		       (expected & flag) ? "" : "un");			\
2429 } while (0)
2430 
2431 	DIAGNOSE(EPT_VLT_RD);
2432 	DIAGNOSE(EPT_VLT_WR);
2433 	DIAGNOSE(EPT_VLT_FETCH);
2434 	DIAGNOSE(EPT_VLT_PERM_RD);
2435 	DIAGNOSE(EPT_VLT_PERM_WR);
2436 	DIAGNOSE(EPT_VLT_PERM_EX);
2437 	DIAGNOSE(EPT_VLT_LADDR_VLD);
2438 	DIAGNOSE(EPT_VLT_PADDR);
2439 
2440 #undef DIAGNOSE
2441 }
2442 
2443 static void do_ept_access_op(enum ept_access_op op)
2444 {
2445 	ept_access_test_data.op = op;
2446 	enter_guest();
2447 }
2448 
2449 /*
2450  * Force the guest to flush its TLB (i.e., flush gva -> gpa mappings). Only
2451  * needed by tests that modify guest PTEs.
2452  */
2453 static void ept_access_test_guest_flush_tlb(void)
2454 {
2455 	do_ept_access_op(OP_FLUSH_TLB);
2456 	skip_exit_vmcall();
2457 }
2458 
2459 /*
2460  * Modifies the EPT entry at @level in the mapping of @gpa. First clears the
2461  * bits in @clear then sets the bits in @set. @mkhuge transforms the entry into
2462  * a huge page.
2463  */
2464 static unsigned long ept_twiddle(unsigned long gpa, bool mkhuge, int level,
2465 				 unsigned long clear, unsigned long set)
2466 {
2467 	struct ept_access_test_data *data = &ept_access_test_data;
2468 	unsigned long orig_pte;
2469 	unsigned long pte;
2470 
2471 	/* Screw with the mapping at the requested level. */
2472 	TEST_ASSERT(get_ept_pte(pml4, gpa, level, &orig_pte));
2473 	pte = orig_pte;
2474 	if (mkhuge)
2475 		pte = (orig_pte & ~EPT_ADDR_MASK) | data->hpa | EPT_LARGE_PAGE;
2476 	else
2477 		pte = orig_pte;
2478 	pte = (pte & ~clear) | set;
2479 	set_ept_pte(pml4, gpa, level, pte);
2480 	ept_sync(INVEPT_SINGLE, eptp);
2481 
2482 	return orig_pte;
2483 }
2484 
2485 static void ept_untwiddle(unsigned long gpa, int level, unsigned long orig_pte)
2486 {
2487 	set_ept_pte(pml4, gpa, level, orig_pte);
2488 	ept_sync(INVEPT_SINGLE, eptp);
2489 }
2490 
2491 static void do_ept_violation(bool leaf, enum ept_access_op op,
2492 			     u64 expected_qual, u64 expected_paddr)
2493 {
2494 	u64 qual;
2495 
2496 	/* Try the access and observe the violation. */
2497 	do_ept_access_op(op);
2498 
2499 	assert_exit_reason(VMX_EPT_VIOLATION);
2500 
2501 	qual = vmcs_read(EXI_QUALIFICATION);
2502 
2503 	/* Mask undefined bits (which may later be defined in certain cases). */
2504 	qual &= ~(EPT_VLT_GUEST_USER | EPT_VLT_GUEST_RW | EPT_VLT_GUEST_EX |
2505 		 EPT_VLT_PERM_USER_EX);
2506 
2507 	diagnose_ept_violation_qual(expected_qual, qual);
2508 	TEST_EXPECT_EQ(expected_qual, qual);
2509 
2510 	#if 0
2511 	/* Disable for now otherwise every test will fail */
2512 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2513 		       (unsigned long) (
2514 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2515 	#endif
2516 	/*
2517 	 * TODO: tests that probe expected_paddr in pages other than the one at
2518 	 * the beginning of the 1g region.
2519 	 */
2520 	TEST_EXPECT_EQ(vmcs_read(INFO_PHYS_ADDR), expected_paddr);
2521 }
2522 
2523 static void
2524 ept_violation_at_level_mkhuge(bool mkhuge, int level, unsigned long clear,
2525 			      unsigned long set, enum ept_access_op op,
2526 			      u64 expected_qual)
2527 {
2528 	struct ept_access_test_data *data = &ept_access_test_data;
2529 	unsigned long orig_pte;
2530 
2531 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2532 
2533 	do_ept_violation(level == 1 || mkhuge, op, expected_qual,
2534 			 op == OP_EXEC ? data->gpa + sizeof(unsigned long) :
2535 					 data->gpa);
2536 
2537 	/* Fix the violation and resume the op loop. */
2538 	ept_untwiddle(data->gpa, level, orig_pte);
2539 	enter_guest();
2540 	skip_exit_vmcall();
2541 }
2542 
2543 static void
2544 ept_violation_at_level(int level, unsigned long clear, unsigned long set,
2545 		       enum ept_access_op op, u64 expected_qual)
2546 {
2547 	ept_violation_at_level_mkhuge(false, level, clear, set, op,
2548 				      expected_qual);
2549 	if (ept_huge_pages_supported(level))
2550 		ept_violation_at_level_mkhuge(true, level, clear, set, op,
2551 					      expected_qual);
2552 }
2553 
2554 static void ept_violation(unsigned long clear, unsigned long set,
2555 			  enum ept_access_op op, u64 expected_qual)
2556 {
2557 	ept_violation_at_level(1, clear, set, op, expected_qual);
2558 	ept_violation_at_level(2, clear, set, op, expected_qual);
2559 	ept_violation_at_level(3, clear, set, op, expected_qual);
2560 	ept_violation_at_level(4, clear, set, op, expected_qual);
2561 }
2562 
2563 static void ept_access_violation(unsigned long access, enum ept_access_op op,
2564 				       u64 expected_qual)
2565 {
2566 	ept_violation(EPT_PRESENT, access, op,
2567 		      expected_qual | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2568 }
2569 
2570 /*
2571  * For translations that don't involve a GVA, that is physical address (paddr)
2572  * accesses, EPT violations don't set the flag EPT_VLT_PADDR.  For a typical
2573  * guest memory access, the hardware does GVA -> GPA -> HPA.  However, certain
2574  * translations don't involve GVAs, such as when the hardware does the guest
2575  * page table walk. For example, in translating GVA_1 -> GPA_1, the guest MMU
2576  * might try to set an A bit on a guest PTE. If the GPA_2 that the PTE resides
2577  * on isn't present in the EPT, then the EPT violation will be for GPA_2 and
2578  * the EPT_VLT_PADDR bit will be clear in the exit qualification.
2579  *
2580  * Note that paddr violations can also be triggered by loading PAE page tables
2581  * with wonky addresses. We don't test that yet.
2582  *
2583  * This function modifies the EPT entry that maps the GPA that the guest page
2584  * table entry mapping ept_access_test_data.gva resides on.
2585  *
2586  *	@ept_access	EPT permissions to set. Other permissions are cleared.
2587  *
2588  *	@pte_ad		Set the A/D bits on the guest PTE accordingly.
2589  *
2590  *	@op		Guest operation to perform with
2591  *			ept_access_test_data.gva.
2592  *
2593  *	@expect_violation
2594  *			Is a violation expected during the paddr access?
2595  *
2596  *	@expected_qual	Expected qualification for the EPT violation.
2597  *			EPT_VLT_PADDR should be clear.
2598  */
2599 static void ept_access_paddr(unsigned long ept_access, unsigned long pte_ad,
2600 			     enum ept_access_op op, bool expect_violation,
2601 			     u64 expected_qual)
2602 {
2603 	struct ept_access_test_data *data = &ept_access_test_data;
2604 	unsigned long *ptep;
2605 	unsigned long gpa;
2606 	unsigned long orig_epte;
2607 	unsigned long epte;
2608 	int i;
2609 
2610 	/* Modify the guest PTE mapping data->gva according to @pte_ad.  */
2611 	ptep = get_pte_level(current_page_table(), data->gva, /*level=*/1);
2612 	TEST_ASSERT(ptep);
2613 	TEST_ASSERT_EQ(*ptep & PT_ADDR_MASK, data->gpa);
2614 	*ptep = (*ptep & ~PT_AD_MASK) | pte_ad;
2615 	ept_access_test_guest_flush_tlb();
2616 
2617 	/*
2618 	 * Now modify the access bits on the EPT entry for the GPA that the
2619 	 * guest PTE resides on. Note that by modifying a single EPT entry,
2620 	 * we're potentially affecting 512 guest PTEs. However, we've carefully
2621 	 * constructed our test such that those other 511 PTEs aren't used by
2622 	 * the guest: data->gva is at the beginning of a 1G huge page, thus the
2623 	 * PTE we're modifying is at the beginning of a 4K page and the
2624 	 * following 511 entires are also under our control (and not touched by
2625 	 * the guest).
2626 	 */
2627 	gpa = virt_to_phys(ptep);
2628 	TEST_ASSERT_EQ(gpa & ~PAGE_MASK, 0);
2629 	/*
2630 	 * Make sure the guest page table page is mapped with a 4K EPT entry,
2631 	 * otherwise our level=1 twiddling below will fail. We use the
2632 	 * identity map (gpa = gpa) since page tables are shared with the host.
2633 	 */
2634 	install_ept(pml4, gpa, gpa, EPT_PRESENT);
2635 	orig_epte = ept_twiddle(gpa, /*mkhuge=*/0, /*level=*/1,
2636 				/*clear=*/EPT_PRESENT, /*set=*/ept_access);
2637 
2638 	if (expect_violation) {
2639 		do_ept_violation(/*leaf=*/true, op,
2640 				 expected_qual | EPT_VLT_LADDR_VLD, gpa);
2641 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2642 		do_ept_access_op(op);
2643 	} else {
2644 		do_ept_access_op(op);
2645 		if (ept_ad_enabled()) {
2646 			for (i = EPT_PAGE_LEVEL; i > 0; i--) {
2647 				TEST_ASSERT(get_ept_pte(pml4, gpa, i, &epte));
2648 				TEST_ASSERT(epte & EPT_ACCESS_FLAG);
2649 				if (i == 1)
2650 					TEST_ASSERT(epte & EPT_DIRTY_FLAG);
2651 				else
2652 					TEST_ASSERT_EQ(epte & EPT_DIRTY_FLAG, 0);
2653 			}
2654 		}
2655 
2656 		ept_untwiddle(gpa, /*level=*/1, orig_epte);
2657 	}
2658 
2659 	TEST_ASSERT(*ptep & PT_ACCESSED_MASK);
2660 	if ((pte_ad & PT_DIRTY_MASK) || op == OP_WRITE)
2661 		TEST_ASSERT(*ptep & PT_DIRTY_MASK);
2662 
2663 	skip_exit_vmcall();
2664 }
2665 
2666 static void ept_access_allowed_paddr(unsigned long ept_access,
2667 				     unsigned long pte_ad,
2668 				     enum ept_access_op op)
2669 {
2670 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/false,
2671 			 /*expected_qual=*/-1);
2672 }
2673 
2674 static void ept_access_violation_paddr(unsigned long ept_access,
2675 				       unsigned long pte_ad,
2676 				       enum ept_access_op op,
2677 				       u64 expected_qual)
2678 {
2679 	ept_access_paddr(ept_access, pte_ad, op, /*expect_violation=*/true,
2680 			 expected_qual);
2681 }
2682 
2683 
2684 static void ept_allowed_at_level_mkhuge(bool mkhuge, int level,
2685 					unsigned long clear,
2686 					unsigned long set,
2687 					enum ept_access_op op)
2688 {
2689 	struct ept_access_test_data *data = &ept_access_test_data;
2690 	unsigned long orig_pte;
2691 
2692 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2693 
2694 	/* No violation. Should proceed to vmcall. */
2695 	do_ept_access_op(op);
2696 	skip_exit_vmcall();
2697 
2698 	ept_untwiddle(data->gpa, level, orig_pte);
2699 }
2700 
2701 static void ept_allowed_at_level(int level, unsigned long clear,
2702 				 unsigned long set, enum ept_access_op op)
2703 {
2704 	ept_allowed_at_level_mkhuge(false, level, clear, set, op);
2705 	if (ept_huge_pages_supported(level))
2706 		ept_allowed_at_level_mkhuge(true, level, clear, set, op);
2707 }
2708 
2709 static void ept_allowed(unsigned long clear, unsigned long set,
2710 			enum ept_access_op op)
2711 {
2712 	ept_allowed_at_level(1, clear, set, op);
2713 	ept_allowed_at_level(2, clear, set, op);
2714 	ept_allowed_at_level(3, clear, set, op);
2715 	ept_allowed_at_level(4, clear, set, op);
2716 }
2717 
2718 static void ept_ignored_bit(int bit)
2719 {
2720 	/* Set the bit. */
2721 	ept_allowed(0, 1ul << bit, OP_READ);
2722 	ept_allowed(0, 1ul << bit, OP_WRITE);
2723 	ept_allowed(0, 1ul << bit, OP_EXEC);
2724 
2725 	/* Clear the bit. */
2726 	ept_allowed(1ul << bit, 0, OP_READ);
2727 	ept_allowed(1ul << bit, 0, OP_WRITE);
2728 	ept_allowed(1ul << bit, 0, OP_EXEC);
2729 }
2730 
2731 static void ept_access_allowed(unsigned long access, enum ept_access_op op)
2732 {
2733 	ept_allowed(EPT_PRESENT, access, op);
2734 }
2735 
2736 
2737 static void ept_misconfig_at_level_mkhuge_op(bool mkhuge, int level,
2738 					     unsigned long clear,
2739 					     unsigned long set,
2740 					     enum ept_access_op op)
2741 {
2742 	struct ept_access_test_data *data = &ept_access_test_data;
2743 	unsigned long orig_pte;
2744 
2745 	orig_pte = ept_twiddle(data->gpa, mkhuge, level, clear, set);
2746 
2747 	do_ept_access_op(op);
2748 	assert_exit_reason(VMX_EPT_MISCONFIG);
2749 
2750 	/* Intel 27.2.1, "For all other VM exits, this field is cleared." */
2751 	#if 0
2752 	/* broken: */
2753 	TEST_EXPECT_EQ_MSG(vmcs_read(EXI_QUALIFICATION), 0);
2754 	#endif
2755 	#if 0
2756 	/*
2757 	 * broken:
2758 	 * According to description of exit qual for EPT violation,
2759 	 * EPT_VLT_LADDR_VLD indicates if GUEST_LINEAR_ADDRESS is valid.
2760 	 * However, I can't find anything that says GUEST_LINEAR_ADDRESS ought
2761 	 * to be set for msiconfig.
2762 	 */
2763 	TEST_EXPECT_EQ(vmcs_read(GUEST_LINEAR_ADDRESS),
2764 		       (unsigned long) (
2765 			       op == OP_EXEC ? data->gva + 1 : data->gva));
2766 	#endif
2767 
2768 	/* Fix the violation and resume the op loop. */
2769 	ept_untwiddle(data->gpa, level, orig_pte);
2770 	enter_guest();
2771 	skip_exit_vmcall();
2772 }
2773 
2774 static void ept_misconfig_at_level_mkhuge(bool mkhuge, int level,
2775 					  unsigned long clear,
2776 					  unsigned long set)
2777 {
2778 	/* The op shouldn't matter (read, write, exec), so try them all! */
2779 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_READ);
2780 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_WRITE);
2781 	ept_misconfig_at_level_mkhuge_op(mkhuge, level, clear, set, OP_EXEC);
2782 }
2783 
2784 static void ept_misconfig_at_level(int level, unsigned long clear,
2785 				   unsigned long set)
2786 {
2787 	ept_misconfig_at_level_mkhuge(false, level, clear, set);
2788 	if (ept_huge_pages_supported(level))
2789 		ept_misconfig_at_level_mkhuge(true, level, clear, set);
2790 }
2791 
2792 static void ept_misconfig(unsigned long clear, unsigned long set)
2793 {
2794 	ept_misconfig_at_level(1, clear, set);
2795 	ept_misconfig_at_level(2, clear, set);
2796 	ept_misconfig_at_level(3, clear, set);
2797 	ept_misconfig_at_level(4, clear, set);
2798 }
2799 
2800 static void ept_access_misconfig(unsigned long access)
2801 {
2802 	ept_misconfig(EPT_PRESENT, access);
2803 }
2804 
2805 static void ept_reserved_bit_at_level_nohuge(int level, int bit)
2806 {
2807 	/* Setting the bit causes a misconfig. */
2808 	ept_misconfig_at_level_mkhuge(false, level, 0, 1ul << bit);
2809 
2810 	/* Making the entry non-present turns reserved bits into ignored. */
2811 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2812 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2813 }
2814 
2815 static void ept_reserved_bit_at_level_huge(int level, int bit)
2816 {
2817 	/* Setting the bit causes a misconfig. */
2818 	ept_misconfig_at_level_mkhuge(true, level, 0, 1ul << bit);
2819 
2820 	/* Making the entry non-present turns reserved bits into ignored. */
2821 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2822 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2823 }
2824 
2825 static void ept_reserved_bit_at_level(int level, int bit)
2826 {
2827 	/* Setting the bit causes a misconfig. */
2828 	ept_misconfig_at_level(level, 0, 1ul << bit);
2829 
2830 	/* Making the entry non-present turns reserved bits into ignored. */
2831 	ept_violation_at_level(level, EPT_PRESENT, 1ul << bit, OP_READ,
2832 			       EPT_VLT_RD | EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
2833 }
2834 
2835 static void ept_reserved_bit(int bit)
2836 {
2837 	ept_reserved_bit_at_level(1, bit);
2838 	ept_reserved_bit_at_level(2, bit);
2839 	ept_reserved_bit_at_level(3, bit);
2840 	ept_reserved_bit_at_level(4, bit);
2841 }
2842 
2843 #define PAGE_2M_ORDER 9
2844 #define PAGE_1G_ORDER 18
2845 
2846 static void *get_1g_page(void)
2847 {
2848 	static void *alloc;
2849 
2850 	if (!alloc)
2851 		alloc = alloc_pages(PAGE_1G_ORDER);
2852 	return alloc;
2853 }
2854 
2855 static void ept_access_test_teardown(void *unused)
2856 {
2857 	/* Exit the guest cleanly. */
2858 	do_ept_access_op(OP_EXIT);
2859 }
2860 
2861 static void ept_access_test_guest(void)
2862 {
2863 	struct ept_access_test_data *data = &ept_access_test_data;
2864 	int (*code)(void) = (int (*)(void)) &data->gva[1];
2865 
2866 	while (true) {
2867 		switch (data->op) {
2868 		case OP_READ:
2869 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_1);
2870 			break;
2871 		case OP_WRITE:
2872 			*data->gva = MAGIC_VAL_2;
2873 			TEST_ASSERT_EQ(*data->gva, MAGIC_VAL_2);
2874 			*data->gva = MAGIC_VAL_1;
2875 			break;
2876 		case OP_EXEC:
2877 			TEST_ASSERT_EQ(42, code());
2878 			break;
2879 		case OP_FLUSH_TLB:
2880 			write_cr3(read_cr3());
2881 			break;
2882 		case OP_EXIT:
2883 			return;
2884 		default:
2885 			TEST_ASSERT_MSG(false, "Unknown op %d", data->op);
2886 		}
2887 		vmcall();
2888 	}
2889 }
2890 
2891 static void ept_access_test_setup(void)
2892 {
2893 	struct ept_access_test_data *data = &ept_access_test_data;
2894 	unsigned long npages = 1ul << PAGE_1G_ORDER;
2895 	unsigned long size = npages * PAGE_SIZE;
2896 	unsigned long *page_table = current_page_table();
2897 	unsigned long pte;
2898 
2899 	if (setup_ept(false))
2900 		test_skip("EPT not supported");
2901 
2902 	/* We use data->gpa = 1 << 39 so that test data has a separate pml4 entry */
2903 	if (cpuid_maxphyaddr() < 40)
2904 		test_skip("Test needs MAXPHYADDR >= 40");
2905 
2906 	test_set_guest(ept_access_test_guest);
2907 	test_add_teardown(ept_access_test_teardown, NULL);
2908 
2909 	data->hva = get_1g_page();
2910 	TEST_ASSERT(data->hva);
2911 	data->hpa = virt_to_phys(data->hva);
2912 
2913 	data->gpa = 1ul << 39;
2914 	data->gva = (void *) ALIGN((unsigned long) alloc_vpages(npages * 2),
2915 				   size);
2916 	TEST_ASSERT(!any_present_pages(page_table, data->gva, size));
2917 	install_pages(page_table, data->gpa, size, data->gva);
2918 
2919 	/*
2920 	 * Make sure nothing's mapped here so the tests that screw with the
2921 	 * pml4 entry don't inadvertently break something.
2922 	 */
2923 	TEST_ASSERT(get_ept_pte(pml4, data->gpa, 4, &pte) && pte == 0);
2924 	TEST_ASSERT(get_ept_pte(pml4, data->gpa + size - 1, 4, &pte) && pte == 0);
2925 	install_ept(pml4, data->hpa, data->gpa, EPT_PRESENT);
2926 
2927 	data->hva[0] = MAGIC_VAL_1;
2928 	memcpy(&data->hva[1], &ret42_start, &ret42_end - &ret42_start);
2929 }
2930 
2931 static void ept_access_test_not_present(void)
2932 {
2933 	ept_access_test_setup();
2934 	/* --- */
2935 	ept_access_violation(0, OP_READ, EPT_VLT_RD);
2936 	ept_access_violation(0, OP_WRITE, EPT_VLT_WR);
2937 	ept_access_violation(0, OP_EXEC, EPT_VLT_FETCH);
2938 }
2939 
2940 static void ept_access_test_read_only(void)
2941 {
2942 	ept_access_test_setup();
2943 
2944 	/* r-- */
2945 	ept_access_allowed(EPT_RA, OP_READ);
2946 	ept_access_violation(EPT_RA, OP_WRITE, EPT_VLT_WR | EPT_VLT_PERM_RD);
2947 	ept_access_violation(EPT_RA, OP_EXEC, EPT_VLT_FETCH | EPT_VLT_PERM_RD);
2948 }
2949 
2950 static void ept_access_test_write_only(void)
2951 {
2952 	ept_access_test_setup();
2953 	/* -w- */
2954 	ept_access_misconfig(EPT_WA);
2955 }
2956 
2957 static void ept_access_test_read_write(void)
2958 {
2959 	ept_access_test_setup();
2960 	/* rw- */
2961 	ept_access_allowed(EPT_RA | EPT_WA, OP_READ);
2962 	ept_access_allowed(EPT_RA | EPT_WA, OP_WRITE);
2963 	ept_access_violation(EPT_RA | EPT_WA, OP_EXEC,
2964 			   EPT_VLT_FETCH | EPT_VLT_PERM_RD | EPT_VLT_PERM_WR);
2965 }
2966 
2967 
2968 static void ept_access_test_execute_only(void)
2969 {
2970 	ept_access_test_setup();
2971 	/* --x */
2972 	if (ept_execute_only_supported()) {
2973 		ept_access_violation(EPT_EA, OP_READ,
2974 				     EPT_VLT_RD | EPT_VLT_PERM_EX);
2975 		ept_access_violation(EPT_EA, OP_WRITE,
2976 				     EPT_VLT_WR | EPT_VLT_PERM_EX);
2977 		ept_access_allowed(EPT_EA, OP_EXEC);
2978 	} else {
2979 		ept_access_misconfig(EPT_EA);
2980 	}
2981 }
2982 
2983 static void ept_access_test_read_execute(void)
2984 {
2985 	ept_access_test_setup();
2986 	/* r-x */
2987 	ept_access_allowed(EPT_RA | EPT_EA, OP_READ);
2988 	ept_access_violation(EPT_RA | EPT_EA, OP_WRITE,
2989 			   EPT_VLT_WR | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX);
2990 	ept_access_allowed(EPT_RA | EPT_EA, OP_EXEC);
2991 }
2992 
2993 static void ept_access_test_write_execute(void)
2994 {
2995 	ept_access_test_setup();
2996 	/* -wx */
2997 	ept_access_misconfig(EPT_WA | EPT_EA);
2998 }
2999 
3000 static void ept_access_test_read_write_execute(void)
3001 {
3002 	ept_access_test_setup();
3003 	/* rwx */
3004 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_READ);
3005 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_WRITE);
3006 	ept_access_allowed(EPT_RA | EPT_WA | EPT_EA, OP_EXEC);
3007 }
3008 
3009 static void ept_access_test_reserved_bits(void)
3010 {
3011 	int i;
3012 	int maxphyaddr;
3013 
3014 	ept_access_test_setup();
3015 
3016 	/* Reserved bits above maxphyaddr. */
3017 	maxphyaddr = cpuid_maxphyaddr();
3018 	for (i = maxphyaddr; i <= 51; i++) {
3019 		report_prefix_pushf("reserved_bit=%d", i);
3020 		ept_reserved_bit(i);
3021 		report_prefix_pop();
3022 	}
3023 
3024 	/* Level-specific reserved bits. */
3025 	ept_reserved_bit_at_level_nohuge(2, 3);
3026 	ept_reserved_bit_at_level_nohuge(2, 4);
3027 	ept_reserved_bit_at_level_nohuge(2, 5);
3028 	ept_reserved_bit_at_level_nohuge(2, 6);
3029 	/* 2M alignment. */
3030 	for (i = 12; i < 20; i++) {
3031 		report_prefix_pushf("reserved_bit=%d", i);
3032 		ept_reserved_bit_at_level_huge(2, i);
3033 		report_prefix_pop();
3034 	}
3035 	ept_reserved_bit_at_level_nohuge(3, 3);
3036 	ept_reserved_bit_at_level_nohuge(3, 4);
3037 	ept_reserved_bit_at_level_nohuge(3, 5);
3038 	ept_reserved_bit_at_level_nohuge(3, 6);
3039 	/* 1G alignment. */
3040 	for (i = 12; i < 29; i++) {
3041 		report_prefix_pushf("reserved_bit=%d", i);
3042 		ept_reserved_bit_at_level_huge(3, i);
3043 		report_prefix_pop();
3044 	}
3045 	ept_reserved_bit_at_level(4, 3);
3046 	ept_reserved_bit_at_level(4, 4);
3047 	ept_reserved_bit_at_level(4, 5);
3048 	ept_reserved_bit_at_level(4, 6);
3049 	ept_reserved_bit_at_level(4, 7);
3050 }
3051 
3052 static void ept_access_test_ignored_bits(void)
3053 {
3054 	ept_access_test_setup();
3055 	/*
3056 	 * Bits ignored at every level. Bits 8 and 9 (A and D) are ignored as
3057 	 * far as translation is concerned even if AD bits are enabled in the
3058 	 * EPTP. Bit 63 is ignored because "EPT-violation #VE" VM-execution
3059 	 * control is 0.
3060 	 */
3061 	ept_ignored_bit(8);
3062 	ept_ignored_bit(9);
3063 	ept_ignored_bit(10);
3064 	ept_ignored_bit(11);
3065 	ept_ignored_bit(52);
3066 	ept_ignored_bit(53);
3067 	ept_ignored_bit(54);
3068 	ept_ignored_bit(55);
3069 	ept_ignored_bit(56);
3070 	ept_ignored_bit(57);
3071 	ept_ignored_bit(58);
3072 	ept_ignored_bit(59);
3073 	ept_ignored_bit(60);
3074 	ept_ignored_bit(61);
3075 	ept_ignored_bit(62);
3076 	ept_ignored_bit(63);
3077 }
3078 
3079 static void ept_access_test_paddr_not_present_ad_disabled(void)
3080 {
3081 	ept_access_test_setup();
3082 	ept_disable_ad_bits();
3083 
3084 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, EPT_VLT_RD);
3085 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, EPT_VLT_RD);
3086 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, EPT_VLT_RD);
3087 }
3088 
3089 static void ept_access_test_paddr_not_present_ad_enabled(void)
3090 {
3091 	u64 qual = EPT_VLT_RD | EPT_VLT_WR;
3092 
3093 	ept_access_test_setup();
3094 	ept_enable_ad_bits_or_skip_test();
3095 
3096 	ept_access_violation_paddr(0, PT_AD_MASK, OP_READ, qual);
3097 	ept_access_violation_paddr(0, PT_AD_MASK, OP_WRITE, qual);
3098 	ept_access_violation_paddr(0, PT_AD_MASK, OP_EXEC, qual);
3099 }
3100 
3101 static void ept_access_test_paddr_read_only_ad_disabled(void)
3102 {
3103 	/*
3104 	 * When EPT AD bits are disabled, all accesses to guest paging
3105 	 * structures are reported separately as a read and (after
3106 	 * translation of the GPA to host physical address) a read+write
3107 	 * if the A/D bits have to be set.
3108 	 */
3109 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
3110 
3111 	ept_access_test_setup();
3112 	ept_disable_ad_bits();
3113 
3114 	/* Can't update A bit, so all accesses fail. */
3115 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
3116 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
3117 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
3118 	/* AD bits disabled, so only writes try to update the D bit. */
3119 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ);
3120 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
3121 	ept_access_allowed_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC);
3122 	/* Both A and D already set, so read-only is OK. */
3123 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_READ);
3124 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_WRITE);
3125 	ept_access_allowed_paddr(EPT_RA, PT_AD_MASK, OP_EXEC);
3126 }
3127 
3128 static void ept_access_test_paddr_read_only_ad_enabled(void)
3129 {
3130 	/*
3131 	 * When EPT AD bits are enabled, all accesses to guest paging
3132 	 * structures are considered writes as far as EPT translation
3133 	 * is concerned.
3134 	 */
3135 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD;
3136 
3137 	ept_access_test_setup();
3138 	ept_enable_ad_bits_or_skip_test();
3139 
3140 	ept_access_violation_paddr(EPT_RA, 0, OP_READ, qual);
3141 	ept_access_violation_paddr(EPT_RA, 0, OP_WRITE, qual);
3142 	ept_access_violation_paddr(EPT_RA, 0, OP_EXEC, qual);
3143 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_READ, qual);
3144 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_WRITE, qual);
3145 	ept_access_violation_paddr(EPT_RA, PT_ACCESSED_MASK, OP_EXEC, qual);
3146 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_READ, qual);
3147 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_WRITE, qual);
3148 	ept_access_violation_paddr(EPT_RA, PT_AD_MASK, OP_EXEC, qual);
3149 }
3150 
3151 static void ept_access_test_paddr_read_write(void)
3152 {
3153 	ept_access_test_setup();
3154 	/* Read-write access to paging structure. */
3155 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_READ);
3156 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_WRITE);
3157 	ept_access_allowed_paddr(EPT_RA | EPT_WA, 0, OP_EXEC);
3158 }
3159 
3160 static void ept_access_test_paddr_read_write_execute(void)
3161 {
3162 	ept_access_test_setup();
3163 	/* RWX access to paging structure. */
3164 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_READ);
3165 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_WRITE);
3166 	ept_access_allowed_paddr(EPT_PRESENT, 0, OP_EXEC);
3167 }
3168 
3169 static void ept_access_test_paddr_read_execute_ad_disabled(void)
3170 {
3171   	/*
3172 	 * When EPT AD bits are disabled, all accesses to guest paging
3173 	 * structures are reported separately as a read and (after
3174 	 * translation of the GPA to host physical address) a read+write
3175 	 * if the A/D bits have to be set.
3176 	 */
3177 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3178 
3179 	ept_access_test_setup();
3180 	ept_disable_ad_bits();
3181 
3182 	/* Can't update A bit, so all accesses fail. */
3183 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3184 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3185 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3186 	/* AD bits disabled, so only writes try to update the D bit. */
3187 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ);
3188 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3189 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC);
3190 	/* Both A and D already set, so read-only is OK. */
3191 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ);
3192 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE);
3193 	ept_access_allowed_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC);
3194 }
3195 
3196 static void ept_access_test_paddr_read_execute_ad_enabled(void)
3197 {
3198 	/*
3199 	 * When EPT AD bits are enabled, all accesses to guest paging
3200 	 * structures are considered writes as far as EPT translation
3201 	 * is concerned.
3202 	 */
3203 	u64 qual = EPT_VLT_WR | EPT_VLT_RD | EPT_VLT_PERM_RD | EPT_VLT_PERM_EX;
3204 
3205 	ept_access_test_setup();
3206 	ept_enable_ad_bits_or_skip_test();
3207 
3208 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_READ, qual);
3209 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_WRITE, qual);
3210 	ept_access_violation_paddr(EPT_RA | EPT_EA, 0, OP_EXEC, qual);
3211 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_READ, qual);
3212 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_WRITE, qual);
3213 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_ACCESSED_MASK, OP_EXEC, qual);
3214 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_READ, qual);
3215 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_WRITE, qual);
3216 	ept_access_violation_paddr(EPT_RA | EPT_EA, PT_AD_MASK, OP_EXEC, qual);
3217 }
3218 
3219 static void ept_access_test_paddr_not_present_page_fault(void)
3220 {
3221 	ept_access_test_setup();
3222 	/*
3223 	 * TODO: test no EPT violation as long as guest PF occurs. e.g., GPA is
3224 	 * page is read-only in EPT but GVA is also mapped read only in PT.
3225 	 * Thus guest page fault before host takes EPT violation for trying to
3226 	 * update A bit.
3227 	 */
3228 }
3229 
3230 static void ept_access_test_force_2m_page(void)
3231 {
3232 	ept_access_test_setup();
3233 
3234 	TEST_ASSERT_EQ(ept_2m_supported(), true);
3235 	ept_allowed_at_level_mkhuge(true, 2, 0, 0, OP_READ);
3236 	ept_violation_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_RA, OP_WRITE,
3237 				      EPT_VLT_WR | EPT_VLT_PERM_RD |
3238 				      EPT_VLT_LADDR_VLD | EPT_VLT_PADDR);
3239 	ept_misconfig_at_level_mkhuge(true, 2, EPT_PRESENT, EPT_WA);
3240 }
3241 
3242 static bool invvpid_valid(u64 type, u64 vpid, u64 gla)
3243 {
3244 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3245 
3246 	TEST_ASSERT(msr & VPID_CAP_INVVPID);
3247 
3248 	if (type < INVVPID_ADDR || type > INVVPID_CONTEXT_LOCAL)
3249 		return false;
3250 
3251 	if (!(msr & (1ull << (type + VPID_CAP_INVVPID_TYPES_SHIFT))))
3252 		return false;
3253 
3254 	if (vpid >> 16)
3255 		return false;
3256 
3257 	if (type != INVVPID_ALL && !vpid)
3258 		return false;
3259 
3260 	if (type == INVVPID_ADDR && !is_canonical(gla))
3261 		return false;
3262 
3263 	return true;
3264 }
3265 
3266 static void try_invvpid(u64 type, u64 vpid, u64 gla)
3267 {
3268 	int rc;
3269 	bool valid = invvpid_valid(type, vpid, gla);
3270 	u64 expected = valid ? VMXERR_UNSUPPORTED_VMCS_COMPONENT
3271 		: VMXERR_INVALID_OPERAND_TO_INVEPT_INVVPID;
3272 	/*
3273 	 * Set VMX_INST_ERROR to VMXERR_UNVALID_VMCS_COMPONENT, so
3274 	 * that we can tell if it is updated by INVVPID.
3275 	 */
3276 	vmcs_read(~0);
3277 	rc = invvpid(type, vpid, gla);
3278 	report(!rc == valid, "INVVPID type %ld VPID %lx GLA %lx %s", type,
3279 	       vpid, gla,
3280 	       valid ? "passes" : "fails");
3281 	report(vmcs_read(VMX_INST_ERROR) == expected,
3282 	       "After %s INVVPID, VMX_INST_ERR is %ld (actual %ld)",
3283 	       rc ? "failed" : "successful",
3284 	       expected, vmcs_read(VMX_INST_ERROR));
3285 }
3286 
3287 static void ds_invvpid(void *data)
3288 {
3289 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3290 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3291 
3292 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3293 	asm volatile("invvpid %0, %1"
3294 		     :
3295 		     : "m"(*(struct invvpid_operand *)data),
3296 		       "r"(type));
3297 }
3298 
3299 /*
3300  * The SS override is ignored in 64-bit mode, so we use an addressing
3301  * mode with %rsp as the base register to generate an implicit SS
3302  * reference.
3303  */
3304 static void ss_invvpid(void *data)
3305 {
3306 	u64 msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3307 	u64 type = ffs(msr >> VPID_CAP_INVVPID_TYPES_SHIFT) - 1;
3308 
3309 	TEST_ASSERT(type >= INVVPID_ADDR && type <= INVVPID_CONTEXT_LOCAL);
3310 	asm volatile("sub %%rsp,%0; invvpid (%%rsp,%0,1), %1"
3311 		     : "+r"(data)
3312 		     : "r"(type));
3313 }
3314 
3315 static void invvpid_test_gp(void)
3316 {
3317 	bool fault;
3318 
3319 	fault = test_for_exception(GP_VECTOR, &ds_invvpid,
3320 				   (void *)NONCANONICAL);
3321 	report(fault, "INVVPID with non-canonical DS operand raises #GP");
3322 }
3323 
3324 static void invvpid_test_ss(void)
3325 {
3326 	bool fault;
3327 
3328 	fault = test_for_exception(SS_VECTOR, &ss_invvpid,
3329 				   (void *)NONCANONICAL);
3330 	report(fault, "INVVPID with non-canonical SS operand raises #SS");
3331 }
3332 
3333 static void invvpid_test_pf(void)
3334 {
3335 	void *vpage = alloc_vpage();
3336 	bool fault;
3337 
3338 	fault = test_for_exception(PF_VECTOR, &ds_invvpid, vpage);
3339 	report(fault, "INVVPID with unmapped operand raises #PF");
3340 }
3341 
3342 static void try_compat_invvpid(void *unused)
3343 {
3344 	struct far_pointer32 fp = {
3345 		.offset = (uintptr_t)&&invvpid,
3346 		.selector = KERNEL_CS32,
3347 	};
3348 	uintptr_t rsp;
3349 
3350 	asm volatile ("mov %%rsp, %0" : "=r"(rsp));
3351 
3352 	TEST_ASSERT_MSG(fp.offset == (uintptr_t)&&invvpid,
3353 			"Code address too high.");
3354 	TEST_ASSERT_MSG(rsp == (u32)rsp, "Stack address too high.");
3355 
3356 	asm goto ("lcall *%0" : : "m" (fp) : "rax" : invvpid);
3357 	return;
3358 invvpid:
3359 	asm volatile (".code32;"
3360 		      "invvpid (%eax), %eax;"
3361 		      "lret;"
3362 		      ".code64");
3363 	__builtin_unreachable();
3364 }
3365 
3366 static void invvpid_test_compatibility_mode(void)
3367 {
3368 	bool fault;
3369 
3370 	fault = test_for_exception(UD_VECTOR, &try_compat_invvpid, NULL);
3371 	report(fault, "Compatibility mode INVVPID raises #UD");
3372 }
3373 
3374 static void invvpid_test_not_in_vmx_operation(void)
3375 {
3376 	bool fault;
3377 
3378 	TEST_ASSERT(!vmx_off());
3379 	fault = test_for_exception(UD_VECTOR, &ds_invvpid, NULL);
3380 	report(fault, "INVVPID outside of VMX operation raises #UD");
3381 	TEST_ASSERT(!vmx_on());
3382 }
3383 
3384 /*
3385  * This does not test real-address mode, virtual-8086 mode, protected mode,
3386  * or CPL > 0.
3387  */
3388 static void invvpid_test_v2(void)
3389 {
3390 	u64 msr;
3391 	int i;
3392 	unsigned types = 0;
3393 	unsigned type;
3394 
3395 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
3396 	    !(ctrl_cpu_rev[1].clr & CPU_VPID))
3397 		test_skip("VPID not supported");
3398 
3399 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
3400 
3401 	if (!(msr & VPID_CAP_INVVPID))
3402 		test_skip("INVVPID not supported.\n");
3403 
3404 	if (msr & VPID_CAP_INVVPID_ADDR)
3405 		types |= 1u << INVVPID_ADDR;
3406 	if (msr & VPID_CAP_INVVPID_CXTGLB)
3407 		types |= 1u << INVVPID_CONTEXT_GLOBAL;
3408 	if (msr & VPID_CAP_INVVPID_ALL)
3409 		types |= 1u << INVVPID_ALL;
3410 	if (msr & VPID_CAP_INVVPID_CXTLOC)
3411 		types |= 1u << INVVPID_CONTEXT_LOCAL;
3412 
3413 	if (!types)
3414 		test_skip("No INVVPID types supported.\n");
3415 
3416 	for (i = -127; i < 128; i++)
3417 		try_invvpid(i, 0xffff, 0);
3418 
3419 	/*
3420 	 * VPID must not be more than 16 bits.
3421 	 */
3422 	for (i = 0; i < 64; i++)
3423 		for (type = 0; type < 4; type++)
3424 			if (types & (1u << type))
3425 				try_invvpid(type, 1ul << i, 0);
3426 
3427 	/*
3428 	 * VPID must not be zero, except for "all contexts."
3429 	 */
3430 	for (type = 0; type < 4; type++)
3431 		if (types & (1u << type))
3432 			try_invvpid(type, 0, 0);
3433 
3434 	/*
3435 	 * The gla operand is only validated for single-address INVVPID.
3436 	 */
3437 	if (types & (1u << INVVPID_ADDR))
3438 		try_invvpid(INVVPID_ADDR, 0xffff, NONCANONICAL);
3439 
3440 	invvpid_test_gp();
3441 	invvpid_test_ss();
3442 	invvpid_test_pf();
3443 	invvpid_test_compatibility_mode();
3444 	invvpid_test_not_in_vmx_operation();
3445 }
3446 
3447 /*
3448  * Test for early VMLAUNCH failure. Returns true if VMLAUNCH makes it
3449  * at least as far as the guest-state checks. Returns false if the
3450  * VMLAUNCH fails early and execution falls through to the next
3451  * instruction.
3452  */
3453 static bool vmlaunch_succeeds(void)
3454 {
3455 	u32 exit_reason;
3456 
3457 	/*
3458 	 * Indirectly set VMX_INST_ERR to 12 ("VMREAD/VMWRITE from/to
3459 	 * unsupported VMCS component"). The caller can then check
3460 	 * to see if a failed VM-entry sets VMX_INST_ERR as expected.
3461 	 */
3462 	vmcs_write(~0u, 0);
3463 
3464 	vmcs_write(HOST_RIP, (uintptr_t)&&success);
3465 	__asm__ __volatile__ goto ("vmwrite %%rsp, %0; vmlaunch"
3466 				   :
3467 				   : "r" ((u64)HOST_RSP)
3468 				   : "cc", "memory"
3469 				   : success);
3470 	return false;
3471 success:
3472 	exit_reason = vmcs_read(EXI_REASON);
3473 	TEST_ASSERT(exit_reason == (VMX_FAIL_STATE | VMX_ENTRY_FAILURE) ||
3474 		    exit_reason == (VMX_FAIL_MSR | VMX_ENTRY_FAILURE));
3475 	return true;
3476 }
3477 
3478 /*
3479  * Try to launch the current VMCS.
3480  */
3481 static void test_vmx_vmlaunch(u32 xerror)
3482 {
3483 	bool success = vmlaunch_succeeds();
3484 	u32 vmx_inst_err;
3485 
3486 	report(success == !xerror, "vmlaunch %s",
3487 	       !xerror ? "succeeds" : "fails");
3488 	if (!success && xerror) {
3489 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3490 		report(vmx_inst_err == xerror,
3491 		       "VMX inst error is %d (actual %d)", xerror,
3492 		       vmx_inst_err);
3493 	}
3494 }
3495 
3496 /*
3497  * Try to launch the current VMCS, and expect one of two possible
3498  * errors (or success) codes.
3499  */
3500 static void test_vmx_vmlaunch2(u32 xerror1, u32 xerror2)
3501 {
3502 	bool success = vmlaunch_succeeds();
3503 	u32 vmx_inst_err;
3504 
3505 	if (!xerror1 == !xerror2)
3506 		report(success == !xerror1, "vmlaunch %s",
3507 		       !xerror1 ? "succeeds" : "fails");
3508 
3509 	if (!success && (xerror1 || xerror2)) {
3510 		vmx_inst_err = vmcs_read(VMX_INST_ERROR);
3511 		report(vmx_inst_err == xerror1 || vmx_inst_err == xerror2,
3512 		       "VMX inst error is %d or %d (actual %d)", xerror1,
3513 		       xerror2, vmx_inst_err);
3514 	}
3515 }
3516 
3517 static void test_vmx_invalid_controls(void)
3518 {
3519 	test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_CONTROL_FIELD);
3520 }
3521 
3522 static void test_vmx_valid_controls(void)
3523 {
3524 	test_vmx_vmlaunch(0);
3525 }
3526 
3527 /*
3528  * Test a particular value of a VM-execution control bit, if the value
3529  * is required or if the value is zero.
3530  */
3531 static void test_rsvd_ctl_bit_value(const char *name, union vmx_ctrl_msr msr,
3532 				    enum Encoding encoding, unsigned bit,
3533 				    unsigned val)
3534 {
3535 	u32 mask = 1u << bit;
3536 	bool expected;
3537 	u32 controls;
3538 
3539 	if (msr.set & mask)
3540 		TEST_ASSERT(msr.clr & mask);
3541 
3542 	/*
3543 	 * We can't arbitrarily turn on a control bit, because it may
3544 	 * introduce dependencies on other VMCS fields. So, we only
3545 	 * test turning on bits that have a required setting.
3546 	 */
3547 	if (val && (msr.clr & mask) && !(msr.set & mask))
3548 		return;
3549 
3550 	report_prefix_pushf("%s %s bit %d",
3551 			    val ? "Set" : "Clear", name, bit);
3552 
3553 	controls = vmcs_read(encoding);
3554 	if (val) {
3555 		vmcs_write(encoding, msr.set | mask);
3556 		expected = (msr.clr & mask);
3557 	} else {
3558 		vmcs_write(encoding, msr.set & ~mask);
3559 		expected = !(msr.set & mask);
3560 	}
3561 	if (expected)
3562 		test_vmx_valid_controls();
3563 	else
3564 		test_vmx_invalid_controls();
3565 	vmcs_write(encoding, controls);
3566 	report_prefix_pop();
3567 }
3568 
3569 /*
3570  * Test reserved values of a VM-execution control bit, based on the
3571  * allowed bit settings from the corresponding VMX capability MSR.
3572  */
3573 static void test_rsvd_ctl_bit(const char *name, union vmx_ctrl_msr msr,
3574 			      enum Encoding encoding, unsigned bit)
3575 {
3576 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 0);
3577 	test_rsvd_ctl_bit_value(name, msr, encoding, bit, 1);
3578 }
3579 
3580 /*
3581  * Reserved bits in the pin-based VM-execution controls must be set
3582  * properly. Software may consult the VMX capability MSRs to determine
3583  * the proper settings.
3584  * [Intel SDM]
3585  */
3586 static void test_pin_based_ctls(void)
3587 {
3588 	unsigned bit;
3589 
3590 	printf("%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PIN" :
3591 	       "MSR_IA32_VMX_PINBASED_CTLS", ctrl_pin_rev.val);
3592 	for (bit = 0; bit < 32; bit++)
3593 		test_rsvd_ctl_bit("pin-based controls",
3594 				  ctrl_pin_rev, PIN_CONTROLS, bit);
3595 }
3596 
3597 /*
3598  * Reserved bits in the primary processor-based VM-execution controls
3599  * must be set properly. Software may consult the VMX capability MSRs
3600  * to determine the proper settings.
3601  * [Intel SDM]
3602  */
3603 static void test_primary_processor_based_ctls(void)
3604 {
3605 	unsigned bit;
3606 
3607 	printf("\n%s: %lx\n", basic.ctrl ? "MSR_IA32_VMX_TRUE_PROC" :
3608 	       "MSR_IA32_VMX_PROCBASED_CTLS", ctrl_cpu_rev[0].val);
3609 	for (bit = 0; bit < 32; bit++)
3610 		test_rsvd_ctl_bit("primary processor-based controls",
3611 				  ctrl_cpu_rev[0], CPU_EXEC_CTRL0, bit);
3612 }
3613 
3614 /*
3615  * If the "activate secondary controls" primary processor-based
3616  * VM-execution control is 1, reserved bits in the secondary
3617  * processor-based VM-execution controls must be cleared. Software may
3618  * consult the VMX capability MSRs to determine which bits are
3619  * reserved.
3620  * If the "activate secondary controls" primary processor-based
3621  * VM-execution control is 0 (or if the processor does not support the
3622  * 1-setting of that control), no checks are performed on the
3623  * secondary processor-based VM-execution controls.
3624  * [Intel SDM]
3625  */
3626 static void test_secondary_processor_based_ctls(void)
3627 {
3628 	u32 primary;
3629 	u32 secondary;
3630 	unsigned bit;
3631 
3632 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY))
3633 		return;
3634 
3635 	primary = vmcs_read(CPU_EXEC_CTRL0);
3636 	secondary = vmcs_read(CPU_EXEC_CTRL1);
3637 
3638 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3639 	printf("\nMSR_IA32_VMX_PROCBASED_CTLS2: %lx\n", ctrl_cpu_rev[1].val);
3640 	for (bit = 0; bit < 32; bit++)
3641 		test_rsvd_ctl_bit("secondary processor-based controls",
3642 				  ctrl_cpu_rev[1], CPU_EXEC_CTRL1, bit);
3643 
3644 	/*
3645 	 * When the "activate secondary controls" VM-execution control
3646 	 * is clear, there are no checks on the secondary controls.
3647 	 */
3648 	vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3649 	vmcs_write(CPU_EXEC_CTRL1, ~0);
3650 	report(vmlaunch_succeeds(),
3651 	       "Secondary processor-based controls ignored");
3652 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3653 	vmcs_write(CPU_EXEC_CTRL0, primary);
3654 }
3655 
3656 static void try_cr3_target_count(unsigned i, unsigned max)
3657 {
3658 	report_prefix_pushf("CR3 target count 0x%x", i);
3659 	vmcs_write(CR3_TARGET_COUNT, i);
3660 	if (i <= max)
3661 		test_vmx_valid_controls();
3662 	else
3663 		test_vmx_invalid_controls();
3664 	report_prefix_pop();
3665 }
3666 
3667 /*
3668  * The CR3-target count must not be greater than 4. Future processors
3669  * may support a different number of CR3-target values. Software
3670  * should read the VMX capability MSR IA32_VMX_MISC to determine the
3671  * number of values supported.
3672  * [Intel SDM]
3673  */
3674 static void test_cr3_targets(void)
3675 {
3676 	unsigned supported_targets = (rdmsr(MSR_IA32_VMX_MISC) >> 16) & 0x1ff;
3677 	u32 cr3_targets = vmcs_read(CR3_TARGET_COUNT);
3678 	unsigned i;
3679 
3680 	printf("\nSupported CR3 targets: %d\n", supported_targets);
3681 	TEST_ASSERT(supported_targets <= 256);
3682 
3683 	try_cr3_target_count(-1u, supported_targets);
3684 	try_cr3_target_count(0x80000000, supported_targets);
3685 	try_cr3_target_count(0x7fffffff, supported_targets);
3686 	for (i = 0; i <= supported_targets + 1; i++)
3687 		try_cr3_target_count(i, supported_targets);
3688 	vmcs_write(CR3_TARGET_COUNT, cr3_targets);
3689 
3690 	/* VMWRITE to nonexistent target fields should fail. */
3691 	for (i = supported_targets; i < 256; i++)
3692 		TEST_ASSERT(vmcs_write(CR3_TARGET_0 + i*2, 0));
3693 }
3694 
3695 /*
3696  * Test a particular address setting in the VMCS
3697  */
3698 static void test_vmcs_addr(const char *name,
3699 			   enum Encoding encoding,
3700 			   u64 align,
3701 			   bool ignored,
3702 			   bool skip_beyond_mapped_ram,
3703 			   u64 addr)
3704 {
3705 	report_prefix_pushf("%s = %lx", name, addr);
3706 	vmcs_write(encoding, addr);
3707 	if (skip_beyond_mapped_ram &&
3708 	    addr > fwcfg_get_u64(FW_CFG_RAM_SIZE) - align &&
3709 	    addr < (1ul << cpuid_maxphyaddr()))
3710 		printf("Skipping physical address beyond mapped RAM\n");
3711 	else if (ignored || (IS_ALIGNED(addr, align) &&
3712 	    addr < (1ul << cpuid_maxphyaddr())))
3713 		test_vmx_valid_controls();
3714 	else
3715 		test_vmx_invalid_controls();
3716 	report_prefix_pop();
3717 }
3718 
3719 /*
3720  * Test interesting values for a VMCS address
3721  */
3722 static void test_vmcs_addr_values(const char *name,
3723 				  enum Encoding encoding,
3724 				  u64 align,
3725 				  bool ignored,
3726 				  bool skip_beyond_mapped_ram,
3727 				  u32 bit_start, u32 bit_end)
3728 {
3729 	unsigned i;
3730 	u64 orig_val = vmcs_read(encoding);
3731 
3732 	for (i = bit_start; i <= bit_end; i++)
3733 		test_vmcs_addr(name, encoding, align, ignored,
3734 			       skip_beyond_mapped_ram, 1ul << i);
3735 
3736 	test_vmcs_addr(name, encoding, align, ignored,
3737 		       skip_beyond_mapped_ram, PAGE_SIZE - 1);
3738 	test_vmcs_addr(name, encoding, align, ignored,
3739 		       skip_beyond_mapped_ram, PAGE_SIZE);
3740 	test_vmcs_addr(name, encoding, align, ignored,
3741 		       skip_beyond_mapped_ram,
3742 		      (1ul << cpuid_maxphyaddr()) - PAGE_SIZE);
3743 	test_vmcs_addr(name, encoding, align, ignored,
3744 		       skip_beyond_mapped_ram, -1ul);
3745 
3746 	vmcs_write(encoding, orig_val);
3747 }
3748 
3749 /*
3750  * Test a physical address reference in the VMCS, when the corresponding
3751  * feature is enabled and when the corresponding feature is disabled.
3752  */
3753 static void test_vmcs_addr_reference(u32 control_bit, enum Encoding field,
3754 				     const char *field_name,
3755 				     const char *control_name, u64 align,
3756 				     bool skip_beyond_mapped_ram,
3757 				     bool control_primary)
3758 {
3759 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
3760 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
3761 	u64 page_addr;
3762 
3763 	if (control_primary) {
3764 		if (!(ctrl_cpu_rev[0].clr & control_bit))
3765 			return;
3766 	} else {
3767 		if (!(ctrl_cpu_rev[1].clr & control_bit))
3768 			return;
3769 	}
3770 
3771 	page_addr = vmcs_read(field);
3772 
3773 	report_prefix_pushf("%s enabled", control_name);
3774 	if (control_primary) {
3775 		vmcs_write(CPU_EXEC_CTRL0, primary | control_bit);
3776 	} else {
3777 		vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3778 		vmcs_write(CPU_EXEC_CTRL1, secondary | control_bit);
3779 	}
3780 
3781 	test_vmcs_addr_values(field_name, field, align, false,
3782 			      skip_beyond_mapped_ram, 0, 63);
3783 	report_prefix_pop();
3784 
3785 	report_prefix_pushf("%s disabled", control_name);
3786 	if (control_primary) {
3787 		vmcs_write(CPU_EXEC_CTRL0, primary & ~control_bit);
3788 	} else {
3789 		vmcs_write(CPU_EXEC_CTRL0, primary & ~CPU_SECONDARY);
3790 		vmcs_write(CPU_EXEC_CTRL1, secondary & ~control_bit);
3791 	}
3792 
3793 	test_vmcs_addr_values(field_name, field, align, true, false, 0, 63);
3794 	report_prefix_pop();
3795 
3796 	vmcs_write(field, page_addr);
3797 	vmcs_write(CPU_EXEC_CTRL0, primary);
3798 	vmcs_write(CPU_EXEC_CTRL1, secondary);
3799 }
3800 
3801 /*
3802  * If the "use I/O bitmaps" VM-execution control is 1, bits 11:0 of
3803  * each I/O-bitmap address must be 0. Neither address should set any
3804  * bits beyond the processor's physical-address width.
3805  * [Intel SDM]
3806  */
3807 static void test_io_bitmaps(void)
3808 {
3809 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_A,
3810 				 "I/O bitmap A", "Use I/O bitmaps",
3811 				 PAGE_SIZE, false, true);
3812 	test_vmcs_addr_reference(CPU_IO_BITMAP, IO_BITMAP_B,
3813 				 "I/O bitmap B", "Use I/O bitmaps",
3814 				 PAGE_SIZE, false, true);
3815 }
3816 
3817 /*
3818  * If the "use MSR bitmaps" VM-execution control is 1, bits 11:0 of
3819  * the MSR-bitmap address must be 0. The address should not set any
3820  * bits beyond the processor's physical-address width.
3821  * [Intel SDM]
3822  */
3823 static void test_msr_bitmap(void)
3824 {
3825 	test_vmcs_addr_reference(CPU_MSR_BITMAP, MSR_BITMAP,
3826 				 "MSR bitmap", "Use MSR bitmaps",
3827 				 PAGE_SIZE, false, true);
3828 }
3829 
3830 /*
3831  * If the "use TPR shadow" VM-execution control is 1, the virtual-APIC
3832  * address must satisfy the following checks:
3833  * - Bits 11:0 of the address must be 0.
3834  * - The address should not set any bits beyond the processor's
3835  *   physical-address width.
3836  * [Intel SDM]
3837  */
3838 static void test_apic_virt_addr(void)
3839 {
3840 	/*
3841 	 * Ensure the processor will never use the virtual-APIC page, since
3842 	 * we will point it to invalid RAM.  Otherwise KVM is puzzled about
3843 	 * what we're trying to achieve and fails vmentry.
3844 	 */
3845 	u32 cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
3846 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0 | CPU_CR8_LOAD | CPU_CR8_STORE);
3847 	test_vmcs_addr_reference(CPU_TPR_SHADOW, APIC_VIRT_ADDR,
3848 				 "virtual-APIC address", "Use TPR shadow",
3849 				 PAGE_SIZE, false, true);
3850 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
3851 }
3852 
3853 /*
3854  * If the "virtualize APIC-accesses" VM-execution control is 1, the
3855  * APIC-access address must satisfy the following checks:
3856  *  - Bits 11:0 of the address must be 0.
3857  *  - The address should not set any bits beyond the processor's
3858  *    physical-address width.
3859  * [Intel SDM]
3860  */
3861 static void test_apic_access_addr(void)
3862 {
3863 	void *apic_access_page = alloc_page();
3864 
3865 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_page));
3866 
3867 	test_vmcs_addr_reference(CPU_VIRT_APIC_ACCESSES, APIC_ACCS_ADDR,
3868 				 "APIC-access address",
3869 				 "virtualize APIC-accesses", PAGE_SIZE,
3870 				 true, false);
3871 }
3872 
3873 static bool set_bit_pattern(u8 mask, u32 *secondary)
3874 {
3875 	u8 i;
3876 	bool flag = false;
3877 	u32 test_bits[3] = {
3878 		CPU_VIRT_X2APIC,
3879 		CPU_APIC_REG_VIRT,
3880 		CPU_VINTD
3881 	};
3882 
3883         for (i = 0; i < ARRAY_SIZE(test_bits); i++) {
3884 		if ((mask & (1u << i)) &&
3885 		    (ctrl_cpu_rev[1].clr & test_bits[i])) {
3886 			*secondary |= test_bits[i];
3887 			flag = true;
3888 		}
3889 	}
3890 
3891 	return (flag);
3892 }
3893 
3894 /*
3895  * If the "use TPR shadow" VM-execution control is 0, the following
3896  * VM-execution controls must also be 0:
3897  * 	- virtualize x2APIC mode
3898  *	- APIC-register virtualization
3899  *	- virtual-interrupt delivery
3900  *    [Intel SDM]
3901  *
3902  * 2. If the "virtualize x2APIC mode" VM-execution control is 1, the
3903  *    "virtualize APIC accesses" VM-execution control must be 0.
3904  *    [Intel SDM]
3905  */
3906 static void test_apic_virtual_ctls(void)
3907 {
3908 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
3909 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
3910 	u32 primary = saved_primary;
3911 	u32 secondary = saved_secondary;
3912 	bool ctrl = false;
3913 	char str[10] = "disabled";
3914 	u8 i = 0, j;
3915 
3916 	/*
3917 	 * First test
3918 	 */
3919 	if (!((ctrl_cpu_rev[0].clr & (CPU_SECONDARY | CPU_TPR_SHADOW)) ==
3920 	    (CPU_SECONDARY | CPU_TPR_SHADOW)))
3921 		return;
3922 
3923 	primary |= CPU_SECONDARY;
3924 	primary &= ~CPU_TPR_SHADOW;
3925 	vmcs_write(CPU_EXEC_CTRL0, primary);
3926 
3927 	while (1) {
3928 		for (j = 1; j < 8; j++) {
3929 			secondary &= ~(CPU_VIRT_X2APIC | CPU_APIC_REG_VIRT | CPU_VINTD);
3930 			if (primary & CPU_TPR_SHADOW) {
3931 				ctrl = true;
3932 			} else {
3933 				if (! set_bit_pattern(j, &secondary))
3934 					ctrl = true;
3935 				else
3936 					ctrl = false;
3937 			}
3938 
3939 			vmcs_write(CPU_EXEC_CTRL1, secondary);
3940 			report_prefix_pushf("Use TPR shadow %s, virtualize x2APIC mode %s, APIC-register virtualization %s, virtual-interrupt delivery %s",
3941 				str, (secondary & CPU_VIRT_X2APIC) ? "enabled" : "disabled", (secondary & CPU_APIC_REG_VIRT) ? "enabled" : "disabled", (secondary & CPU_VINTD) ? "enabled" : "disabled");
3942 			if (ctrl)
3943 				test_vmx_valid_controls();
3944 			else
3945 				test_vmx_invalid_controls();
3946 			report_prefix_pop();
3947 		}
3948 
3949 		if (i == 1)
3950 			break;
3951 		i++;
3952 
3953 		primary |= CPU_TPR_SHADOW;
3954 		vmcs_write(CPU_EXEC_CTRL0, primary);
3955 		strcpy(str, "enabled");
3956 	}
3957 
3958 	/*
3959 	 * Second test
3960 	 */
3961 	u32 apic_virt_ctls = (CPU_VIRT_X2APIC | CPU_VIRT_APIC_ACCESSES);
3962 
3963 	primary = saved_primary;
3964 	secondary = saved_secondary;
3965 	if (!((ctrl_cpu_rev[1].clr & apic_virt_ctls) == apic_virt_ctls))
3966 		return;
3967 
3968 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY);
3969 	secondary &= ~CPU_VIRT_APIC_ACCESSES;
3970 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_X2APIC);
3971 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access disabled");
3972 	test_vmx_valid_controls();
3973 	report_prefix_pop();
3974 
3975 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_APIC_ACCESSES);
3976 	report_prefix_pushf("Virtualize x2APIC mode disabled; virtualize APIC access enabled");
3977 	test_vmx_valid_controls();
3978 	report_prefix_pop();
3979 
3980 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VIRT_X2APIC);
3981 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access enabled");
3982 	test_vmx_invalid_controls();
3983 	report_prefix_pop();
3984 
3985 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VIRT_APIC_ACCESSES);
3986 	report_prefix_pushf("Virtualize x2APIC mode enabled; virtualize APIC access disabled");
3987 	test_vmx_valid_controls();
3988 	report_prefix_pop();
3989 
3990 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
3991 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
3992 }
3993 
3994 /*
3995  * If the "virtual-interrupt delivery" VM-execution control is 1, the
3996  * "external-interrupt exiting" VM-execution control must be 1.
3997  * [Intel SDM]
3998  */
3999 static void test_virtual_intr_ctls(void)
4000 {
4001 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
4002 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
4003 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4004 	u32 primary = saved_primary;
4005 	u32 secondary = saved_secondary;
4006 	u32 pin = saved_pin;
4007 
4008 	if (!((ctrl_cpu_rev[1].clr & CPU_VINTD) &&
4009 	    (ctrl_pin_rev.clr & PIN_EXTINT)))
4010 		return;
4011 
4012 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
4013 	vmcs_write(CPU_EXEC_CTRL1, secondary & ~CPU_VINTD);
4014 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
4015 	report_prefix_pushf("Virtualize interrupt-delivery disabled; external-interrupt exiting disabled");
4016 	test_vmx_valid_controls();
4017 	report_prefix_pop();
4018 
4019 	vmcs_write(CPU_EXEC_CTRL1, secondary | CPU_VINTD);
4020 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
4021 	test_vmx_invalid_controls();
4022 	report_prefix_pop();
4023 
4024 	vmcs_write(PIN_CONTROLS, pin | PIN_EXTINT);
4025 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting enabled");
4026 	test_vmx_valid_controls();
4027 	report_prefix_pop();
4028 
4029 	vmcs_write(PIN_CONTROLS, pin & ~PIN_EXTINT);
4030 	report_prefix_pushf("Virtualize interrupt-delivery enabled; external-interrupt exiting disabled");
4031 	test_vmx_invalid_controls();
4032 	report_prefix_pop();
4033 
4034 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
4035 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
4036 	vmcs_write(PIN_CONTROLS, saved_pin);
4037 }
4038 
4039 static void test_pi_desc_addr(u64 addr, bool ctrl)
4040 {
4041 	vmcs_write(POSTED_INTR_DESC_ADDR, addr);
4042 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-descriptor-address 0x%lx", addr);
4043 	if (ctrl)
4044 		test_vmx_valid_controls();
4045 	else
4046 		test_vmx_invalid_controls();
4047 	report_prefix_pop();
4048 }
4049 
4050 /*
4051  * If the “process posted interrupts†VM-execution control is 1, the
4052  * following must be true:
4053  *
4054  *	- The “virtual-interrupt delivery†VM-execution control is 1.
4055  *	- The “acknowledge interrupt on exit†VM-exit control is 1.
4056  *	- The posted-interrupt notification vector has a value in the
4057  *	- range 0–255 (bits 15:8 are all 0).
4058  *	- Bits 5:0 of the posted-interrupt descriptor address are all 0.
4059  *	- The posted-interrupt descriptor address does not set any bits
4060  *	  beyond the processor's physical-address width.
4061  * [Intel SDM]
4062  */
4063 static void test_posted_intr(void)
4064 {
4065 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
4066 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
4067 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4068 	u32 exit_ctl_saved = vmcs_read(EXI_CONTROLS);
4069 	u32 primary = saved_primary;
4070 	u32 secondary = saved_secondary;
4071 	u32 pin = saved_pin;
4072 	u32 exit_ctl = exit_ctl_saved;
4073 	u16 vec;
4074 	int i;
4075 
4076 	if (!((ctrl_pin_rev.clr & PIN_POST_INTR) &&
4077 	    (ctrl_cpu_rev[1].clr & CPU_VINTD) &&
4078 	    (ctrl_exit_rev.clr & EXI_INTA)))
4079 		return;
4080 
4081 	vmcs_write(CPU_EXEC_CTRL0, primary | CPU_SECONDARY | CPU_TPR_SHADOW);
4082 
4083 	/*
4084 	 * Test virtual-interrupt-delivery and acknowledge-interrupt-on-exit
4085 	 */
4086 	pin |= PIN_POST_INTR;
4087 	vmcs_write(PIN_CONTROLS, pin);
4088 	secondary &= ~CPU_VINTD;
4089 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4090 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled");
4091 	test_vmx_invalid_controls();
4092 	report_prefix_pop();
4093 
4094 	secondary |= CPU_VINTD;
4095 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4096 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled");
4097 	test_vmx_invalid_controls();
4098 	report_prefix_pop();
4099 
4100 	exit_ctl &= ~EXI_INTA;
4101 	vmcs_write(EXI_CONTROLS, exit_ctl);
4102 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit disabled");
4103 	test_vmx_invalid_controls();
4104 	report_prefix_pop();
4105 
4106 	exit_ctl |= EXI_INTA;
4107 	vmcs_write(EXI_CONTROLS, exit_ctl);
4108 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
4109 	test_vmx_valid_controls();
4110 	report_prefix_pop();
4111 
4112 	secondary &= ~CPU_VINTD;
4113 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4114 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery disabled; acknowledge-interrupt-on-exit enabled");
4115 	test_vmx_invalid_controls();
4116 	report_prefix_pop();
4117 
4118 	secondary |= CPU_VINTD;
4119 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4120 	report_prefix_pushf("Process-posted-interrupts enabled; virtual-interrupt-delivery enabled; acknowledge-interrupt-on-exit enabled");
4121 	test_vmx_valid_controls();
4122 	report_prefix_pop();
4123 
4124 	/*
4125 	 * Test posted-interrupt notification vector
4126 	 */
4127 	for (i = 0; i < 8; i++) {
4128 		vec = (1ul << i);
4129 		vmcs_write(PINV, vec);
4130 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4131 		test_vmx_valid_controls();
4132 		report_prefix_pop();
4133 	}
4134 	for (i = 8; i < 16; i++) {
4135 		vec = (1ul << i);
4136 		vmcs_write(PINV, vec);
4137 		report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4138 		test_vmx_invalid_controls();
4139 		report_prefix_pop();
4140 	}
4141 
4142 	vec &= ~(0xff << 8);
4143 	vmcs_write(PINV, vec);
4144 	report_prefix_pushf("Process-posted-interrupts enabled; posted-interrupt-notification-vector %u", vec);
4145 	test_vmx_valid_controls();
4146 	report_prefix_pop();
4147 
4148 	/*
4149 	 * Test posted-interrupt descriptor addresss
4150 	 */
4151 	for (i = 0; i < 6; i++) {
4152 		test_pi_desc_addr(1ul << i, false);
4153 	}
4154 
4155 	test_pi_desc_addr(0xf0, false);
4156 	test_pi_desc_addr(0xff, false);
4157 	test_pi_desc_addr(0x0f, false);
4158 	test_pi_desc_addr(0x8000, true);
4159 	test_pi_desc_addr(0x00, true);
4160 	test_pi_desc_addr(0xc000, true);
4161 
4162 	test_vmcs_addr_values("process-posted interrupts",
4163 			       POSTED_INTR_DESC_ADDR, 64,
4164 			       false, false, 0, 63);
4165 
4166 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
4167 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
4168 	vmcs_write(PIN_CONTROLS, saved_pin);
4169 }
4170 
4171 static void test_apic_ctls(void)
4172 {
4173 	test_apic_virt_addr();
4174 	test_apic_access_addr();
4175 	test_apic_virtual_ctls();
4176 	test_virtual_intr_ctls();
4177 	test_posted_intr();
4178 }
4179 
4180 /*
4181  * If the “enable VPID†VM-execution control is 1, the value of the
4182  * of the VPID VM-execution control field must not be 0000H.
4183  * [Intel SDM]
4184  */
4185 static void test_vpid(void)
4186 {
4187 	u32 saved_primary = vmcs_read(CPU_EXEC_CTRL0);
4188 	u32 saved_secondary = vmcs_read(CPU_EXEC_CTRL1);
4189 	u16 vpid = 0x0000;
4190 	int i;
4191 
4192 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4193 	    (ctrl_cpu_rev[1].clr & CPU_VPID))) {
4194 		printf("Secondary controls and/or VPID not supported\n");
4195 		return;
4196 	}
4197 
4198 	vmcs_write(CPU_EXEC_CTRL0, saved_primary | CPU_SECONDARY);
4199 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary & ~CPU_VPID);
4200 	vmcs_write(VPID, vpid);
4201 	report_prefix_pushf("VPID disabled; VPID value %x", vpid);
4202 	test_vmx_valid_controls();
4203 	report_prefix_pop();
4204 
4205 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary | CPU_VPID);
4206 	report_prefix_pushf("VPID enabled; VPID value %x", vpid);
4207 	test_vmx_invalid_controls();
4208 	report_prefix_pop();
4209 
4210 	for (i = 0; i < 16; i++) {
4211 		vpid = (short)1 << i;;
4212 		vmcs_write(VPID, vpid);
4213 		report_prefix_pushf("VPID enabled; VPID value %x", vpid);
4214 		test_vmx_valid_controls();
4215 		report_prefix_pop();
4216 	}
4217 
4218 	vmcs_write(CPU_EXEC_CTRL0, saved_primary);
4219 	vmcs_write(CPU_EXEC_CTRL1, saved_secondary);
4220 }
4221 
4222 static void set_vtpr(unsigned vtpr)
4223 {
4224 	*(u32 *)phys_to_virt(vmcs_read(APIC_VIRT_ADDR) + APIC_TASKPRI) = vtpr;
4225 }
4226 
4227 static void try_tpr_threshold_and_vtpr(unsigned threshold, unsigned vtpr)
4228 {
4229 	bool valid = true;
4230 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4231 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4232 
4233 	if ((primary & CPU_TPR_SHADOW) &&
4234 	    (!(primary & CPU_SECONDARY) ||
4235 	     !(secondary & (CPU_VINTD | CPU_VIRT_APIC_ACCESSES))))
4236 		valid = (threshold & 0xf) <= ((vtpr >> 4) & 0xf);
4237 
4238 	set_vtpr(vtpr);
4239 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0x%x",
4240 	    threshold, (vtpr >> 4) & 0xf);
4241 	if (valid)
4242 		test_vmx_valid_controls();
4243 	else
4244 		test_vmx_invalid_controls();
4245 	report_prefix_pop();
4246 }
4247 
4248 static void test_invalid_event_injection(void)
4249 {
4250 	u32 ent_intr_info_save = vmcs_read(ENT_INTR_INFO);
4251 	u32 ent_intr_error_save = vmcs_read(ENT_INTR_ERROR);
4252 	u32 ent_inst_len_save = vmcs_read(ENT_INST_LEN);
4253 	u32 primary_save = vmcs_read(CPU_EXEC_CTRL0);
4254 	u32 secondary_save = vmcs_read(CPU_EXEC_CTRL1);
4255 	u64 guest_cr0_save = vmcs_read(GUEST_CR0);
4256 	u32 ent_intr_info_base = INTR_INFO_VALID_MASK;
4257 	u32 ent_intr_info, ent_intr_err, ent_intr_len;
4258 	u32 cnt;
4259 
4260 	/* Setup */
4261 	report_prefix_push("invalid event injection");
4262 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4263 	vmcs_write(ENT_INST_LEN, 0x00000001);
4264 
4265 	/* The field’s interruption type is not set to a reserved value. */
4266 	ent_intr_info = ent_intr_info_base | INTR_TYPE_RESERVED | DE_VECTOR;
4267 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4268 			    "RESERVED interruption type invalid [-]",
4269 			    ent_intr_info);
4270 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4271 	test_vmx_invalid_controls();
4272 	report_prefix_pop();
4273 
4274 	ent_intr_info = ent_intr_info_base | INTR_TYPE_EXT_INTR |
4275 			DE_VECTOR;
4276 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4277 			    "RESERVED interruption type invalid [+]",
4278 			    ent_intr_info);
4279 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4280 	test_vmx_valid_controls();
4281 	report_prefix_pop();
4282 
4283 	/* If the interruption type is other event, the vector is 0. */
4284 	ent_intr_info = ent_intr_info_base | INTR_TYPE_OTHER_EVENT | DB_VECTOR;
4285 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4286 			    "(OTHER EVENT && vector != 0) invalid [-]",
4287 			    ent_intr_info);
4288 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4289 	test_vmx_invalid_controls();
4290 	report_prefix_pop();
4291 
4292 	/* If the interruption type is NMI, the vector is 2 (negative case). */
4293 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | DE_VECTOR;
4294 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4295 			    "(NMI && vector != 2) invalid [-]", ent_intr_info);
4296 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4297 	test_vmx_invalid_controls();
4298 	report_prefix_pop();
4299 
4300 	/* If the interruption type is NMI, the vector is 2 (positive case). */
4301 	ent_intr_info = ent_intr_info_base | INTR_TYPE_NMI_INTR | NMI_VECTOR;
4302 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4303 			    "(NMI && vector == 2) valid [+]", ent_intr_info);
4304 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4305 	test_vmx_valid_controls();
4306 	report_prefix_pop();
4307 
4308 	/*
4309 	 * If the interruption type
4310 	 * is HW exception, the vector is at most 31.
4311 	 */
4312 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION | 0x20;
4313 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4314 			    "(HW exception && vector > 31) invalid [-]",
4315 			    ent_intr_info);
4316 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4317 	test_vmx_invalid_controls();
4318 	report_prefix_pop();
4319 
4320 	/*
4321 	 * deliver-error-code is 1 iff either
4322 	 * (a) the "unrestricted guest" VM-execution control is 0
4323 	 * (b) CR0.PE is set.
4324 	 */
4325 
4326 	/* Assert that unrestricted guest is disabled or unsupported */
4327 	assert(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
4328 	       !(secondary_save & CPU_URG));
4329 
4330 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4331 			GP_VECTOR;
4332 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4333 			    "error code <-> (!URG || prot_mode) [-]",
4334 			    ent_intr_info);
4335 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4336 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4337 	test_vmx_invalid_controls();
4338 	report_prefix_pop();
4339 
4340 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4341 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4342 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4343 			    "error code <-> (!URG || prot_mode) [+]",
4344 			    ent_intr_info);
4345 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4346 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4347 	test_vmx_valid_controls();
4348 	report_prefix_pop();
4349 
4350 	if (enable_unrestricted_guest())
4351 		goto skip_unrestricted_guest;
4352 
4353 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4354 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4355 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4356 			    "error code <-> (!URG || prot_mode) [-]",
4357 			    ent_intr_info);
4358 	vmcs_write(GUEST_CR0, guest_cr0_save & ~X86_CR0_PE & ~X86_CR0_PG);
4359 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4360 	test_vmx_invalid_controls();
4361 	report_prefix_pop();
4362 
4363 	ent_intr_info = ent_intr_info_base | INTR_TYPE_HARD_EXCEPTION |
4364 			GP_VECTOR;
4365 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4366 			    "error code <-> (!URG || prot_mode) [-]",
4367 			    ent_intr_info);
4368 	vmcs_write(GUEST_CR0, guest_cr0_save | X86_CR0_PE);
4369 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4370 	test_vmx_invalid_controls();
4371 	report_prefix_pop();
4372 
4373 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4374 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4375 
4376 skip_unrestricted_guest:
4377 	vmcs_write(GUEST_CR0, guest_cr0_save);
4378 
4379 	/* deliver-error-code is 1 iff the interruption type is HW exception */
4380 	report_prefix_push("error code <-> HW exception");
4381 	for (cnt = 0; cnt < 8; cnt++) {
4382 		u32 exception_type_mask = cnt << 8;
4383 		u32 deliver_error_code_mask =
4384 			exception_type_mask != INTR_TYPE_HARD_EXCEPTION ?
4385 			INTR_INFO_DELIVER_CODE_MASK : 0;
4386 
4387 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4388 				exception_type_mask | GP_VECTOR;
4389 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4390 				    ent_intr_info);
4391 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4392 		test_vmx_invalid_controls();
4393 		report_prefix_pop();
4394 	}
4395 	report_prefix_pop();
4396 
4397 	/*
4398 	 * deliver-error-code is 1 iff the the vector
4399 	 * indicates an exception that would normally deliver an error code
4400 	 */
4401 	report_prefix_push("error code <-> vector delivers error code");
4402 	for (cnt = 0; cnt < 32; cnt++) {
4403 		bool has_error_code = false;
4404 		u32 deliver_error_code_mask;
4405 
4406 		switch (cnt) {
4407 		case DF_VECTOR:
4408 		case TS_VECTOR:
4409 		case NP_VECTOR:
4410 		case SS_VECTOR:
4411 		case GP_VECTOR:
4412 		case PF_VECTOR:
4413 		case AC_VECTOR:
4414 			has_error_code = true;
4415 		}
4416 
4417 		/* Negative case */
4418 		deliver_error_code_mask = has_error_code ?
4419 						0 :
4420 						INTR_INFO_DELIVER_CODE_MASK;
4421 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4422 				INTR_TYPE_HARD_EXCEPTION | cnt;
4423 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4424 				    ent_intr_info);
4425 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4426 		test_vmx_invalid_controls();
4427 		report_prefix_pop();
4428 
4429 		/* Positive case */
4430 		deliver_error_code_mask = has_error_code ?
4431 						INTR_INFO_DELIVER_CODE_MASK :
4432 						0;
4433 		ent_intr_info = ent_intr_info_base | deliver_error_code_mask |
4434 				INTR_TYPE_HARD_EXCEPTION | cnt;
4435 		report_prefix_pushf("VM-entry intr info=0x%x [+]",
4436 				    ent_intr_info);
4437 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4438 		test_vmx_valid_controls();
4439 		report_prefix_pop();
4440 	}
4441 	report_prefix_pop();
4442 
4443 	/* Reserved bits in the field (30:12) are 0. */
4444 	report_prefix_push("reserved bits clear");
4445 	for (cnt = 12; cnt <= 30; cnt++) {
4446 		ent_intr_info = ent_intr_info_base |
4447 				INTR_INFO_DELIVER_CODE_MASK |
4448 				INTR_TYPE_HARD_EXCEPTION | GP_VECTOR |
4449 				(1U << cnt);
4450 		report_prefix_pushf("VM-entry intr info=0x%x [-]",
4451 				    ent_intr_info);
4452 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4453 		test_vmx_invalid_controls();
4454 		report_prefix_pop();
4455 	}
4456 	report_prefix_pop();
4457 
4458 	/*
4459 	 * If deliver-error-code is 1
4460 	 * bits 31:16 of the VM-entry exception error-code field are 0.
4461 	 */
4462 	ent_intr_info = ent_intr_info_base | INTR_INFO_DELIVER_CODE_MASK |
4463 			INTR_TYPE_HARD_EXCEPTION | GP_VECTOR;
4464 	report_prefix_pushf("%s, VM-entry intr info=0x%x",
4465 			    "VM-entry exception error code[31:16] clear",
4466 			    ent_intr_info);
4467 	vmcs_write(ENT_INTR_INFO, ent_intr_info);
4468 	for (cnt = 16; cnt <= 31; cnt++) {
4469 		ent_intr_err = 1U << cnt;
4470 		report_prefix_pushf("VM-entry intr error=0x%x [-]",
4471 				    ent_intr_err);
4472 		vmcs_write(ENT_INTR_ERROR, ent_intr_err);
4473 		test_vmx_invalid_controls();
4474 		report_prefix_pop();
4475 	}
4476 	vmcs_write(ENT_INTR_ERROR, 0x00000000);
4477 	report_prefix_pop();
4478 
4479 	/*
4480 	 * If the interruption type is software interrupt, software exception,
4481 	 * or privileged software exception, the VM-entry instruction-length
4482 	 * field is in the range 0–15.
4483 	 */
4484 
4485 	for (cnt = 0; cnt < 3; cnt++) {
4486 		switch (cnt) {
4487 		case 0:
4488 			ent_intr_info = ent_intr_info_base |
4489 					INTR_TYPE_SOFT_INTR;
4490 			break;
4491 		case 1:
4492 			ent_intr_info = ent_intr_info_base |
4493 					INTR_TYPE_SOFT_EXCEPTION;
4494 			break;
4495 		case 2:
4496 			ent_intr_info = ent_intr_info_base |
4497 					INTR_TYPE_PRIV_SW_EXCEPTION;
4498 			break;
4499 		}
4500 		report_prefix_pushf("%s, VM-entry intr info=0x%x",
4501 				    "VM-entry instruction-length check",
4502 				    ent_intr_info);
4503 		vmcs_write(ENT_INTR_INFO, ent_intr_info);
4504 
4505 		/* Instruction length set to -1 (0xFFFFFFFF) should fail */
4506 		ent_intr_len = -1;
4507 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4508 				    ent_intr_len);
4509 		vmcs_write(ENT_INST_LEN, ent_intr_len);
4510 		test_vmx_invalid_controls();
4511 		report_prefix_pop();
4512 
4513 		/* Instruction length set to 16 should fail */
4514 		ent_intr_len = 0x00000010;
4515 		report_prefix_pushf("VM-entry intr length = 0x%x [-]",
4516 				    ent_intr_len);
4517 		vmcs_write(ENT_INST_LEN, 0x00000010);
4518 		test_vmx_invalid_controls();
4519 		report_prefix_pop();
4520 
4521 		report_prefix_pop();
4522 	}
4523 
4524 	/* Cleanup */
4525 	vmcs_write(ENT_INTR_INFO, ent_intr_info_save);
4526 	vmcs_write(ENT_INTR_ERROR, ent_intr_error_save);
4527 	vmcs_write(ENT_INST_LEN, ent_inst_len_save);
4528 	vmcs_write(CPU_EXEC_CTRL0, primary_save);
4529 	vmcs_write(CPU_EXEC_CTRL1, secondary_save);
4530 	vmcs_write(GUEST_CR0, guest_cr0_save);
4531 	report_prefix_pop();
4532 }
4533 
4534 /*
4535  * Test interesting vTPR values for a given TPR threshold.
4536  */
4537 static void test_vtpr_values(unsigned threshold)
4538 {
4539 	try_tpr_threshold_and_vtpr(threshold, (threshold - 1) << 4);
4540 	try_tpr_threshold_and_vtpr(threshold, threshold << 4);
4541 	try_tpr_threshold_and_vtpr(threshold, (threshold + 1) << 4);
4542 }
4543 
4544 static void try_tpr_threshold(unsigned threshold)
4545 {
4546 	bool valid = true;
4547 
4548 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4549 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4550 
4551 	if ((primary & CPU_TPR_SHADOW) && !((primary & CPU_SECONDARY) &&
4552 	    (secondary & CPU_VINTD)))
4553 		valid = !(threshold >> 4);
4554 
4555 	set_vtpr(-1);
4556 	vmcs_write(TPR_THRESHOLD, threshold);
4557 	report_prefix_pushf("TPR threshold 0x%x, VTPR.class 0xf", threshold);
4558 	if (valid)
4559 		test_vmx_valid_controls();
4560 	else
4561 		test_vmx_invalid_controls();
4562 	report_prefix_pop();
4563 
4564 	if (valid)
4565 		test_vtpr_values(threshold);
4566 }
4567 
4568 /*
4569  * Test interesting TPR threshold values.
4570  */
4571 static void test_tpr_threshold_values(void)
4572 {
4573 	unsigned i;
4574 
4575 	for (i = 0; i < 0x10; i++)
4576 		try_tpr_threshold(i);
4577 	for (i = 4; i < 32; i++)
4578 		try_tpr_threshold(1u << i);
4579 	try_tpr_threshold(-1u);
4580 	try_tpr_threshold(0x7fffffff);
4581 }
4582 
4583 /*
4584  * This test covers the following two VM entry checks:
4585  *
4586  *      i) If the "use TPR shadow" VM-execution control is 1 and the
4587  *         "virtual-interrupt delivery" VM-execution control is 0, bits
4588  *         31:4 of the TPR threshold VM-execution control field must
4589 	   be 0.
4590  *         [Intel SDM]
4591  *
4592  *      ii) If the "use TPR shadow" VM-execution control is 1, the
4593  *          "virtual-interrupt delivery" VM-execution control is 0
4594  *          and the "virtualize APIC accesses" VM-execution control
4595  *          is 0, the value of bits 3:0 of the TPR threshold VM-execution
4596  *          control field must not be greater than the value of bits
4597  *          7:4 of VTPR.
4598  *          [Intel SDM]
4599  */
4600 static void test_tpr_threshold(void)
4601 {
4602 	u32 primary = vmcs_read(CPU_EXEC_CTRL0);
4603 	u64 apic_virt_addr = vmcs_read(APIC_VIRT_ADDR);
4604 	u64 threshold = vmcs_read(TPR_THRESHOLD);
4605 	void *virtual_apic_page;
4606 
4607 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW))
4608 		return;
4609 
4610 	virtual_apic_page = alloc_page();
4611 	memset(virtual_apic_page, 0xff, PAGE_SIZE);
4612 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
4613 
4614 	vmcs_write(CPU_EXEC_CTRL0, primary & ~(CPU_TPR_SHADOW | CPU_SECONDARY));
4615 	report_prefix_pushf("Use TPR shadow disabled, secondary controls disabled");
4616 	test_tpr_threshold_values();
4617 	report_prefix_pop();
4618 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | CPU_TPR_SHADOW);
4619 	report_prefix_pushf("Use TPR shadow enabled, secondary controls disabled");
4620 	test_tpr_threshold_values();
4621 	report_prefix_pop();
4622 
4623 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4624 	    (ctrl_cpu_rev[1].clr & (CPU_VINTD  | CPU_VIRT_APIC_ACCESSES))))
4625 		goto out;
4626 	u32 secondary = vmcs_read(CPU_EXEC_CTRL1);
4627 
4628 	if (ctrl_cpu_rev[1].clr & CPU_VINTD) {
4629 		vmcs_write(CPU_EXEC_CTRL1, CPU_VINTD);
4630 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4631 		test_tpr_threshold_values();
4632 		report_prefix_pop();
4633 
4634 		vmcs_write(CPU_EXEC_CTRL0,
4635 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4636 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses disabled");
4637 		test_tpr_threshold_values();
4638 		report_prefix_pop();
4639 	}
4640 
4641 	if (ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES) {
4642 		vmcs_write(CPU_EXEC_CTRL0,
4643 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4644 		vmcs_write(CPU_EXEC_CTRL1, CPU_VIRT_APIC_ACCESSES);
4645 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4646 		test_tpr_threshold_values();
4647 		report_prefix_pop();
4648 
4649 		vmcs_write(CPU_EXEC_CTRL0,
4650 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4651 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4652 		test_tpr_threshold_values();
4653 		report_prefix_pop();
4654 	}
4655 
4656 	if ((ctrl_cpu_rev[1].clr &
4657 	     (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) ==
4658 	    (CPU_VINTD | CPU_VIRT_APIC_ACCESSES)) {
4659 		vmcs_write(CPU_EXEC_CTRL0,
4660 			   vmcs_read(CPU_EXEC_CTRL0) & ~CPU_SECONDARY);
4661 		vmcs_write(CPU_EXEC_CTRL1,
4662 			   CPU_VINTD | CPU_VIRT_APIC_ACCESSES);
4663 		report_prefix_pushf("Use TPR shadow enabled; secondary controls disabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4664 		test_tpr_threshold_values();
4665 		report_prefix_pop();
4666 
4667 		vmcs_write(CPU_EXEC_CTRL0,
4668 			   vmcs_read(CPU_EXEC_CTRL0) | CPU_SECONDARY);
4669 		report_prefix_pushf("Use TPR shadow enabled; secondary controls enabled; virtual-interrupt delivery enabled; virtualize APIC accesses enabled");
4670 		test_tpr_threshold_values();
4671 		report_prefix_pop();
4672 	}
4673 
4674 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4675 out:
4676 	vmcs_write(TPR_THRESHOLD, threshold);
4677 	vmcs_write(APIC_VIRT_ADDR, apic_virt_addr);
4678 	vmcs_write(CPU_EXEC_CTRL0, primary);
4679 }
4680 
4681 /*
4682  * This test verifies the following two vmentry checks:
4683  *
4684  *  If the "NMI exiting" VM-execution control is 0, "Virtual NMIs"
4685  *  VM-execution control must be 0.
4686  *  [Intel SDM]
4687  *
4688  *  If the “virtual NMIs” VM-execution control is 0, the “NMI-window
4689  *  exiting” VM-execution control must be 0.
4690  *  [Intel SDM]
4691  */
4692 static void test_nmi_ctrls(void)
4693 {
4694 	u32 pin_ctrls, cpu_ctrls0, test_pin_ctrls, test_cpu_ctrls0;
4695 
4696 	if ((ctrl_pin_rev.clr & (PIN_NMI | PIN_VIRT_NMI)) !=
4697 	    (PIN_NMI | PIN_VIRT_NMI)) {
4698 		printf("NMI exiting and Virtual NMIs are not supported !\n");
4699 		return;
4700 	}
4701 
4702 	/* Save the controls so that we can restore them after our tests */
4703 	pin_ctrls = vmcs_read(PIN_CONTROLS);
4704 	cpu_ctrls0 = vmcs_read(CPU_EXEC_CTRL0);
4705 
4706 	test_pin_ctrls = pin_ctrls & ~(PIN_NMI | PIN_VIRT_NMI);
4707 	test_cpu_ctrls0 = cpu_ctrls0 & ~CPU_NMI_WINDOW;
4708 
4709 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4710 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs disabled");
4711 	test_vmx_valid_controls();
4712 	report_prefix_pop();
4713 
4714 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_VIRT_NMI);
4715 	report_prefix_pushf("NMI-exiting disabled, virtual-NMIs enabled");
4716 	test_vmx_invalid_controls();
4717 	report_prefix_pop();
4718 
4719 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4720 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs enabled");
4721 	test_vmx_valid_controls();
4722 	report_prefix_pop();
4723 
4724 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | PIN_NMI);
4725 	report_prefix_pushf("NMI-exiting enabled, virtual-NMIs disabled");
4726 	test_vmx_valid_controls();
4727 	report_prefix_pop();
4728 
4729 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
4730 		report_info("NMI-window exiting is not supported, skipping...");
4731 		goto done;
4732 	}
4733 
4734 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4735 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4736 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting enabled");
4737 	test_vmx_invalid_controls();
4738 	report_prefix_pop();
4739 
4740 	vmcs_write(PIN_CONTROLS, test_pin_ctrls);
4741 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4742 	report_prefix_pushf("Virtual-NMIs disabled, NMI-window-exiting disabled");
4743 	test_vmx_valid_controls();
4744 	report_prefix_pop();
4745 
4746 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4747 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0 | CPU_NMI_WINDOW);
4748 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting enabled");
4749 	test_vmx_valid_controls();
4750 	report_prefix_pop();
4751 
4752 	vmcs_write(PIN_CONTROLS, test_pin_ctrls | (PIN_NMI | PIN_VIRT_NMI));
4753 	vmcs_write(CPU_EXEC_CTRL0, test_cpu_ctrls0);
4754 	report_prefix_pushf("Virtual-NMIs enabled, NMI-window-exiting disabled");
4755 	test_vmx_valid_controls();
4756 	report_prefix_pop();
4757 
4758 	/* Restore the controls to their original values */
4759 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrls0);
4760 done:
4761 	vmcs_write(PIN_CONTROLS, pin_ctrls);
4762 }
4763 
4764 static void test_eptp_ad_bit(u64 eptp, bool ctrl)
4765 {
4766 	vmcs_write(EPTP, eptp);
4767 	report_prefix_pushf("Enable-EPT enabled; EPT accessed and dirty flag %s",
4768 	    (eptp & EPTP_AD_FLAG) ? "1": "0");
4769 	if (ctrl)
4770 		test_vmx_valid_controls();
4771 	else
4772 		test_vmx_invalid_controls();
4773 	report_prefix_pop();
4774 
4775 }
4776 
4777 /*
4778  * 1. If the "enable EPT" VM-execution control is 1, the "EPTP VM-execution"
4779  *    control field must satisfy the following checks:
4780  *
4781  *     - The EPT memory type (bits 2:0) must be a value supported by the
4782  *	 processor as indicated in the IA32_VMX_EPT_VPID_CAP MSR.
4783  *     - Bits 5:3 (1 less than the EPT page-walk length) must indicate a
4784  *	 supported EPT page-walk length.
4785  *     - Bit 6 (enable bit for accessed and dirty flags for EPT) must be
4786  *	 0 if bit 21 of the IA32_VMX_EPT_VPID_CAP MSR is read as 0,
4787  *	 indicating that the processor does not support accessed and dirty
4788  *	 dirty flags for EPT.
4789  *     - Reserved bits 11:7 and 63:N (where N is the processor's
4790  *	 physical-address width) must all be 0.
4791  *
4792  * 2. If the "unrestricted guest" VM-execution control is 1, the
4793  *    "enable EPT" VM-execution control must also be 1.
4794  */
4795 static void test_ept_eptp(void)
4796 {
4797 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4798 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4799 	u64 eptp_saved = vmcs_read(EPTP);
4800 	u32 primary = primary_saved;
4801 	u32 secondary = secondary_saved;
4802 	u64 msr, eptp = eptp_saved;
4803 	bool un_cache = false;
4804 	bool wr_bk = false;
4805 	bool ctrl;
4806 	u32 i, maxphysaddr;
4807 	u64 j, resv_bits_mask = 0;
4808 
4809 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4810 	    (ctrl_cpu_rev[1].clr & CPU_EPT))) {
4811 		printf("\"CPU secondary\" and/or \"enable EPT\" execution controls are not supported !\n");
4812 		return;
4813 	}
4814 
4815 	/*
4816 	 * Memory type (bits 2:0)
4817 	 */
4818 	msr = rdmsr(MSR_IA32_VMX_EPT_VPID_CAP);
4819 	if (msr & EPT_CAP_UC)
4820 		un_cache = true;
4821 	if (msr & EPT_CAP_WB)
4822 		wr_bk = true;
4823 
4824 	/* Support for 4-level EPT is mandatory. */
4825 	report(msr & EPT_CAP_PWL4, "4-level EPT support check");
4826 
4827 	primary |= CPU_SECONDARY;
4828 	vmcs_write(CPU_EXEC_CTRL0, primary);
4829 	secondary |= CPU_EPT;
4830 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4831 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4832 	    (3ul << EPTP_PG_WALK_LEN_SHIFT);
4833 	vmcs_write(EPTP, eptp);
4834 
4835 	for (i = 0; i < 8; i++) {
4836 		if (i == 0) {
4837 			if (un_cache) {
4838 				report_info("EPT paging structure memory-type is Un-cacheable\n");
4839 				ctrl = true;
4840 			} else {
4841 				ctrl = false;
4842 			}
4843 		} else if (i == 6) {
4844 			if (wr_bk) {
4845 				report_info("EPT paging structure memory-type is Write-back\n");
4846 				ctrl = true;
4847 			} else {
4848 				ctrl = false;
4849 			}
4850 		} else {
4851 			ctrl = false;
4852 		}
4853 
4854 		eptp = (eptp & ~EPT_MEM_TYPE_MASK) | i;
4855 		vmcs_write(EPTP, eptp);
4856 		report_prefix_pushf("Enable-EPT enabled; EPT memory type %lu",
4857 		    eptp & EPT_MEM_TYPE_MASK);
4858 		if (ctrl)
4859 			test_vmx_valid_controls();
4860 		else
4861 			test_vmx_invalid_controls();
4862 		report_prefix_pop();
4863 	}
4864 
4865 	eptp = (eptp & ~EPT_MEM_TYPE_MASK) | 6ul;
4866 
4867 	/*
4868 	 * Page walk length (bits 5:3).  Note, the value in VMCS.EPTP "is 1
4869 	 * less than the EPT page-walk length".
4870 	 */
4871 	for (i = 0; i < 8; i++) {
4872 		eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4873 		    (i << EPTP_PG_WALK_LEN_SHIFT);
4874 		if (i == 3 || (i == 4 && (msr & EPT_CAP_PWL5)))
4875 			ctrl = true;
4876 		else
4877 			ctrl = false;
4878 
4879 		vmcs_write(EPTP, eptp);
4880 		report_prefix_pushf("Enable-EPT enabled; EPT page walk length %lu",
4881 		    eptp & EPTP_PG_WALK_LEN_MASK);
4882 		if (ctrl)
4883 			test_vmx_valid_controls();
4884 		else
4885 			test_vmx_invalid_controls();
4886 		report_prefix_pop();
4887 	}
4888 
4889 	eptp = (eptp & ~EPTP_PG_WALK_LEN_MASK) |
4890 	    3ul << EPTP_PG_WALK_LEN_SHIFT;
4891 
4892 	/*
4893 	 * Accessed and dirty flag (bit 6)
4894 	 */
4895 	if (msr & EPT_CAP_AD_FLAG) {
4896 		report_info("Processor supports accessed and dirty flag");
4897 		eptp &= ~EPTP_AD_FLAG;
4898 		test_eptp_ad_bit(eptp, true);
4899 
4900 		eptp |= EPTP_AD_FLAG;
4901 		test_eptp_ad_bit(eptp, true);
4902 	} else {
4903 		report_info("Processor does not supports accessed and dirty flag");
4904 		eptp &= ~EPTP_AD_FLAG;
4905 		test_eptp_ad_bit(eptp, true);
4906 
4907 		eptp |= EPTP_AD_FLAG;
4908 		test_eptp_ad_bit(eptp, false);
4909 	}
4910 
4911 	/*
4912 	 * Reserved bits [11:7] and [63:N]
4913 	 */
4914 	for (i = 0; i < 32; i++) {
4915 		eptp = (eptp &
4916 		    ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT)) |
4917 		    (i << EPTP_RESERV_BITS_SHIFT);
4918 		vmcs_write(EPTP, eptp);
4919 		report_prefix_pushf("Enable-EPT enabled; reserved bits [11:7] %lu",
4920 		    (eptp >> EPTP_RESERV_BITS_SHIFT) &
4921 		    EPTP_RESERV_BITS_MASK);
4922 		if (i == 0)
4923 			test_vmx_valid_controls();
4924 		else
4925 			test_vmx_invalid_controls();
4926 		report_prefix_pop();
4927 	}
4928 
4929 	eptp = (eptp & ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT));
4930 
4931 	maxphysaddr = cpuid_maxphyaddr();
4932 	for (i = 0; i < (63 - maxphysaddr + 1); i++) {
4933 		resv_bits_mask |= 1ul << i;
4934 	}
4935 
4936 	for (j = maxphysaddr - 1; j <= 63; j++) {
4937 		eptp = (eptp & ~(resv_bits_mask << maxphysaddr)) |
4938 		    (j < maxphysaddr ? 0 : 1ul << j);
4939 		vmcs_write(EPTP, eptp);
4940 		report_prefix_pushf("Enable-EPT enabled; reserved bits [63:N] %lu",
4941 		    (eptp >> maxphysaddr) & resv_bits_mask);
4942 		if (j < maxphysaddr)
4943 			test_vmx_valid_controls();
4944 		else
4945 			test_vmx_invalid_controls();
4946 		report_prefix_pop();
4947 	}
4948 
4949 	secondary &= ~(CPU_EPT | CPU_URG);
4950 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4951 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest disabled");
4952 	test_vmx_valid_controls();
4953 	report_prefix_pop();
4954 
4955 	if (!(ctrl_cpu_rev[1].clr & CPU_URG))
4956 		goto skip_unrestricted_guest;
4957 
4958 	secondary |= CPU_URG;
4959 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4960 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest enabled");
4961 	test_vmx_invalid_controls();
4962 	report_prefix_pop();
4963 
4964 	secondary |= CPU_EPT;
4965 	setup_dummy_ept();
4966 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest enabled");
4967 	test_vmx_valid_controls();
4968 	report_prefix_pop();
4969 
4970 skip_unrestricted_guest:
4971 	secondary &= ~CPU_URG;
4972 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4973 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest disabled");
4974 	test_vmx_valid_controls();
4975 	report_prefix_pop();
4976 
4977 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4978 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4979 	vmcs_write(EPTP, eptp_saved);
4980 }
4981 
4982 /*
4983  * If the 'enable PML' VM-execution control is 1, the 'enable EPT'
4984  * VM-execution control must also be 1. In addition, the PML address
4985  * must satisfy the following checks:
4986  *
4987  *    * Bits 11:0 of the address must be 0.
4988  *    * The address should not set any bits beyond the processor's
4989  *	physical-address width.
4990  *
4991  *  [Intel SDM]
4992  */
4993 static void test_pml(void)
4994 {
4995 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4996 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4997 	u32 primary = primary_saved;
4998 	u32 secondary = secondary_saved;
4999 
5000 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
5001 	    (ctrl_cpu_rev[1].clr & CPU_EPT) && (ctrl_cpu_rev[1].clr & CPU_PML))) {
5002 		printf("\"Secondary execution\" control or \"enable EPT\" control or \"enable PML\" control is not supported !\n");
5003 		return;
5004 	}
5005 
5006 	primary |= CPU_SECONDARY;
5007 	vmcs_write(CPU_EXEC_CTRL0, primary);
5008 	secondary &= ~(CPU_PML | CPU_EPT);
5009 	vmcs_write(CPU_EXEC_CTRL1, secondary);
5010 	report_prefix_pushf("enable-PML disabled, enable-EPT disabled");
5011 	test_vmx_valid_controls();
5012 	report_prefix_pop();
5013 
5014 	secondary |= CPU_PML;
5015 	vmcs_write(CPU_EXEC_CTRL1, secondary);
5016 	report_prefix_pushf("enable-PML enabled, enable-EPT disabled");
5017 	test_vmx_invalid_controls();
5018 	report_prefix_pop();
5019 
5020 	secondary |= CPU_EPT;
5021 	setup_dummy_ept();
5022 	report_prefix_pushf("enable-PML enabled, enable-EPT enabled");
5023 	test_vmx_valid_controls();
5024 	report_prefix_pop();
5025 
5026 	secondary &= ~CPU_PML;
5027 	vmcs_write(CPU_EXEC_CTRL1, secondary);
5028 	report_prefix_pushf("enable-PML disabled, enable EPT enabled");
5029 	test_vmx_valid_controls();
5030 	report_prefix_pop();
5031 
5032 	test_vmcs_addr_reference(CPU_PML, PMLADDR, "PML address", "PML",
5033 				 PAGE_SIZE, false, false);
5034 
5035 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
5036 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
5037 }
5038 
5039  /*
5040  * If the "activate VMX-preemption timer" VM-execution control is 0, the
5041  * the "save VMX-preemption timer value" VM-exit control must also be 0.
5042  *
5043  *  [Intel SDM]
5044  */
5045 static void test_vmx_preemption_timer(void)
5046 {
5047 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
5048 	u32 saved_exit = vmcs_read(EXI_CONTROLS);
5049 	u32 pin = saved_pin;
5050 	u32 exit = saved_exit;
5051 
5052 	if (!((ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) ||
5053 	    (ctrl_pin_rev.clr & PIN_PREEMPT))) {
5054 		printf("\"Save-VMX-preemption-timer\" control and/or \"Enable-VMX-preemption-timer\" control is not supported\n");
5055 		return;
5056 	}
5057 
5058 	pin |= PIN_PREEMPT;
5059 	vmcs_write(PIN_CONTROLS, pin);
5060 	exit &= ~EXI_SAVE_PREEMPT;
5061 	vmcs_write(EXI_CONTROLS, exit);
5062 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer disabled");
5063 	test_vmx_valid_controls();
5064 	report_prefix_pop();
5065 
5066 	exit |= EXI_SAVE_PREEMPT;
5067 	vmcs_write(EXI_CONTROLS, exit);
5068 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer enabled");
5069 	test_vmx_valid_controls();
5070 	report_prefix_pop();
5071 
5072 	pin &= ~PIN_PREEMPT;
5073 	vmcs_write(PIN_CONTROLS, pin);
5074 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer enabled");
5075 	test_vmx_invalid_controls();
5076 	report_prefix_pop();
5077 
5078 	exit &= ~EXI_SAVE_PREEMPT;
5079 	vmcs_write(EXI_CONTROLS, exit);
5080 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer disabled");
5081 	test_vmx_valid_controls();
5082 	report_prefix_pop();
5083 
5084 	vmcs_write(PIN_CONTROLS, saved_pin);
5085 	vmcs_write(EXI_CONTROLS, saved_exit);
5086 }
5087 
5088 extern unsigned char test_mtf1;
5089 extern unsigned char test_mtf2;
5090 extern unsigned char test_mtf3;
5091 extern unsigned char test_mtf4;
5092 
5093 static void test_mtf_guest(void)
5094 {
5095 	asm ("vmcall;\n\t"
5096 	     "out %al, $0x80;\n\t"
5097 	     "test_mtf1:\n\t"
5098 	     "vmcall;\n\t"
5099 	     "out %al, $0x80;\n\t"
5100 	     "test_mtf2:\n\t"
5101 	     /*
5102 	      * Prepare for the 'MOV CR3' test. Attempt to induce a
5103 	      * general-protection fault by moving a non-canonical address into
5104 	      * CR3. The 'MOV CR3' instruction does not take an imm64 operand,
5105 	      * so we must MOV the desired value into a register first.
5106 	      *
5107 	      * MOV RAX is done before the VMCALL such that MTF is only enabled
5108 	      * for the instruction under test.
5109 	      */
5110 	     "mov $0xaaaaaaaaaaaaaaaa, %rax;\n\t"
5111 	     "vmcall;\n\t"
5112 	     "mov %rax, %cr3;\n\t"
5113 	     "test_mtf3:\n\t"
5114 	     "vmcall;\n\t"
5115 	     /*
5116 	      * ICEBP/INT1 instruction. Though the instruction is now
5117 	      * documented, don't rely on assemblers enumerating the
5118 	      * instruction. Resort to hand assembly.
5119 	      */
5120 	     ".byte 0xf1;\n\t"
5121 	     "vmcall;\n\t"
5122 	     "test_mtf4:\n\t"
5123 	     "mov $0, %eax;\n\t");
5124 }
5125 
5126 static void test_mtf_gp_handler(struct ex_regs *regs)
5127 {
5128 	regs->rip = (unsigned long) &test_mtf3;
5129 }
5130 
5131 static void test_mtf_db_handler(struct ex_regs *regs)
5132 {
5133 }
5134 
5135 static void enable_mtf(void)
5136 {
5137 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5138 
5139 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 | CPU_MTF);
5140 }
5141 
5142 static void disable_mtf(void)
5143 {
5144 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5145 
5146 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 & ~CPU_MTF);
5147 }
5148 
5149 static void enable_tf(void)
5150 {
5151 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
5152 
5153 	vmcs_write(GUEST_RFLAGS, rflags | X86_EFLAGS_TF);
5154 }
5155 
5156 static void disable_tf(void)
5157 {
5158 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
5159 
5160 	vmcs_write(GUEST_RFLAGS, rflags & ~X86_EFLAGS_TF);
5161 }
5162 
5163 static void report_mtf(const char *insn_name, unsigned long exp_rip)
5164 {
5165 	unsigned long rip = vmcs_read(GUEST_RIP);
5166 
5167 	assert_exit_reason(VMX_MTF);
5168 	report(rip == exp_rip, "MTF VM-exit after %s. RIP: 0x%lx (expected 0x%lx)",
5169 	       insn_name, rip, exp_rip);
5170 }
5171 
5172 static void vmx_mtf_test(void)
5173 {
5174 	unsigned long pending_dbg;
5175 	handler old_gp, old_db;
5176 
5177 	if (!(ctrl_cpu_rev[0].clr & CPU_MTF)) {
5178 		printf("CPU does not support the 'monitor trap flag' processor-based VM-execution control.\n");
5179 		return;
5180 	}
5181 
5182 	test_set_guest(test_mtf_guest);
5183 
5184 	/* Expect an MTF VM-exit after OUT instruction */
5185 	enter_guest();
5186 	skip_exit_vmcall();
5187 
5188 	enable_mtf();
5189 	enter_guest();
5190 	report_mtf("OUT", (unsigned long) &test_mtf1);
5191 	disable_mtf();
5192 
5193 	/*
5194 	 * Concurrent #DB trap and MTF on instruction boundary. Expect MTF
5195 	 * VM-exit with populated 'pending debug exceptions' VMCS field.
5196 	 */
5197 	enter_guest();
5198 	skip_exit_vmcall();
5199 
5200 	enable_mtf();
5201 	enable_tf();
5202 
5203 	enter_guest();
5204 	report_mtf("OUT", (unsigned long) &test_mtf2);
5205 	pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
5206 	report(pending_dbg & DR_STEP,
5207 	       "'pending debug exceptions' field after MTF VM-exit: 0x%lx (expected 0x%lx)",
5208 	       pending_dbg, (unsigned long) DR_STEP);
5209 
5210 	disable_mtf();
5211 	disable_tf();
5212 	vmcs_write(GUEST_PENDING_DEBUG, 0);
5213 
5214 	/*
5215 	 * #GP exception takes priority over MTF. Expect MTF VM-exit with RIP
5216 	 * advanced to first instruction of #GP handler.
5217 	 */
5218 	enter_guest();
5219 	skip_exit_vmcall();
5220 
5221 	old_gp = handle_exception(GP_VECTOR, test_mtf_gp_handler);
5222 
5223 	enable_mtf();
5224 	enter_guest();
5225 	report_mtf("MOV CR3", (unsigned long) get_idt_addr(&boot_idt[GP_VECTOR]));
5226 	disable_mtf();
5227 
5228 	/*
5229 	 * Concurrent MTF and privileged software exception (i.e. ICEBP/INT1).
5230 	 * MTF should follow the delivery of #DB trap, though the SDM doesn't
5231 	 * provide clear indication of the relative priority.
5232 	 */
5233 	enter_guest();
5234 	skip_exit_vmcall();
5235 
5236 	handle_exception(GP_VECTOR, old_gp);
5237 	old_db = handle_exception(DB_VECTOR, test_mtf_db_handler);
5238 
5239 	enable_mtf();
5240 	enter_guest();
5241 	report_mtf("INT1", (unsigned long) get_idt_addr(&boot_idt[DB_VECTOR]));
5242 	disable_mtf();
5243 
5244 	enter_guest();
5245 	skip_exit_vmcall();
5246 	handle_exception(DB_VECTOR, old_db);
5247 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK | INTR_TYPE_OTHER_EVENT);
5248 	enter_guest();
5249 	report_mtf("injected MTF", (unsigned long) &test_mtf4);
5250 	enter_guest();
5251 }
5252 
5253 /*
5254  * Tests for VM-execution control fields
5255  */
5256 static void test_vm_execution_ctls(void)
5257 {
5258 	test_pin_based_ctls();
5259 	test_primary_processor_based_ctls();
5260 	test_secondary_processor_based_ctls();
5261 	test_cr3_targets();
5262 	test_io_bitmaps();
5263 	test_msr_bitmap();
5264 	test_apic_ctls();
5265 	test_tpr_threshold();
5266 	test_nmi_ctrls();
5267 	test_pml();
5268 	test_vpid();
5269 	test_ept_eptp();
5270 	test_vmx_preemption_timer();
5271 }
5272 
5273  /*
5274   * The following checks are performed for the VM-entry MSR-load address if
5275   * the VM-entry MSR-load count field is non-zero:
5276   *
5277   *    - The lower 4 bits of the VM-entry MSR-load address must be 0.
5278   *      The address should not set any bits beyond the processor’s
5279   *      physical-address width.
5280   *
5281   *    - The address of the last byte in the VM-entry MSR-load area
5282   *      should not set any bits beyond the processor’s physical-address
5283   *      width. The address of this last byte is VM-entry MSR-load address
5284   *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5285   *      uses more bits than the processor’s physical-address width.)
5286   *
5287   *
5288   *  [Intel SDM]
5289   */
5290 static void test_entry_msr_load(void)
5291 {
5292 	entry_msr_load = alloc_page();
5293 	u64 tmp;
5294 	u32 entry_msr_ld_cnt = 1;
5295 	int i;
5296 	u32 addr_len = 64;
5297 
5298 	vmcs_write(ENT_MSR_LD_CNT, entry_msr_ld_cnt);
5299 
5300 	/* Check first 4 bits of VM-entry MSR-load address */
5301 	for (i = 0; i < 4; i++) {
5302 		tmp = (u64)entry_msr_load | 1ull << i;
5303 		vmcs_write(ENTER_MSR_LD_ADDR, tmp);
5304 		report_prefix_pushf("VM-entry MSR-load addr [4:0] %lx",
5305 				    tmp & 0xf);
5306 		test_vmx_invalid_controls();
5307 		report_prefix_pop();
5308 	}
5309 
5310 	if (basic.val & (1ul << 48))
5311 		addr_len = 32;
5312 
5313 	test_vmcs_addr_values("VM-entry-MSR-load address",
5314 				ENTER_MSR_LD_ADDR, 16, false, false,
5315 				4, addr_len - 1);
5316 
5317 	/*
5318 	 * Check last byte of VM-entry MSR-load address
5319 	 */
5320 	entry_msr_load = (struct vmx_msr_entry *)((u64)entry_msr_load & ~0xf);
5321 
5322 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5323 							i < 64; i++) {
5324 		tmp = ((u64)entry_msr_load + entry_msr_ld_cnt * 16 - 1) |
5325 			1ul << i;
5326 		vmcs_write(ENTER_MSR_LD_ADDR,
5327 			   tmp - (entry_msr_ld_cnt * 16 - 1));
5328 		test_vmx_invalid_controls();
5329 	}
5330 
5331 	vmcs_write(ENT_MSR_LD_CNT, 2);
5332 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5333 	test_vmx_invalid_controls();
5334 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5335 	test_vmx_valid_controls();
5336 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5337 	test_vmx_valid_controls();
5338 }
5339 
5340 static struct vmx_state_area_test_data {
5341 	u32 msr;
5342 	u64 exp;
5343 	bool enabled;
5344 } vmx_state_area_test_data;
5345 
5346 static void guest_state_test_main(void)
5347 {
5348 	u64 obs;
5349 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
5350 
5351 	while (1) {
5352 		if (vmx_get_test_stage() == 2)
5353 			break;
5354 
5355 		if (data->enabled) {
5356 			obs = rdmsr(data->msr);
5357 			report(data->exp == obs,
5358 			       "Guest state is 0x%lx (expected 0x%lx)",
5359 			       obs, data->exp);
5360 		}
5361 
5362 		vmcall();
5363 	}
5364 
5365 	asm volatile("fnop");
5366 }
5367 
5368 static void test_guest_state(const char *test, bool xfail, u64 field,
5369 			     const char * field_name)
5370 {
5371 	struct vmentry_result result;
5372 	u8 abort_flags;
5373 
5374 	abort_flags = ABORT_ON_EARLY_VMENTRY_FAIL;
5375 	if (!xfail)
5376 		abort_flags = ABORT_ON_INVALID_GUEST_STATE;
5377 
5378 	__enter_guest(abort_flags, &result);
5379 
5380 	report(result.exit_reason.failed_vmentry == xfail &&
5381 	       ((xfail && result.exit_reason.basic == VMX_FAIL_STATE) ||
5382 	        (!xfail && result.exit_reason.basic == VMX_VMCALL)) &&
5383 		(!xfail || vmcs_read(EXI_QUALIFICATION) == ENTRY_FAIL_DEFAULT),
5384 	        "%s, %s %lx", test, field_name, field);
5385 
5386 	if (!result.exit_reason.failed_vmentry)
5387 		skip_exit_insn();
5388 }
5389 
5390 /*
5391  * Tests for VM-entry control fields
5392  */
5393 static void test_vm_entry_ctls(void)
5394 {
5395 	test_invalid_event_injection();
5396 	test_entry_msr_load();
5397 }
5398 
5399 /*
5400  * The following checks are performed for the VM-exit MSR-store address if
5401  * the VM-exit MSR-store count field is non-zero:
5402  *
5403  *    - The lower 4 bits of the VM-exit MSR-store address must be 0.
5404  *      The address should not set any bits beyond the processor’s
5405  *      physical-address width.
5406  *
5407  *    - The address of the last byte in the VM-exit MSR-store area
5408  *      should not set any bits beyond the processor’s physical-address
5409  *      width. The address of this last byte is VM-exit MSR-store address
5410  *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5411  *      uses more bits than the processor’s physical-address width.)
5412  *
5413  * If IA32_VMX_BASIC[48] is read as 1, neither address should set any bits
5414  * in the range 63:32.
5415  *
5416  *  [Intel SDM]
5417  */
5418 static void test_exit_msr_store(void)
5419 {
5420 	exit_msr_store = alloc_page();
5421 	u64 tmp;
5422 	u32 exit_msr_st_cnt = 1;
5423 	int i;
5424 	u32 addr_len = 64;
5425 
5426 	vmcs_write(EXI_MSR_ST_CNT, exit_msr_st_cnt);
5427 
5428 	/* Check first 4 bits of VM-exit MSR-store address */
5429 	for (i = 0; i < 4; i++) {
5430 		tmp = (u64)exit_msr_store | 1ull << i;
5431 		vmcs_write(EXIT_MSR_ST_ADDR, tmp);
5432 		report_prefix_pushf("VM-exit MSR-store addr [4:0] %lx",
5433 				    tmp & 0xf);
5434 		test_vmx_invalid_controls();
5435 		report_prefix_pop();
5436 	}
5437 
5438 	if (basic.val & (1ul << 48))
5439 		addr_len = 32;
5440 
5441 	test_vmcs_addr_values("VM-exit-MSR-store address",
5442 				EXIT_MSR_ST_ADDR, 16, false, false,
5443 				4, addr_len - 1);
5444 
5445 	/*
5446 	 * Check last byte of VM-exit MSR-store address
5447 	 */
5448 	exit_msr_store = (struct vmx_msr_entry *)((u64)exit_msr_store & ~0xf);
5449 
5450 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5451 							i < 64; i++) {
5452 		tmp = ((u64)exit_msr_store + exit_msr_st_cnt * 16 - 1) |
5453 			1ul << i;
5454 		vmcs_write(EXIT_MSR_ST_ADDR,
5455 			   tmp - (exit_msr_st_cnt * 16 - 1));
5456 		test_vmx_invalid_controls();
5457 	}
5458 
5459 	vmcs_write(EXI_MSR_ST_CNT, 2);
5460 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5461 	test_vmx_invalid_controls();
5462 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5463 	test_vmx_valid_controls();
5464 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5465 	test_vmx_valid_controls();
5466 }
5467 
5468 /*
5469  * Tests for VM-exit controls
5470  */
5471 static void test_vm_exit_ctls(void)
5472 {
5473 	test_exit_msr_store();
5474 }
5475 
5476 /*
5477  * Check that the virtual CPU checks all of the VMX controls as
5478  * documented in the Intel SDM.
5479  */
5480 static void vmx_controls_test(void)
5481 {
5482 	/*
5483 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
5484 	 * fail due to invalid guest state, should we make it that
5485 	 * far.
5486 	 */
5487 	vmcs_write(GUEST_RFLAGS, 0);
5488 
5489 	test_vm_execution_ctls();
5490 	test_vm_exit_ctls();
5491 	test_vm_entry_ctls();
5492 }
5493 
5494 struct apic_reg_virt_config {
5495 	bool apic_register_virtualization;
5496 	bool use_tpr_shadow;
5497 	bool virtualize_apic_accesses;
5498 	bool virtualize_x2apic_mode;
5499 	bool activate_secondary_controls;
5500 };
5501 
5502 struct apic_reg_test {
5503 	const char *name;
5504 	struct apic_reg_virt_config apic_reg_virt_config;
5505 };
5506 
5507 struct apic_reg_virt_expectation {
5508 	enum Reason rd_exit_reason;
5509 	enum Reason wr_exit_reason;
5510 	u32 val;
5511 	u32 (*virt_fn)(u32);
5512 
5513 	/*
5514 	 * If false, accessing the APIC access address from L2 is treated as a
5515 	 * normal memory operation, rather than triggering virtualization.
5516 	 */
5517 	bool virtualize_apic_accesses;
5518 };
5519 
5520 static u32 apic_virt_identity(u32 val)
5521 {
5522 	return val;
5523 }
5524 
5525 static u32 apic_virt_nibble1(u32 val)
5526 {
5527 	return val & 0xf0;
5528 }
5529 
5530 static u32 apic_virt_byte3(u32 val)
5531 {
5532 	return val & (0xff << 24);
5533 }
5534 
5535 static bool apic_reg_virt_exit_expectation(
5536 	u32 reg, struct apic_reg_virt_config *config,
5537 	struct apic_reg_virt_expectation *expectation)
5538 {
5539 	/* Good configs, where some L2 APIC accesses are virtualized. */
5540 	bool virtualize_apic_accesses_only =
5541 		config->virtualize_apic_accesses &&
5542 		!config->use_tpr_shadow &&
5543 		!config->apic_register_virtualization &&
5544 		!config->virtualize_x2apic_mode &&
5545 		config->activate_secondary_controls;
5546 	bool virtualize_apic_accesses_and_use_tpr_shadow =
5547 		config->virtualize_apic_accesses &&
5548 		config->use_tpr_shadow &&
5549 		!config->apic_register_virtualization &&
5550 		!config->virtualize_x2apic_mode &&
5551 		config->activate_secondary_controls;
5552 	bool apic_register_virtualization =
5553 		config->virtualize_apic_accesses &&
5554 		config->use_tpr_shadow &&
5555 		config->apic_register_virtualization &&
5556 		!config->virtualize_x2apic_mode &&
5557 		config->activate_secondary_controls;
5558 
5559 	expectation->val = MAGIC_VAL_1;
5560 	expectation->virt_fn = apic_virt_identity;
5561 	expectation->virtualize_apic_accesses =
5562 		config->virtualize_apic_accesses &&
5563 		config->activate_secondary_controls;
5564 	if (virtualize_apic_accesses_only) {
5565 		expectation->rd_exit_reason = VMX_APIC_ACCESS;
5566 		expectation->wr_exit_reason = VMX_APIC_ACCESS;
5567 	} else if (virtualize_apic_accesses_and_use_tpr_shadow) {
5568 		switch (reg) {
5569 		case APIC_TASKPRI:
5570 			expectation->rd_exit_reason = VMX_VMCALL;
5571 			expectation->wr_exit_reason = VMX_VMCALL;
5572 			expectation->virt_fn = apic_virt_nibble1;
5573 			break;
5574 		default:
5575 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5576 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5577 		}
5578 	} else if (apic_register_virtualization) {
5579 		expectation->rd_exit_reason = VMX_VMCALL;
5580 
5581 		switch (reg) {
5582 		case APIC_ID:
5583 		case APIC_EOI:
5584 		case APIC_LDR:
5585 		case APIC_DFR:
5586 		case APIC_SPIV:
5587 		case APIC_ESR:
5588 		case APIC_ICR:
5589 		case APIC_LVTT:
5590 		case APIC_LVTTHMR:
5591 		case APIC_LVTPC:
5592 		case APIC_LVT0:
5593 		case APIC_LVT1:
5594 		case APIC_LVTERR:
5595 		case APIC_TMICT:
5596 		case APIC_TDCR:
5597 			expectation->wr_exit_reason = VMX_APIC_WRITE;
5598 			break;
5599 		case APIC_LVR:
5600 		case APIC_ISR ... APIC_ISR + 0x70:
5601 		case APIC_TMR ... APIC_TMR + 0x70:
5602 		case APIC_IRR ... APIC_IRR + 0x70:
5603 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5604 			break;
5605 		case APIC_TASKPRI:
5606 			expectation->wr_exit_reason = VMX_VMCALL;
5607 			expectation->virt_fn = apic_virt_nibble1;
5608 			break;
5609 		case APIC_ICR2:
5610 			expectation->wr_exit_reason = VMX_VMCALL;
5611 			expectation->virt_fn = apic_virt_byte3;
5612 			break;
5613 		default:
5614 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5615 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5616 		}
5617 	} else if (!expectation->virtualize_apic_accesses) {
5618 		/*
5619 		 * No APIC registers are directly virtualized. This includes
5620 		 * VTPR, which can be virtualized through MOV to/from CR8 via
5621 		 * the use TPR shadow control, but not through directly
5622 		 * accessing VTPR.
5623 		 */
5624 		expectation->rd_exit_reason = VMX_VMCALL;
5625 		expectation->wr_exit_reason = VMX_VMCALL;
5626 	} else {
5627 		printf("Cannot parse APIC register virtualization config:\n"
5628 		       "\tvirtualize_apic_accesses: %d\n"
5629 		       "\tuse_tpr_shadow: %d\n"
5630 		       "\tapic_register_virtualization: %d\n"
5631 		       "\tvirtualize_x2apic_mode: %d\n"
5632 		       "\tactivate_secondary_controls: %d\n",
5633 		       config->virtualize_apic_accesses,
5634 		       config->use_tpr_shadow,
5635 		       config->apic_register_virtualization,
5636 		       config->virtualize_x2apic_mode,
5637 		       config->activate_secondary_controls);
5638 
5639 		return false;
5640 	}
5641 
5642 	return true;
5643 }
5644 
5645 struct apic_reg_test apic_reg_tests[] = {
5646 	/* Good configs, where some L2 APIC accesses are virtualized. */
5647 	{
5648 		.name = "Virtualize APIC accesses",
5649 		.apic_reg_virt_config = {
5650 			.virtualize_apic_accesses = true,
5651 			.use_tpr_shadow = false,
5652 			.apic_register_virtualization = false,
5653 			.virtualize_x2apic_mode = false,
5654 			.activate_secondary_controls = true,
5655 		},
5656 	},
5657 	{
5658 		.name = "Virtualize APIC accesses + Use TPR shadow",
5659 		.apic_reg_virt_config = {
5660 			.virtualize_apic_accesses = true,
5661 			.use_tpr_shadow = true,
5662 			.apic_register_virtualization = false,
5663 			.virtualize_x2apic_mode = false,
5664 			.activate_secondary_controls = true,
5665 		},
5666 	},
5667 	{
5668 		.name = "APIC-register virtualization",
5669 		.apic_reg_virt_config = {
5670 			.virtualize_apic_accesses = true,
5671 			.use_tpr_shadow = true,
5672 			.apic_register_virtualization = true,
5673 			.virtualize_x2apic_mode = false,
5674 			.activate_secondary_controls = true,
5675 		},
5676 	},
5677 
5678 	/*
5679 	 * Test that the secondary processor-based VM-execution controls are
5680 	 * correctly ignored when "activate secondary controls" is disabled.
5681 	 */
5682 	{
5683 		.name = "Activate secondary controls off",
5684 		.apic_reg_virt_config = {
5685 			.virtualize_apic_accesses = true,
5686 			.use_tpr_shadow = false,
5687 			.apic_register_virtualization = true,
5688 			.virtualize_x2apic_mode = true,
5689 			.activate_secondary_controls = false,
5690 		},
5691 	},
5692 	{
5693 		.name = "Activate secondary controls off + Use TPR shadow",
5694 		.apic_reg_virt_config = {
5695 			.virtualize_apic_accesses = true,
5696 			.use_tpr_shadow = true,
5697 			.apic_register_virtualization = true,
5698 			.virtualize_x2apic_mode = true,
5699 			.activate_secondary_controls = false,
5700 		},
5701 	},
5702 
5703 	/*
5704 	 * Test that the APIC access address is treated like an arbitrary memory
5705 	 * address when "virtualize APIC accesses" is disabled.
5706 	 */
5707 	{
5708 		.name = "Virtualize APIC accesses off + Use TPR shadow",
5709 		.apic_reg_virt_config = {
5710 			.virtualize_apic_accesses = false,
5711 			.use_tpr_shadow = true,
5712 			.apic_register_virtualization = true,
5713 			.virtualize_x2apic_mode = true,
5714 			.activate_secondary_controls = true,
5715 		},
5716 	},
5717 
5718 	/*
5719 	 * Test that VM entry fails due to invalid controls when
5720 	 * "APIC-register virtualization" is enabled while "use TPR shadow" is
5721 	 * disabled.
5722 	 */
5723 	{
5724 		.name = "APIC-register virtualization + Use TPR shadow off",
5725 		.apic_reg_virt_config = {
5726 			.virtualize_apic_accesses = true,
5727 			.use_tpr_shadow = false,
5728 			.apic_register_virtualization = true,
5729 			.virtualize_x2apic_mode = false,
5730 			.activate_secondary_controls = true,
5731 		},
5732 	},
5733 
5734 	/*
5735 	 * Test that VM entry fails due to invalid controls when
5736 	 * "Virtualize x2APIC mode" is enabled while "use TPR shadow" is
5737 	 * disabled.
5738 	 */
5739 	{
5740 		.name = "Virtualize x2APIC mode + Use TPR shadow off",
5741 		.apic_reg_virt_config = {
5742 			.virtualize_apic_accesses = false,
5743 			.use_tpr_shadow = false,
5744 			.apic_register_virtualization = false,
5745 			.virtualize_x2apic_mode = true,
5746 			.activate_secondary_controls = true,
5747 		},
5748 	},
5749 	{
5750 		.name = "Virtualize x2APIC mode + Use TPR shadow off v2",
5751 		.apic_reg_virt_config = {
5752 			.virtualize_apic_accesses = false,
5753 			.use_tpr_shadow = false,
5754 			.apic_register_virtualization = true,
5755 			.virtualize_x2apic_mode = true,
5756 			.activate_secondary_controls = true,
5757 		},
5758 	},
5759 
5760 	/*
5761 	 * Test that VM entry fails due to invalid controls when
5762 	 * "virtualize x2APIC mode" is enabled while "virtualize APIC accesses"
5763 	 * is enabled.
5764 	 */
5765 	{
5766 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses",
5767 		.apic_reg_virt_config = {
5768 			.virtualize_apic_accesses = true,
5769 			.use_tpr_shadow = true,
5770 			.apic_register_virtualization = false,
5771 			.virtualize_x2apic_mode = true,
5772 			.activate_secondary_controls = true,
5773 		},
5774 	},
5775 	{
5776 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses v2",
5777 		.apic_reg_virt_config = {
5778 			.virtualize_apic_accesses = true,
5779 			.use_tpr_shadow = true,
5780 			.apic_register_virtualization = true,
5781 			.virtualize_x2apic_mode = true,
5782 			.activate_secondary_controls = true,
5783 		},
5784 	},
5785 };
5786 
5787 enum Apic_op {
5788 	APIC_OP_XAPIC_RD,
5789 	APIC_OP_XAPIC_WR,
5790 	TERMINATE,
5791 };
5792 
5793 static u32 vmx_xapic_read(u32 *apic_access_address, u32 reg)
5794 {
5795 	return *(volatile u32 *)((uintptr_t)apic_access_address + reg);
5796 }
5797 
5798 static void vmx_xapic_write(u32 *apic_access_address, u32 reg, u32 val)
5799 {
5800 	*(volatile u32 *)((uintptr_t)apic_access_address + reg) = val;
5801 }
5802 
5803 struct apic_reg_virt_guest_args {
5804 	enum Apic_op op;
5805 	u32 *apic_access_address;
5806 	u32 reg;
5807 	u32 val;
5808 	bool check_rd;
5809 	u32 (*virt_fn)(u32);
5810 } apic_reg_virt_guest_args;
5811 
5812 static void apic_reg_virt_guest(void)
5813 {
5814 	volatile struct apic_reg_virt_guest_args *args =
5815 		&apic_reg_virt_guest_args;
5816 
5817 	for (;;) {
5818 		enum Apic_op op = args->op;
5819 		u32 *apic_access_address = args->apic_access_address;
5820 		u32 reg = args->reg;
5821 		u32 val = args->val;
5822 		bool check_rd = args->check_rd;
5823 		u32 (*virt_fn)(u32) = args->virt_fn;
5824 
5825 		if (op == TERMINATE)
5826 			break;
5827 
5828 		if (op == APIC_OP_XAPIC_RD) {
5829 			u32 ret = vmx_xapic_read(apic_access_address, reg);
5830 
5831 			if (check_rd) {
5832 				u32 want = virt_fn(val);
5833 				u32 got = virt_fn(ret);
5834 
5835 				report(got == want,
5836 				       "read 0x%x, expected 0x%x.", got, want);
5837 			}
5838 		} else if (op == APIC_OP_XAPIC_WR) {
5839 			vmx_xapic_write(apic_access_address, reg, val);
5840 		}
5841 
5842 		/*
5843 		 * The L1 should always execute a vmcall after it's done testing
5844 		 * an individual APIC operation. This helps to validate that the
5845 		 * L1 and L2 are in sync with each other, as expected.
5846 		 */
5847 		vmcall();
5848 	}
5849 }
5850 
5851 static void test_xapic_rd(
5852 	u32 reg, struct apic_reg_virt_expectation *expectation,
5853 	u32 *apic_access_address, u32 *virtual_apic_page)
5854 {
5855 	u32 val = expectation->val;
5856 	u32 exit_reason_want = expectation->rd_exit_reason;
5857 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5858 
5859 	report_prefix_pushf("xapic - reading 0x%03x", reg);
5860 
5861 	/* Configure guest to do an xapic read */
5862 	args->op = APIC_OP_XAPIC_RD;
5863 	args->apic_access_address = apic_access_address;
5864 	args->reg = reg;
5865 	args->val = val;
5866 	args->check_rd = exit_reason_want == VMX_VMCALL;
5867 	args->virt_fn = expectation->virt_fn;
5868 
5869 	/* Setup virtual APIC page */
5870 	if (!expectation->virtualize_apic_accesses) {
5871 		apic_access_address[apic_reg_index(reg)] = val;
5872 		virtual_apic_page[apic_reg_index(reg)] = 0;
5873 	} else if (exit_reason_want == VMX_VMCALL) {
5874 		apic_access_address[apic_reg_index(reg)] = 0;
5875 		virtual_apic_page[apic_reg_index(reg)] = val;
5876 	}
5877 
5878 	/* Enter guest */
5879 	enter_guest();
5880 
5881 	/*
5882 	 * Validate the behavior and
5883 	 * pass a magic value back to the guest.
5884 	 */
5885 	if (exit_reason_want == VMX_APIC_ACCESS) {
5886 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5887 
5888 		assert_exit_reason(exit_reason_want);
5889 		report(apic_page_offset == reg,
5890 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5891 		       apic_page_offset, reg);
5892 		skip_exit_insn();
5893 
5894 		/* Reenter guest so it can consume/check rcx and exit again. */
5895 		enter_guest();
5896 	} else if (exit_reason_want != VMX_VMCALL) {
5897 		report(false, "Oops, bad exit expectation: %u.",
5898 		       exit_reason_want);
5899 	}
5900 
5901 	skip_exit_vmcall();
5902 	report_prefix_pop();
5903 }
5904 
5905 static void test_xapic_wr(
5906 	u32 reg, struct apic_reg_virt_expectation *expectation,
5907 	u32 *apic_access_address, u32 *virtual_apic_page)
5908 {
5909 	u32 val = expectation->val;
5910 	u32 exit_reason_want = expectation->wr_exit_reason;
5911 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5912 	bool virtualized =
5913 		expectation->virtualize_apic_accesses &&
5914 		(exit_reason_want == VMX_APIC_WRITE ||
5915 		 exit_reason_want == VMX_VMCALL);
5916 	bool checked = false;
5917 
5918 	report_prefix_pushf("xapic - writing 0x%x to 0x%03x", val, reg);
5919 
5920 	/* Configure guest to do an xapic read */
5921 	args->op = APIC_OP_XAPIC_WR;
5922 	args->apic_access_address = apic_access_address;
5923 	args->reg = reg;
5924 	args->val = val;
5925 
5926 	/* Setup virtual APIC page */
5927 	if (virtualized || !expectation->virtualize_apic_accesses) {
5928 		apic_access_address[apic_reg_index(reg)] = 0;
5929 		virtual_apic_page[apic_reg_index(reg)] = 0;
5930 	}
5931 
5932 	/* Enter guest */
5933 	enter_guest();
5934 
5935 	/*
5936 	 * Validate the behavior and
5937 	 * pass a magic value back to the guest.
5938 	 */
5939 	if (exit_reason_want == VMX_APIC_ACCESS) {
5940 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5941 
5942 		assert_exit_reason(exit_reason_want);
5943 		report(apic_page_offset == reg,
5944 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5945 		       apic_page_offset, reg);
5946 		skip_exit_insn();
5947 
5948 		/* Reenter guest so it can consume/check rcx and exit again. */
5949 		enter_guest();
5950 	} else if (exit_reason_want == VMX_APIC_WRITE) {
5951 		assert_exit_reason(exit_reason_want);
5952 		report(virtual_apic_page[apic_reg_index(reg)] == val,
5953 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%x",
5954 		       apic_reg_index(reg),
5955 		       virtual_apic_page[apic_reg_index(reg)], val);
5956 		checked = true;
5957 
5958 		/* Reenter guest so it can consume/check rcx and exit again. */
5959 		enter_guest();
5960 	} else if (exit_reason_want != VMX_VMCALL) {
5961 		report(false, "Oops, bad exit expectation: %u.",
5962 		       exit_reason_want);
5963 	}
5964 
5965 	assert_exit_reason(VMX_VMCALL);
5966 	if (virtualized && !checked) {
5967 		u32 want = expectation->virt_fn(val);
5968 		u32 got = virtual_apic_page[apic_reg_index(reg)];
5969 		got = expectation->virt_fn(got);
5970 
5971 		report(got == want, "exitless write; val is 0x%x, want 0x%x",
5972 		       got, want);
5973 	} else if (!expectation->virtualize_apic_accesses && !checked) {
5974 		u32 got = apic_access_address[apic_reg_index(reg)];
5975 
5976 		report(got == val,
5977 		       "non-virtualized write; val is 0x%x, want 0x%x", got,
5978 		       val);
5979 	} else if (!expectation->virtualize_apic_accesses && checked) {
5980 		report(false,
5981 		       "Non-virtualized write was prematurely checked!");
5982 	}
5983 
5984 	skip_exit_vmcall();
5985 	report_prefix_pop();
5986 }
5987 
5988 enum Config_type {
5989 	CONFIG_TYPE_GOOD,
5990 	CONFIG_TYPE_UNSUPPORTED,
5991 	CONFIG_TYPE_VMENTRY_FAILS_EARLY,
5992 };
5993 
5994 static enum Config_type configure_apic_reg_virt_test(
5995 	struct apic_reg_virt_config *apic_reg_virt_config)
5996 {
5997 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
5998 	u32 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
5999 	/* Configs where L2 entry fails early, due to invalid controls. */
6000 	bool use_tpr_shadow_incorrectly_off =
6001 		!apic_reg_virt_config->use_tpr_shadow &&
6002 		(apic_reg_virt_config->apic_register_virtualization ||
6003 		 apic_reg_virt_config->virtualize_x2apic_mode) &&
6004 		apic_reg_virt_config->activate_secondary_controls;
6005 	bool virtualize_apic_accesses_incorrectly_on =
6006 		apic_reg_virt_config->virtualize_apic_accesses &&
6007 		apic_reg_virt_config->virtualize_x2apic_mode &&
6008 		apic_reg_virt_config->activate_secondary_controls;
6009 	bool vmentry_fails_early =
6010 		use_tpr_shadow_incorrectly_off ||
6011 		virtualize_apic_accesses_incorrectly_on;
6012 
6013 	if (apic_reg_virt_config->activate_secondary_controls) {
6014 		if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
6015 			printf("VM-execution control \"activate secondary controls\" NOT supported.\n");
6016 			return CONFIG_TYPE_UNSUPPORTED;
6017 		}
6018 		cpu_exec_ctrl0 |= CPU_SECONDARY;
6019 	} else {
6020 		cpu_exec_ctrl0 &= ~CPU_SECONDARY;
6021 	}
6022 
6023 	if (apic_reg_virt_config->virtualize_apic_accesses) {
6024 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES)) {
6025 			printf("VM-execution control \"virtualize APIC accesses\" NOT supported.\n");
6026 			return CONFIG_TYPE_UNSUPPORTED;
6027 		}
6028 		cpu_exec_ctrl1 |= CPU_VIRT_APIC_ACCESSES;
6029 	} else {
6030 		cpu_exec_ctrl1 &= ~CPU_VIRT_APIC_ACCESSES;
6031 	}
6032 
6033 	if (apic_reg_virt_config->use_tpr_shadow) {
6034 		if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
6035 			printf("VM-execution control \"use TPR shadow\" NOT supported.\n");
6036 			return CONFIG_TYPE_UNSUPPORTED;
6037 		}
6038 		cpu_exec_ctrl0 |= CPU_TPR_SHADOW;
6039 	} else {
6040 		cpu_exec_ctrl0 &= ~CPU_TPR_SHADOW;
6041 	}
6042 
6043 	if (apic_reg_virt_config->apic_register_virtualization) {
6044 		if (!(ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT)) {
6045 			printf("VM-execution control \"APIC-register virtualization\" NOT supported.\n");
6046 			return CONFIG_TYPE_UNSUPPORTED;
6047 		}
6048 		cpu_exec_ctrl1 |= CPU_APIC_REG_VIRT;
6049 	} else {
6050 		cpu_exec_ctrl1 &= ~CPU_APIC_REG_VIRT;
6051 	}
6052 
6053 	if (apic_reg_virt_config->virtualize_x2apic_mode) {
6054 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_X2APIC)) {
6055 			printf("VM-execution control \"virtualize x2APIC mode\" NOT supported.\n");
6056 			return CONFIG_TYPE_UNSUPPORTED;
6057 		}
6058 		cpu_exec_ctrl1 |= CPU_VIRT_X2APIC;
6059 	} else {
6060 		cpu_exec_ctrl1 &= ~CPU_VIRT_X2APIC;
6061 	}
6062 
6063 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6064 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6065 
6066 	if (vmentry_fails_early)
6067 		return CONFIG_TYPE_VMENTRY_FAILS_EARLY;
6068 
6069 	return CONFIG_TYPE_GOOD;
6070 }
6071 
6072 static bool cpu_has_apicv(void)
6073 {
6074 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
6075 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
6076 		(ctrl_pin_rev.clr & PIN_POST_INTR));
6077 }
6078 
6079 /* Validates APIC register access across valid virtualization configurations. */
6080 static void apic_reg_virt_test(void)
6081 {
6082 	u32 *apic_access_address;
6083 	u32 *virtual_apic_page;
6084 	u64 control;
6085 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6086 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6087 	int i;
6088 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
6089 
6090 	if (!cpu_has_apicv()) {
6091 		report_skip(__func__);
6092 		return;
6093 	}
6094 
6095 	control = cpu_exec_ctrl1;
6096 	control &= ~CPU_VINTD;
6097 	vmcs_write(CPU_EXEC_CTRL1, control);
6098 
6099 	test_set_guest(apic_reg_virt_guest);
6100 
6101 	/*
6102 	 * From the SDM: The 1-setting of the "virtualize APIC accesses"
6103 	 * VM-execution is guaranteed to apply only if translations to the
6104 	 * APIC-access address use a 4-KByte page.
6105 	 */
6106 	apic_access_address = alloc_page();
6107 	force_4k_page(apic_access_address);
6108 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_address));
6109 
6110 	virtual_apic_page = alloc_page();
6111 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
6112 
6113 	for (i = 0; i < ARRAY_SIZE(apic_reg_tests); i++) {
6114 		struct apic_reg_test *apic_reg_test = &apic_reg_tests[i];
6115 		struct apic_reg_virt_config *apic_reg_virt_config =
6116 				&apic_reg_test->apic_reg_virt_config;
6117 		enum Config_type config_type;
6118 		u32 reg;
6119 
6120 		printf("--- %s test ---\n", apic_reg_test->name);
6121 		config_type =
6122 			configure_apic_reg_virt_test(apic_reg_virt_config);
6123 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
6124 			printf("Skip because of missing features.\n");
6125 			continue;
6126 		}
6127 
6128 		if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6129 			enter_guest_with_bad_controls();
6130 			continue;
6131 		}
6132 
6133 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6134 			struct apic_reg_virt_expectation expectation = {};
6135 			bool ok;
6136 
6137 			ok = apic_reg_virt_exit_expectation(
6138 				reg, apic_reg_virt_config, &expectation);
6139 			if (!ok) {
6140 				report(false, "Malformed test.");
6141 				break;
6142 			}
6143 
6144 			test_xapic_rd(reg, &expectation, apic_access_address,
6145 				      virtual_apic_page);
6146 			test_xapic_wr(reg, &expectation, apic_access_address,
6147 				      virtual_apic_page);
6148 		}
6149 	}
6150 
6151 	/* Terminate the guest */
6152 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6153 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6154 	args->op = TERMINATE;
6155 	enter_guest();
6156 	assert_exit_reason(VMX_VMCALL);
6157 }
6158 
6159 struct virt_x2apic_mode_config {
6160 	struct apic_reg_virt_config apic_reg_virt_config;
6161 	bool virtual_interrupt_delivery;
6162 	bool use_msr_bitmaps;
6163 	bool disable_x2apic_msr_intercepts;
6164 	bool disable_x2apic;
6165 };
6166 
6167 struct virt_x2apic_mode_test_case {
6168 	const char *name;
6169 	struct virt_x2apic_mode_config virt_x2apic_mode_config;
6170 };
6171 
6172 enum Virt_x2apic_mode_behavior_type {
6173 	X2APIC_ACCESS_VIRTUALIZED,
6174 	X2APIC_ACCESS_PASSED_THROUGH,
6175 	X2APIC_ACCESS_TRIGGERS_GP,
6176 };
6177 
6178 struct virt_x2apic_mode_expectation {
6179 	enum Reason rd_exit_reason;
6180 	enum Reason wr_exit_reason;
6181 
6182 	/*
6183 	 * RDMSR and WRMSR handle 64-bit values. However, except for ICR, all of
6184 	 * the x2APIC registers are 32 bits. Notice:
6185 	 *   1. vmx_x2apic_read() clears the upper 32 bits for 32-bit registers.
6186 	 *   2. vmx_x2apic_write() expects the val arg to be well-formed.
6187 	 */
6188 	u64 rd_val;
6189 	u64 wr_val;
6190 
6191 	/*
6192 	 * Compares input to virtualized output;
6193 	 * 1st arg is pointer to return expected virtualization output.
6194 	 */
6195 	u64 (*virt_fn)(u64);
6196 
6197 	enum Virt_x2apic_mode_behavior_type rd_behavior;
6198 	enum Virt_x2apic_mode_behavior_type wr_behavior;
6199 	bool wr_only;
6200 };
6201 
6202 static u64 virt_x2apic_mode_identity(u64 val)
6203 {
6204 	return val;
6205 }
6206 
6207 static u64 virt_x2apic_mode_nibble1(u64 val)
6208 {
6209 	return val & 0xf0;
6210 }
6211 
6212 static void virt_x2apic_mode_rd_expectation(
6213 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6214 	bool apic_register_virtualization, bool virtual_interrupt_delivery,
6215 	struct virt_x2apic_mode_expectation *expectation)
6216 {
6217 	bool readable =
6218 		!x2apic_reg_reserved(reg) &&
6219 		reg != APIC_EOI;
6220 
6221 	expectation->rd_exit_reason = VMX_VMCALL;
6222 	expectation->virt_fn = virt_x2apic_mode_identity;
6223 	if (virt_x2apic_mode_on && apic_register_virtualization) {
6224 		expectation->rd_val = MAGIC_VAL_1;
6225 		if (reg == APIC_PROCPRI && virtual_interrupt_delivery)
6226 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6227 		else if (reg == APIC_TASKPRI)
6228 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6229 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6230 	} else if (virt_x2apic_mode_on && !apic_register_virtualization &&
6231 		   reg == APIC_TASKPRI) {
6232 		expectation->rd_val = MAGIC_VAL_1;
6233 		expectation->virt_fn = virt_x2apic_mode_nibble1;
6234 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6235 	} else if (!disable_x2apic && readable) {
6236 		expectation->rd_val = apic_read(reg);
6237 		expectation->rd_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6238 	} else {
6239 		expectation->rd_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6240 	}
6241 }
6242 
6243 /*
6244  * get_x2apic_wr_val() creates an innocuous write value for an x2APIC register.
6245  *
6246  * For writable registers, get_x2apic_wr_val() deposits the write value into the
6247  * val pointer arg and returns true. For non-writable registers, val is not
6248  * modified and get_x2apic_wr_val() returns false.
6249  */
6250 static bool get_x2apic_wr_val(u32 reg, u64 *val)
6251 {
6252 	switch (reg) {
6253 	case APIC_TASKPRI:
6254 		/* Bits 31:8 are reserved. */
6255 		*val &= 0xff;
6256 		break;
6257 	case APIC_EOI:
6258 	case APIC_ESR:
6259 	case APIC_TMICT:
6260 		/*
6261 		 * EOI, ESR: WRMSR of a non-zero value causes #GP(0).
6262 		 * TMICT: A write of 0 to the initial-count register effectively
6263 		 *        stops the local APIC timer, in both one-shot and
6264 		 *        periodic mode.
6265 		 */
6266 		*val = 0;
6267 		break;
6268 	case APIC_SPIV:
6269 	case APIC_LVTT:
6270 	case APIC_LVTTHMR:
6271 	case APIC_LVTPC:
6272 	case APIC_LVT0:
6273 	case APIC_LVT1:
6274 	case APIC_LVTERR:
6275 	case APIC_TDCR:
6276 		/*
6277 		 * To avoid writing a 1 to a reserved bit or causing some other
6278 		 * unintended side effect, read the current value and use it as
6279 		 * the write value.
6280 		 */
6281 		*val = apic_read(reg);
6282 		break;
6283 	case APIC_CMCI:
6284 		if (!apic_lvt_entry_supported(6))
6285 			return false;
6286 		*val = apic_read(reg);
6287 		break;
6288 	case APIC_ICR:
6289 		*val = 0x40000 | 0xf1;
6290 		break;
6291 	case APIC_SELF_IPI:
6292 		/*
6293 		 * With special processing (i.e., virtualize x2APIC mode +
6294 		 * virtual interrupt delivery), writing zero causes an
6295 		 * APIC-write VM exit. We plan to add a test for enabling
6296 		 * "virtual-interrupt delivery" in VMCS12, and that's where we
6297 		 * will test a self IPI with special processing.
6298 		 */
6299 		*val = 0x0;
6300 		break;
6301 	default:
6302 		return false;
6303 	}
6304 
6305 	return true;
6306 }
6307 
6308 static bool special_processing_applies(u32 reg, u64 *val,
6309 				       bool virt_int_delivery)
6310 {
6311 	bool special_processing =
6312 		(reg == APIC_TASKPRI) ||
6313 		(virt_int_delivery &&
6314 		 (reg == APIC_EOI || reg == APIC_SELF_IPI));
6315 
6316 	if (special_processing) {
6317 		TEST_ASSERT(get_x2apic_wr_val(reg, val));
6318 		return true;
6319 	}
6320 
6321 	return false;
6322 }
6323 
6324 static void virt_x2apic_mode_wr_expectation(
6325 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6326 	bool virt_int_delivery,
6327 	struct virt_x2apic_mode_expectation *expectation)
6328 {
6329 	expectation->wr_exit_reason = VMX_VMCALL;
6330 	expectation->wr_val = MAGIC_VAL_1;
6331 	expectation->wr_only = false;
6332 
6333 	if (virt_x2apic_mode_on &&
6334 	    special_processing_applies(reg, &expectation->wr_val,
6335 				       virt_int_delivery)) {
6336 		expectation->wr_behavior = X2APIC_ACCESS_VIRTUALIZED;
6337 		if (reg == APIC_SELF_IPI)
6338 			expectation->wr_exit_reason = VMX_APIC_WRITE;
6339 	} else if (!disable_x2apic &&
6340 		   get_x2apic_wr_val(reg, &expectation->wr_val)) {
6341 		expectation->wr_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6342 		if (reg == APIC_EOI || reg == APIC_SELF_IPI)
6343 			expectation->wr_only = true;
6344 		if (reg == APIC_ICR)
6345 			expectation->wr_exit_reason = VMX_EXTINT;
6346 	} else {
6347 		expectation->wr_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6348 		/*
6349 		 * Writing 1 to a reserved bit triggers a #GP.
6350 		 * Thus, set the write value to 0, which seems
6351 		 * the most likely to detect a missed #GP.
6352 		 */
6353 		expectation->wr_val = 0;
6354 	}
6355 }
6356 
6357 static void virt_x2apic_mode_exit_expectation(
6358 	u32 reg, struct virt_x2apic_mode_config *config,
6359 	struct virt_x2apic_mode_expectation *expectation)
6360 {
6361 	struct apic_reg_virt_config *base_config =
6362 		&config->apic_reg_virt_config;
6363 	bool virt_x2apic_mode_on =
6364 		base_config->virtualize_x2apic_mode &&
6365 		config->use_msr_bitmaps &&
6366 		config->disable_x2apic_msr_intercepts &&
6367 		base_config->activate_secondary_controls;
6368 
6369 	virt_x2apic_mode_wr_expectation(
6370 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6371 		config->virtual_interrupt_delivery, expectation);
6372 	virt_x2apic_mode_rd_expectation(
6373 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6374 		base_config->apic_register_virtualization,
6375 		config->virtual_interrupt_delivery, expectation);
6376 }
6377 
6378 struct virt_x2apic_mode_test_case virt_x2apic_mode_tests[] = {
6379 	/*
6380 	 * Baseline "virtualize x2APIC mode" configuration:
6381 	 *   - virtualize x2APIC mode
6382 	 *   - virtual-interrupt delivery
6383 	 *   - APIC-register virtualization
6384 	 *   - x2APIC MSR intercepts disabled
6385 	 *
6386 	 * Reads come from virtual APIC page, special processing applies to
6387 	 * VTPR, EOI, and SELF IPI, and all other writes pass through to L1
6388 	 * APIC.
6389 	 */
6390 	{
6391 		.name = "Baseline",
6392 		.virt_x2apic_mode_config = {
6393 			.virtual_interrupt_delivery = true,
6394 			.use_msr_bitmaps = true,
6395 			.disable_x2apic_msr_intercepts = true,
6396 			.disable_x2apic = false,
6397 			.apic_reg_virt_config = {
6398 				.apic_register_virtualization = true,
6399 				.use_tpr_shadow = true,
6400 				.virtualize_apic_accesses = false,
6401 				.virtualize_x2apic_mode = true,
6402 				.activate_secondary_controls = true,
6403 			},
6404 		},
6405 	},
6406 	{
6407 		.name = "Baseline w/ x2apic disabled",
6408 		.virt_x2apic_mode_config = {
6409 			.virtual_interrupt_delivery = true,
6410 			.use_msr_bitmaps = true,
6411 			.disable_x2apic_msr_intercepts = true,
6412 			.disable_x2apic = true,
6413 			.apic_reg_virt_config = {
6414 				.apic_register_virtualization = true,
6415 				.use_tpr_shadow = true,
6416 				.virtualize_apic_accesses = false,
6417 				.virtualize_x2apic_mode = true,
6418 				.activate_secondary_controls = true,
6419 			},
6420 		},
6421 	},
6422 
6423 	/*
6424 	 * Baseline, minus virtual-interrupt delivery. Reads come from virtual
6425 	 * APIC page, special processing applies to VTPR, and all other writes
6426 	 * pass through to L1 APIC.
6427 	 */
6428 	{
6429 		.name = "Baseline - virtual interrupt delivery",
6430 		.virt_x2apic_mode_config = {
6431 			.virtual_interrupt_delivery = false,
6432 			.use_msr_bitmaps = true,
6433 			.disable_x2apic_msr_intercepts = true,
6434 			.disable_x2apic = false,
6435 			.apic_reg_virt_config = {
6436 				.apic_register_virtualization = true,
6437 				.use_tpr_shadow = true,
6438 				.virtualize_apic_accesses = false,
6439 				.virtualize_x2apic_mode = true,
6440 				.activate_secondary_controls = true,
6441 			},
6442 		},
6443 	},
6444 
6445 	/*
6446 	 * Baseline, minus APIC-register virtualization. x2APIC reads pass
6447 	 * through to L1's APIC, unless reading VTPR
6448 	 */
6449 	{
6450 		.name = "Virtualize x2APIC mode, no APIC reg virt",
6451 		.virt_x2apic_mode_config = {
6452 			.virtual_interrupt_delivery = true,
6453 			.use_msr_bitmaps = true,
6454 			.disable_x2apic_msr_intercepts = true,
6455 			.disable_x2apic = false,
6456 			.apic_reg_virt_config = {
6457 				.apic_register_virtualization = false,
6458 				.use_tpr_shadow = true,
6459 				.virtualize_apic_accesses = false,
6460 				.virtualize_x2apic_mode = true,
6461 				.activate_secondary_controls = true,
6462 			},
6463 		},
6464 	},
6465 	{
6466 		.name = "Virtualize x2APIC mode, no APIC reg virt, x2APIC off",
6467 		.virt_x2apic_mode_config = {
6468 			.virtual_interrupt_delivery = true,
6469 			.use_msr_bitmaps = true,
6470 			.disable_x2apic_msr_intercepts = true,
6471 			.disable_x2apic = true,
6472 			.apic_reg_virt_config = {
6473 				.apic_register_virtualization = false,
6474 				.use_tpr_shadow = true,
6475 				.virtualize_apic_accesses = false,
6476 				.virtualize_x2apic_mode = true,
6477 				.activate_secondary_controls = true,
6478 			},
6479 		},
6480 	},
6481 
6482 	/*
6483 	 * Enable "virtualize x2APIC mode" and "APIC-register virtualization",
6484 	 * and disable intercepts for the x2APIC MSRs, but fail to enable
6485 	 * "activate secondary controls" (i.e. L2 gets access to L1's x2APIC
6486 	 * MSRs).
6487 	 */
6488 	{
6489 		.name = "Fail to enable activate secondary controls",
6490 		.virt_x2apic_mode_config = {
6491 			.virtual_interrupt_delivery = true,
6492 			.use_msr_bitmaps = true,
6493 			.disable_x2apic_msr_intercepts = true,
6494 			.disable_x2apic = false,
6495 			.apic_reg_virt_config = {
6496 				.apic_register_virtualization = true,
6497 				.use_tpr_shadow = true,
6498 				.virtualize_apic_accesses = false,
6499 				.virtualize_x2apic_mode = true,
6500 				.activate_secondary_controls = false,
6501 			},
6502 		},
6503 	},
6504 
6505 	/*
6506 	 * Enable "APIC-register virtualization" and enable "activate secondary
6507 	 * controls" and disable intercepts for the x2APIC MSRs, but do not
6508 	 * enable the "virtualize x2APIC mode" VM-execution control (i.e. L2
6509 	 * gets access to L1's x2APIC MSRs).
6510 	 */
6511 	{
6512 		.name = "Fail to enable virtualize x2APIC mode",
6513 		.virt_x2apic_mode_config = {
6514 			.virtual_interrupt_delivery = true,
6515 			.use_msr_bitmaps = true,
6516 			.disable_x2apic_msr_intercepts = true,
6517 			.disable_x2apic = false,
6518 			.apic_reg_virt_config = {
6519 				.apic_register_virtualization = true,
6520 				.use_tpr_shadow = true,
6521 				.virtualize_apic_accesses = false,
6522 				.virtualize_x2apic_mode = false,
6523 				.activate_secondary_controls = true,
6524 			},
6525 		},
6526 	},
6527 
6528 	/*
6529 	 * Disable "Virtualize x2APIC mode", disable x2APIC MSR intercepts, and
6530 	 * enable "APIC-register virtualization" --> L2 gets L1's x2APIC MSRs.
6531 	 */
6532 	{
6533 		.name = "Baseline",
6534 		.virt_x2apic_mode_config = {
6535 			.virtual_interrupt_delivery = true,
6536 			.use_msr_bitmaps = true,
6537 			.disable_x2apic_msr_intercepts = true,
6538 			.disable_x2apic = false,
6539 			.apic_reg_virt_config = {
6540 				.apic_register_virtualization = true,
6541 				.use_tpr_shadow = true,
6542 				.virtualize_apic_accesses = false,
6543 				.virtualize_x2apic_mode = false,
6544 				.activate_secondary_controls = true,
6545 			},
6546 		},
6547 	},
6548 };
6549 
6550 enum X2apic_op {
6551 	X2APIC_OP_RD,
6552 	X2APIC_OP_WR,
6553 	X2APIC_TERMINATE,
6554 };
6555 
6556 static u64 vmx_x2apic_read(u32 reg)
6557 {
6558 	u32 msr_addr = x2apic_msr(reg);
6559 	u64 val;
6560 
6561 	val = rdmsr(msr_addr);
6562 
6563 	return val;
6564 }
6565 
6566 static void vmx_x2apic_write(u32 reg, u64 val)
6567 {
6568 	u32 msr_addr = x2apic_msr(reg);
6569 
6570 	wrmsr(msr_addr, val);
6571 }
6572 
6573 struct virt_x2apic_mode_guest_args {
6574 	enum X2apic_op op;
6575 	u32 reg;
6576 	u64 val;
6577 	bool should_gp;
6578 	u64 (*virt_fn)(u64);
6579 } virt_x2apic_mode_guest_args;
6580 
6581 static volatile bool handle_x2apic_gp_ran;
6582 static volatile u32 handle_x2apic_gp_insn_len;
6583 static void handle_x2apic_gp(struct ex_regs *regs)
6584 {
6585 	handle_x2apic_gp_ran = true;
6586 	regs->rip += handle_x2apic_gp_insn_len;
6587 }
6588 
6589 static handler setup_x2apic_gp_handler(void)
6590 {
6591 	handler old_handler;
6592 
6593 	old_handler = handle_exception(GP_VECTOR, handle_x2apic_gp);
6594 	/* RDMSR and WRMSR are both 2 bytes, assuming no prefixes. */
6595 	handle_x2apic_gp_insn_len = 2;
6596 
6597 	return old_handler;
6598 }
6599 
6600 static void teardown_x2apic_gp_handler(handler old_handler)
6601 {
6602 	handle_exception(GP_VECTOR, old_handler);
6603 
6604 	/*
6605 	 * Defensively reset instruction length, so that if the handler is
6606 	 * incorrectly used, it will loop infinitely, rather than run off into
6607 	 * la la land.
6608 	 */
6609 	handle_x2apic_gp_insn_len = 0;
6610 	handle_x2apic_gp_ran = false;
6611 }
6612 
6613 static void virt_x2apic_mode_guest(void)
6614 {
6615 	volatile struct virt_x2apic_mode_guest_args *args =
6616 		&virt_x2apic_mode_guest_args;
6617 
6618 	for (;;) {
6619 		enum X2apic_op op = args->op;
6620 		u32 reg = args->reg;
6621 		u64 val = args->val;
6622 		bool should_gp = args->should_gp;
6623 		u64 (*virt_fn)(u64) = args->virt_fn;
6624 		handler old_handler;
6625 
6626 		if (op == X2APIC_TERMINATE)
6627 			break;
6628 
6629 		if (should_gp) {
6630 			TEST_ASSERT(!handle_x2apic_gp_ran);
6631 			old_handler = setup_x2apic_gp_handler();
6632 		}
6633 
6634 		if (op == X2APIC_OP_RD) {
6635 			u64 ret = vmx_x2apic_read(reg);
6636 
6637 			if (!should_gp) {
6638 				u64 want = virt_fn(val);
6639 				u64 got = virt_fn(ret);
6640 
6641 				report(got == want,
6642 				       "APIC read; got 0x%lx, want 0x%lx.",
6643 				       got, want);
6644 			}
6645 		} else if (op == X2APIC_OP_WR) {
6646 			vmx_x2apic_write(reg, val);
6647 		}
6648 
6649 		if (should_gp) {
6650 			report(handle_x2apic_gp_ran,
6651 			       "x2APIC op triggered GP.");
6652 			teardown_x2apic_gp_handler(old_handler);
6653 		}
6654 
6655 		/*
6656 		 * The L1 should always execute a vmcall after it's done testing
6657 		 * an individual APIC operation. This helps to validate that the
6658 		 * L1 and L2 are in sync with each other, as expected.
6659 		 */
6660 		vmcall();
6661 	}
6662 }
6663 
6664 static void test_x2apic_rd(
6665 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6666 	u32 *virtual_apic_page)
6667 {
6668 	u64 val = expectation->rd_val;
6669 	u32 exit_reason_want = expectation->rd_exit_reason;
6670 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6671 
6672 	report_prefix_pushf("x2apic - reading 0x%03x", reg);
6673 
6674 	/* Configure guest to do an x2apic read */
6675 	args->op = X2APIC_OP_RD;
6676 	args->reg = reg;
6677 	args->val = val;
6678 	args->should_gp = expectation->rd_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6679 	args->virt_fn = expectation->virt_fn;
6680 
6681 	/* Setup virtual APIC page */
6682 	if (expectation->rd_behavior == X2APIC_ACCESS_VIRTUALIZED)
6683 		virtual_apic_page[apic_reg_index(reg)] = (u32)val;
6684 
6685 	/* Enter guest */
6686 	enter_guest();
6687 
6688 	if (exit_reason_want != VMX_VMCALL) {
6689 		report(false, "Oops, bad exit expectation: %u.",
6690 		       exit_reason_want);
6691 	}
6692 
6693 	skip_exit_vmcall();
6694 	report_prefix_pop();
6695 }
6696 
6697 static volatile bool handle_x2apic_ipi_ran;
6698 static void handle_x2apic_ipi(isr_regs_t *regs)
6699 {
6700 	handle_x2apic_ipi_ran = true;
6701 	eoi();
6702 }
6703 
6704 static void test_x2apic_wr(
6705 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6706 	u32 *virtual_apic_page)
6707 {
6708 	u64 val = expectation->wr_val;
6709 	u32 exit_reason_want = expectation->wr_exit_reason;
6710 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6711 	int ipi_vector = 0xf1;
6712 	u32 restore_val = 0;
6713 
6714 	report_prefix_pushf("x2apic - writing 0x%lx to 0x%03x", val, reg);
6715 
6716 	/* Configure guest to do an x2apic read */
6717 	args->op = X2APIC_OP_WR;
6718 	args->reg = reg;
6719 	args->val = val;
6720 	args->should_gp = expectation->wr_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6721 
6722 	/* Setup virtual APIC page */
6723 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED)
6724 		virtual_apic_page[apic_reg_index(reg)] = 0;
6725 	if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH && !expectation->wr_only)
6726 		restore_val = apic_read(reg);
6727 
6728 	/* Setup IPI handler */
6729 	handle_x2apic_ipi_ran = false;
6730 	handle_irq(ipi_vector, handle_x2apic_ipi);
6731 
6732 	/* Enter guest */
6733 	enter_guest();
6734 
6735 	/*
6736 	 * Validate the behavior and
6737 	 * pass a magic value back to the guest.
6738 	 */
6739 	if (exit_reason_want == VMX_EXTINT) {
6740 		assert_exit_reason(exit_reason_want);
6741 
6742 		/* Clear the external interrupt. */
6743 		irq_enable();
6744 		asm volatile ("nop");
6745 		irq_disable();
6746 		report(handle_x2apic_ipi_ran,
6747 		       "Got pending interrupt after IRQ enabled.");
6748 
6749 		enter_guest();
6750 	} else if (exit_reason_want == VMX_APIC_WRITE) {
6751 		assert_exit_reason(exit_reason_want);
6752 		report(virtual_apic_page[apic_reg_index(reg)] == val,
6753 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%lx",
6754 		       apic_reg_index(reg),
6755 		       virtual_apic_page[apic_reg_index(reg)], val);
6756 
6757 		/* Reenter guest so it can consume/check rcx and exit again. */
6758 		enter_guest();
6759 	} else if (exit_reason_want != VMX_VMCALL) {
6760 		report(false, "Oops, bad exit expectation: %u.",
6761 		       exit_reason_want);
6762 	}
6763 
6764 	assert_exit_reason(VMX_VMCALL);
6765 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED) {
6766 		u64 want = val;
6767 		u32 got = virtual_apic_page[apic_reg_index(reg)];
6768 
6769 		report(got == want, "x2APIC write; got 0x%x, want 0x%lx", got,
6770 		       want);
6771 	} else if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH) {
6772 		if (!expectation->wr_only) {
6773 			u32 got = apic_read(reg);
6774 			bool ok;
6775 
6776 			/*
6777 			 * When L1's TPR is passed through to L2, the lower
6778 			 * nibble can be lost. For example, if L2 executes
6779 			 * WRMSR(0x808, 0x78), then, L1 might read 0x70.
6780 			 *
6781 			 * Here's how the lower nibble can get lost:
6782 			 *   1. L2 executes WRMSR(0x808, 0x78).
6783 			 *   2. L2 exits to L0 with a WRMSR exit.
6784 			 *   3. L0 emulates WRMSR, by writing L1's TPR.
6785 			 *   4. L0 re-enters L2.
6786 			 *   5. L2 exits to L0 (reason doesn't matter).
6787 			 *   6. L0 reflects L2's exit to L1.
6788 			 *   7. Before entering L1, L0 exits to user-space
6789 			 *      (e.g., to satisfy TPR access reporting).
6790 			 *   8. User-space executes KVM_SET_REGS ioctl, which
6791 			 *      clears the lower nibble of L1's TPR.
6792 			 */
6793 			if (reg == APIC_TASKPRI) {
6794 				got = apic_virt_nibble1(got);
6795 				val = apic_virt_nibble1(val);
6796 			}
6797 
6798 			ok = got == val;
6799 			report(ok,
6800 			       "non-virtualized write; val is 0x%x, want 0x%lx",
6801 			       got, val);
6802 			apic_write(reg, restore_val);
6803 		} else {
6804 			report(true, "non-virtualized and write-only OK");
6805 		}
6806 	}
6807 	skip_exit_insn();
6808 
6809 	report_prefix_pop();
6810 }
6811 
6812 static enum Config_type configure_virt_x2apic_mode_test(
6813 	struct virt_x2apic_mode_config *virt_x2apic_mode_config,
6814 	u8 *msr_bitmap_page)
6815 {
6816 	int msr;
6817 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6818 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6819 
6820 	/* x2apic-specific VMCS config */
6821 	if (virt_x2apic_mode_config->use_msr_bitmaps) {
6822 		/* virt_x2apic_mode_test() checks for MSR bitmaps support */
6823 		cpu_exec_ctrl0 |= CPU_MSR_BITMAP;
6824 	} else {
6825 		cpu_exec_ctrl0 &= ~CPU_MSR_BITMAP;
6826 	}
6827 
6828 	if (virt_x2apic_mode_config->virtual_interrupt_delivery) {
6829 		if (!(ctrl_cpu_rev[1].clr & CPU_VINTD)) {
6830 			report_skip("VM-execution control \"virtual-interrupt delivery\" NOT supported.\n");
6831 			return CONFIG_TYPE_UNSUPPORTED;
6832 		}
6833 		cpu_exec_ctrl1 |= CPU_VINTD;
6834 	} else {
6835 		cpu_exec_ctrl1 &= ~CPU_VINTD;
6836 	}
6837 
6838 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6839 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6840 
6841 	/* x2APIC MSR intercepts are usually off for "Virtualize x2APIC mode" */
6842 	for (msr = 0x800; msr <= 0x8ff; msr++) {
6843 		if (virt_x2apic_mode_config->disable_x2apic_msr_intercepts) {
6844 			clear_bit(msr, msr_bitmap_page + 0x000);
6845 			clear_bit(msr, msr_bitmap_page + 0x800);
6846 		} else {
6847 			set_bit(msr, msr_bitmap_page + 0x000);
6848 			set_bit(msr, msr_bitmap_page + 0x800);
6849 		}
6850 	}
6851 
6852 	/* x2APIC mode can impact virtualization */
6853 	reset_apic();
6854 	if (!virt_x2apic_mode_config->disable_x2apic)
6855 		enable_x2apic();
6856 
6857 	return configure_apic_reg_virt_test(
6858 		&virt_x2apic_mode_config->apic_reg_virt_config);
6859 }
6860 
6861 static void virt_x2apic_mode_test(void)
6862 {
6863 	u32 *virtual_apic_page;
6864 	u8 *msr_bitmap_page;
6865 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6866 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6867 	int i;
6868 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6869 
6870 	if (!cpu_has_apicv()) {
6871 		report_skip(__func__);
6872 		return;
6873 	}
6874 
6875 	/*
6876 	 * This is to exercise an issue in KVM's logic to merge L0's and L1's
6877 	 * MSR bitmaps. Previously, an L1 could get at L0's x2APIC MSRs by
6878 	 * writing the IA32_SPEC_CTRL MSR or the IA32_PRED_CMD MSRs. KVM would
6879 	 * then proceed to manipulate the MSR bitmaps, as if VMCS12 had the
6880 	 * "Virtualize x2APIC mod" control set, even when it didn't.
6881 	 */
6882 	if (has_spec_ctrl())
6883 		wrmsr(MSR_IA32_SPEC_CTRL, 1);
6884 
6885 	/*
6886 	 * Check that VMCS12 supports:
6887 	 *   - "Virtual-APIC address", indicated by "use TPR shadow"
6888 	 *   - "MSR-bitmap address", indicated by "use MSR bitmaps"
6889 	 */
6890 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
6891 		report_skip("VM-execution control \"use TPR shadow\" NOT supported.\n");
6892 		return;
6893 	} else if (!(ctrl_cpu_rev[0].clr & CPU_MSR_BITMAP)) {
6894 		report_skip("VM-execution control \"use MSR bitmaps\" NOT supported.\n");
6895 		return;
6896 	}
6897 
6898 	test_set_guest(virt_x2apic_mode_guest);
6899 
6900 	virtual_apic_page = alloc_page();
6901 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
6902 
6903 	msr_bitmap_page = alloc_page();
6904 	memset(msr_bitmap_page, 0xff, PAGE_SIZE);
6905 	vmcs_write(MSR_BITMAP, virt_to_phys(msr_bitmap_page));
6906 
6907 	for (i = 0; i < ARRAY_SIZE(virt_x2apic_mode_tests); i++) {
6908 		struct virt_x2apic_mode_test_case *virt_x2apic_mode_test_case =
6909 			&virt_x2apic_mode_tests[i];
6910 		struct virt_x2apic_mode_config *virt_x2apic_mode_config =
6911 			&virt_x2apic_mode_test_case->virt_x2apic_mode_config;
6912 		enum Config_type config_type;
6913 		u32 reg;
6914 
6915 		printf("--- %s test ---\n", virt_x2apic_mode_test_case->name);
6916 		config_type =
6917 			configure_virt_x2apic_mode_test(virt_x2apic_mode_config,
6918 							msr_bitmap_page);
6919 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
6920 			report_skip("Skip because of missing features.\n");
6921 			continue;
6922 		} else if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6923 			enter_guest_with_bad_controls();
6924 			continue;
6925 		}
6926 
6927 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6928 			struct virt_x2apic_mode_expectation expectation;
6929 
6930 			virt_x2apic_mode_exit_expectation(
6931 				reg, virt_x2apic_mode_config, &expectation);
6932 
6933 			test_x2apic_rd(reg, &expectation, virtual_apic_page);
6934 			test_x2apic_wr(reg, &expectation, virtual_apic_page);
6935 		}
6936 	}
6937 
6938 
6939 	/* Terminate the guest */
6940 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6941 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6942 	args->op = X2APIC_TERMINATE;
6943 	enter_guest();
6944 	assert_exit_reason(VMX_VMCALL);
6945 }
6946 
6947 static void test_ctl_reg(const char *cr_name, u64 cr, u64 fixed0, u64 fixed1)
6948 {
6949 	u64 val;
6950 	u64 cr_saved = vmcs_read(cr);
6951 	int i;
6952 
6953 	val = fixed0 & fixed1;
6954 	if (cr == HOST_CR4)
6955 		vmcs_write(cr, val | X86_CR4_PAE);
6956 	else
6957 		vmcs_write(cr, val);
6958 	report_prefix_pushf("%s %lx", cr_name, val);
6959 	if (val == fixed0)
6960 		test_vmx_vmlaunch(0);
6961 	else
6962 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6963 	report_prefix_pop();
6964 
6965 	for (i = 0; i < 64; i++) {
6966 
6967 		/* Set a bit when the corresponding bit in fixed1 is 0 */
6968 		if ((fixed1 & (1ull << i)) == 0) {
6969 			if (cr == HOST_CR4 && ((1ull << i) & X86_CR4_SMEP ||
6970 					       (1ull << i) & X86_CR4_SMAP))
6971 				continue;
6972 
6973 			vmcs_write(cr, cr_saved | (1ull << i));
6974 			report_prefix_pushf("%s %llx", cr_name,
6975 						cr_saved | (1ull << i));
6976 			test_vmx_vmlaunch(
6977 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6978 			report_prefix_pop();
6979 		}
6980 
6981 		/* Unset a bit when the corresponding bit in fixed0 is 1 */
6982 		if (fixed0 & (1ull << i)) {
6983 			vmcs_write(cr, cr_saved & ~(1ull << i));
6984 			report_prefix_pushf("%s %llx", cr_name,
6985 						cr_saved & ~(1ull << i));
6986 			test_vmx_vmlaunch(
6987 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6988 			report_prefix_pop();
6989 		}
6990 	}
6991 
6992 	vmcs_write(cr, cr_saved);
6993 }
6994 
6995 /*
6996  * 1. The CR0 field must not set any bit to a value not supported in VMX
6997  *    operation.
6998  * 2. The CR4 field must not set any bit to a value not supported in VMX
6999  *    operation.
7000  * 3. On processors that support Intel 64 architecture, the CR3 field must
7001  *    be such that bits 63:52 and bits in the range 51:32 beyond the
7002  *    processor’s physical-address width must be 0.
7003  *
7004  *  [Intel SDM]
7005  */
7006 static void test_host_ctl_regs(void)
7007 {
7008 	u64 fixed0, fixed1, cr3, cr3_saved;
7009 	int i;
7010 
7011 	/* Test CR0 */
7012 	fixed0 = rdmsr(MSR_IA32_VMX_CR0_FIXED0);
7013 	fixed1 = rdmsr(MSR_IA32_VMX_CR0_FIXED1);
7014 	test_ctl_reg("HOST_CR0", HOST_CR0, fixed0, fixed1);
7015 
7016 	/* Test CR4 */
7017 	fixed0 = rdmsr(MSR_IA32_VMX_CR4_FIXED0);
7018 	fixed1 = rdmsr(MSR_IA32_VMX_CR4_FIXED1) &
7019 		 ~(X86_CR4_SMEP | X86_CR4_SMAP);
7020 	test_ctl_reg("HOST_CR4", HOST_CR4, fixed0, fixed1);
7021 
7022 	/* Test CR3 */
7023 	cr3_saved = vmcs_read(HOST_CR3);
7024 	for (i = cpuid_maxphyaddr(); i < 64; i++) {
7025 		cr3 = cr3_saved | (1ul << i);
7026 		vmcs_write(HOST_CR3, cr3);
7027 		report_prefix_pushf("HOST_CR3 %lx", cr3);
7028 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7029 		report_prefix_pop();
7030 	}
7031 
7032 	vmcs_write(HOST_CR3, cr3_saved);
7033 }
7034 
7035 static void test_efer_vmlaunch(u32 fld, bool ok)
7036 {
7037 	if (fld == HOST_EFER) {
7038 		if (ok)
7039 			test_vmx_vmlaunch(0);
7040 		else
7041 			test_vmx_vmlaunch2(VMXERR_ENTRY_INVALID_CONTROL_FIELD,
7042 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7043 	} else {
7044 		test_guest_state("EFER test", !ok, GUEST_EFER, "GUEST_EFER");
7045 	}
7046 }
7047 
7048 static void test_efer_one(u32 fld, const char * fld_name, u64 efer,
7049 			  u32 ctrl_fld, u64 ctrl,
7050 			  int i, const char *efer_bit_name)
7051 {
7052 	bool ok;
7053 
7054 	ok = true;
7055 	if (ctrl_fld == EXI_CONTROLS && (ctrl & EXI_LOAD_EFER)) {
7056 		if (!!(efer & EFER_LMA) != !!(ctrl & EXI_HOST_64))
7057 			ok = false;
7058 		if (!!(efer & EFER_LME) != !!(ctrl & EXI_HOST_64))
7059 			ok = false;
7060 	}
7061 	if (ctrl_fld == ENT_CONTROLS && (ctrl & ENT_LOAD_EFER)) {
7062 		/* Check LMA too since CR0.PG is set.  */
7063 		if (!!(efer & EFER_LMA) != !!(ctrl & ENT_GUEST_64))
7064 			ok = false;
7065 		if (!!(efer & EFER_LME) != !!(ctrl & ENT_GUEST_64))
7066 			ok = false;
7067 	}
7068 
7069 	/*
7070 	 * Skip the test if it would enter the guest in 32-bit mode.
7071 	 * Perhaps write the test in assembly and make sure it
7072 	 * can be run in either mode?
7073 	 */
7074 	if (fld == GUEST_EFER && ok && !(ctrl & ENT_GUEST_64))
7075 		return;
7076 
7077 	vmcs_write(ctrl_fld, ctrl);
7078 	vmcs_write(fld, efer);
7079 	report_prefix_pushf("%s %s bit turned %s, controls %s",
7080 			    fld_name, efer_bit_name,
7081 			    (i & 1) ? "on" : "off",
7082 			    (i & 2) ? "on" : "off");
7083 
7084 	test_efer_vmlaunch(fld, ok);
7085 	report_prefix_pop();
7086 }
7087 
7088 static void test_efer_bit(u32 fld, const char * fld_name,
7089 			  u32 ctrl_fld, u64 ctrl_bit, u64 efer_bit,
7090 			  const char *efer_bit_name)
7091 {
7092 	u64 efer_saved = vmcs_read(fld);
7093 	u32 ctrl_saved = vmcs_read(ctrl_fld);
7094 	int i;
7095 
7096 	for (i = 0; i < 4; i++) {
7097 		u64 efer = efer_saved & ~efer_bit;
7098 		u64 ctrl = ctrl_saved & ~ctrl_bit;
7099 
7100 		if (i & 1)
7101 			efer |= efer_bit;
7102 		if (i & 2)
7103 			ctrl |= ctrl_bit;
7104 
7105 		test_efer_one(fld, fld_name, efer, ctrl_fld, ctrl,
7106 			      i, efer_bit_name);
7107 	}
7108 
7109 	vmcs_write(ctrl_fld, ctrl_saved);
7110 	vmcs_write(fld, efer_saved);
7111 }
7112 
7113 static void test_efer(u32 fld, const char * fld_name, u32 ctrl_fld,
7114 		      u64 ctrl_bit1, u64 ctrl_bit2)
7115 {
7116 	u64 efer_saved = vmcs_read(fld);
7117 	u32 ctrl_saved = vmcs_read(ctrl_fld);
7118 	u64 efer_reserved_bits =  ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
7119 	u64 i;
7120 	u64 efer;
7121 
7122 	if (cpu_has_efer_nx())
7123 		efer_reserved_bits &= ~EFER_NX;
7124 
7125 	if (!ctrl_bit1) {
7126 		printf("\"Load-IA32-EFER\" exit control not supported\n");
7127 		goto test_entry_exit_mode;
7128 	}
7129 
7130 	report_prefix_pushf("%s %lx", fld_name, efer_saved);
7131 	test_efer_vmlaunch(fld, true);
7132 	report_prefix_pop();
7133 
7134 	/*
7135 	 * Check reserved bits
7136 	 */
7137 	vmcs_write(ctrl_fld, ctrl_saved & ~ctrl_bit1);
7138 	for (i = 0; i < 64; i++) {
7139 		if ((1ull << i) & efer_reserved_bits) {
7140 			efer = efer_saved | (1ull << i);
7141 			vmcs_write(fld, efer);
7142 			report_prefix_pushf("%s %lx", fld_name, efer);
7143 			test_efer_vmlaunch(fld, true);
7144 			report_prefix_pop();
7145 		}
7146 	}
7147 
7148 	vmcs_write(ctrl_fld, ctrl_saved | ctrl_bit1);
7149 	for (i = 0; i < 64; i++) {
7150 		if ((1ull << i) & efer_reserved_bits) {
7151 			efer = efer_saved | (1ull << i);
7152 			vmcs_write(fld, efer);
7153 			report_prefix_pushf("%s %lx", fld_name, efer);
7154 			test_efer_vmlaunch(fld, false);
7155 			report_prefix_pop();
7156 		}
7157 	}
7158 
7159 	vmcs_write(ctrl_fld, ctrl_saved);
7160 	vmcs_write(fld, efer_saved);
7161 
7162 	/*
7163 	 * Check LMA and LME bits
7164 	 */
7165 	test_efer_bit(fld, fld_name,
7166 		      ctrl_fld, ctrl_bit1,
7167 		      EFER_LMA,
7168 		      "EFER_LMA");
7169 	test_efer_bit(fld, fld_name,
7170 		      ctrl_fld, ctrl_bit1,
7171 		      EFER_LME,
7172 		      "EFER_LME");
7173 
7174 test_entry_exit_mode:
7175 	test_efer_bit(fld, fld_name,
7176 		      ctrl_fld, ctrl_bit2,
7177 		      EFER_LMA,
7178 		      "EFER_LMA");
7179 	test_efer_bit(fld, fld_name,
7180 		      ctrl_fld, ctrl_bit2,
7181 		      EFER_LME,
7182 		      "EFER_LME");
7183 }
7184 
7185 /*
7186  * If the 'load IA32_EFER' VM-exit control is 1, bits reserved in the
7187  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7188  * the values of the LMA and LME bits in the field must each be that of
7189  * the 'host address-space size' VM-exit control.
7190  *
7191  *  [Intel SDM]
7192  */
7193 static void test_host_efer(void)
7194 {
7195 	test_efer(HOST_EFER, "HOST_EFER", EXI_CONTROLS,
7196 		  ctrl_exit_rev.clr & EXI_LOAD_EFER,
7197 		  EXI_HOST_64);
7198 }
7199 
7200 /*
7201  * If the 'load IA32_EFER' VM-enter control is 1, bits reserved in the
7202  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7203  * the values of the LMA and LME bits in the field must each be that of
7204  * the 'IA32e-mode guest' VM-exit control.
7205  */
7206 static void test_guest_efer(void)
7207 {
7208 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER)) {
7209 		printf("\"Load-IA32-EFER\" entry control not supported\n");
7210 		return;
7211 	}
7212 
7213 	vmcs_write(GUEST_EFER, rdmsr(MSR_EFER));
7214 	test_efer(GUEST_EFER, "GUEST_EFER", ENT_CONTROLS,
7215 		  ctrl_enter_rev.clr & ENT_LOAD_EFER,
7216 		  ENT_GUEST_64);
7217 }
7218 
7219 /*
7220  * PAT values higher than 8 are uninteresting since they're likely lumped
7221  * in with "8". We only test values above 8 one bit at a time,
7222  * in order to reduce the number of VM-Entries and keep the runtime reasonable.
7223  */
7224 #define	PAT_VAL_LIMIT	8
7225 
7226 static void test_pat(u32 field, const char * field_name, u32 ctrl_field,
7227 		     u64 ctrl_bit)
7228 {
7229 	u32 ctrl_saved = vmcs_read(ctrl_field);
7230 	u64 pat_saved = vmcs_read(field);
7231 	u64 i, val;
7232 	u32 j;
7233 	int error;
7234 
7235 	vmcs_clear_bits(ctrl_field, ctrl_bit);
7236 
7237 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7238 		/* Test PAT0..PAT7 fields */
7239 		for (j = 0; j < (i ? 8 : 1); j++) {
7240 			val = i << j * 8;
7241 			vmcs_write(field, val);
7242 			if (field == HOST_PAT) {
7243 				report_prefix_pushf("%s %lx", field_name, val);
7244 				test_vmx_vmlaunch(0);
7245 				report_prefix_pop();
7246 
7247 			} else {	// GUEST_PAT
7248 				test_guest_state("ENT_LOAD_PAT enabled", false,
7249 						 val, "GUEST_PAT");
7250 			}
7251 		}
7252 	}
7253 
7254 	vmcs_set_bits(ctrl_field, ctrl_bit);
7255 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7256 		/* Test PAT0..PAT7 fields */
7257 		for (j = 0; j < (i ? 8 : 1); j++) {
7258 			val = i << j * 8;
7259 			vmcs_write(field, val);
7260 
7261 			if (field == HOST_PAT) {
7262 				report_prefix_pushf("%s %lx", field_name, val);
7263 				if (i == 0x2 || i == 0x3 || i >= 0x8)
7264 					error =
7265 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
7266 				else
7267 					error = 0;
7268 
7269 				test_vmx_vmlaunch(error);
7270 				report_prefix_pop();
7271 
7272 			} else {	// GUEST_PAT
7273 				error = (i == 0x2 || i == 0x3 || i >= 0x8);
7274 				test_guest_state("ENT_LOAD_PAT enabled", !!error,
7275 						 val, "GUEST_PAT");
7276 			}
7277 
7278 		}
7279 	}
7280 
7281 	vmcs_write(ctrl_field, ctrl_saved);
7282 	vmcs_write(field, pat_saved);
7283 }
7284 
7285 /*
7286  *  If the "load IA32_PAT" VM-exit control is 1, the value of the field
7287  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7288  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7289  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7290  *  6 (WB), or 7 (UC-).
7291  *
7292  *  [Intel SDM]
7293  */
7294 static void test_load_host_pat(void)
7295 {
7296 	/*
7297 	 * "load IA32_PAT" VM-exit control
7298 	 */
7299 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT)) {
7300 		printf("\"Load-IA32-PAT\" exit control not supported\n");
7301 		return;
7302 	}
7303 
7304 	test_pat(HOST_PAT, "HOST_PAT", EXI_CONTROLS, EXI_LOAD_PAT);
7305 }
7306 
7307 union cpuidA_eax {
7308 	struct {
7309 		unsigned int version_id:8;
7310 		unsigned int num_counters_gp:8;
7311 		unsigned int bit_width:8;
7312 		unsigned int mask_length:8;
7313 	} split;
7314 	unsigned int full;
7315 };
7316 
7317 union cpuidA_edx {
7318 	struct {
7319 		unsigned int num_counters_fixed:5;
7320 		unsigned int bit_width_fixed:8;
7321 		unsigned int reserved:9;
7322 	} split;
7323 	unsigned int full;
7324 };
7325 
7326 static bool valid_pgc(u64 val)
7327 {
7328 	struct cpuid id;
7329 	union cpuidA_eax eax;
7330 	union cpuidA_edx edx;
7331 	u64 mask;
7332 
7333 	id = cpuid(0xA);
7334 	eax.full = id.a;
7335 	edx.full = id.d;
7336 	mask = ~(((1ull << eax.split.num_counters_gp) - 1) |
7337 		 (((1ull << edx.split.num_counters_fixed) - 1) << 32));
7338 
7339 	return !(val & mask);
7340 }
7341 
7342 static void test_pgc_vmlaunch(u32 xerror, u32 xreason, bool xfail, bool host)
7343 {
7344 	u32 inst_err;
7345 	u64 obs;
7346 	bool success;
7347 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7348 
7349 	if (host) {
7350 		success = vmlaunch_succeeds();
7351 		obs = rdmsr(data->msr);
7352 		if (!success) {
7353 			inst_err = vmcs_read(VMX_INST_ERROR);
7354 			report(xerror == inst_err, "vmlaunch failed, "
7355 			       "VMX Inst Error is %d (expected %d)",
7356 			       inst_err, xerror);
7357 		} else {
7358 			report(!data->enabled || data->exp == obs,
7359 			       "Host state is 0x%lx (expected 0x%lx)",
7360 			       obs, data->exp);
7361 			report(success != xfail, "vmlaunch succeeded");
7362 		}
7363 	} else {
7364 		test_guest_state("load GUEST_PERF_GLOBAL_CTRL", xfail,
7365 				 GUEST_PERF_GLOBAL_CTRL,
7366 				 "GUEST_PERF_GLOBAL_CTRL");
7367 	}
7368 }
7369 
7370 /*
7371  * test_load_perf_global_ctrl is a generic function for testing the
7372  * "load IA32_PERF_GLOBAL_CTRL" VM-{Entry,Exit} controls. This test function
7373  * tests the provided ctrl_val when disabled and enabled.
7374  *
7375  * @nr: VMCS field number corresponding to the host/guest state field
7376  * @name: Name of the above VMCS field for printing in test report
7377  * @ctrl_nr: VMCS field number corresponding to the VM-{Entry,Exit} control
7378  * @ctrl_val: Bit to set on the ctrl_field
7379  */
7380 static void test_perf_global_ctrl(u32 nr, const char *name, u32 ctrl_nr,
7381 				  const char *ctrl_name, u64 ctrl_val)
7382 {
7383 	u64 ctrl_saved = vmcs_read(ctrl_nr);
7384 	u64 pgc_saved = vmcs_read(nr);
7385 	u64 i, val;
7386 	bool host = nr == HOST_PERF_GLOBAL_CTRL;
7387 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7388 
7389 	data->msr = MSR_CORE_PERF_GLOBAL_CTRL;
7390 	msr_bmp_init();
7391 	vmcs_write(ctrl_nr, ctrl_saved & ~ctrl_val);
7392 	data->enabled = false;
7393 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=0 on %s",
7394 			    ctrl_name);
7395 
7396 	for (i = 0; i < 64; i++) {
7397 		val = 1ull << i;
7398 		vmcs_write(nr, val);
7399 		report_prefix_pushf("%s = 0x%lx", name, val);
7400 		test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7401 		report_prefix_pop();
7402 	}
7403 	report_prefix_pop();
7404 
7405 	vmcs_write(ctrl_nr, ctrl_saved | ctrl_val);
7406 	data->enabled = true;
7407 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=1 on %s",
7408 			    ctrl_name);
7409 	for (i = 0; i < 64; i++) {
7410 		val = 1ull << i;
7411 		data->exp = val;
7412 		vmcs_write(nr, val);
7413 		report_prefix_pushf("%s = 0x%lx", name, val);
7414 		if (valid_pgc(val)) {
7415 			test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7416 		} else {
7417 			if (host)
7418 				test_pgc_vmlaunch(
7419 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD,
7420 					0,
7421 					true,
7422 					host);
7423 			else
7424 				test_pgc_vmlaunch(
7425 					0,
7426 					VMX_ENTRY_FAILURE | VMX_FAIL_STATE,
7427 					true,
7428 					host);
7429 		}
7430 		report_prefix_pop();
7431 	}
7432 
7433 	data->enabled = false;
7434 	report_prefix_pop();
7435 	vmcs_write(ctrl_nr, ctrl_saved);
7436 	vmcs_write(nr, pgc_saved);
7437 }
7438 
7439 static void test_load_host_perf_global_ctrl(void)
7440 {
7441 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PERF)) {
7442 		printf("\"load IA32_PERF_GLOBAL_CTRL\" exit control not supported\n");
7443 		return;
7444 	}
7445 
7446 	test_perf_global_ctrl(HOST_PERF_GLOBAL_CTRL, "HOST_PERF_GLOBAL_CTRL",
7447 				   EXI_CONTROLS, "EXI_CONTROLS", EXI_LOAD_PERF);
7448 }
7449 
7450 
7451 static void test_load_guest_perf_global_ctrl(void)
7452 {
7453 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PERF)) {
7454 		printf("\"load IA32_PERF_GLOBAL_CTRL\" entry control not supported\n");
7455 		return;
7456 	}
7457 
7458 	test_perf_global_ctrl(GUEST_PERF_GLOBAL_CTRL, "GUEST_PERF_GLOBAL_CTRL",
7459 				   ENT_CONTROLS, "ENT_CONTROLS", ENT_LOAD_PERF);
7460 }
7461 
7462 
7463 /*
7464  * test_vmcs_field - test a value for the given VMCS field
7465  * @field: VMCS field
7466  * @field_name: string name of VMCS field
7467  * @bit_start: starting bit
7468  * @bit_end: ending bit
7469  * @val: value that the bit range must or must not contain
7470  * @valid_val: whether value given in 'val' must be valid or not
7471  * @error: expected VMCS error when vmentry fails for an invalid value
7472  */
7473 static void test_vmcs_field(u64 field, const char *field_name, u32 bit_start,
7474 			    u32 bit_end, u64 val, bool valid_val, u32 error)
7475 {
7476 	u64 field_saved = vmcs_read(field);
7477 	u32 i;
7478 	u64 tmp;
7479 	u32 bit_on;
7480 	u64 mask = ~0ull;
7481 
7482 	mask = (mask >> bit_end) << bit_end;
7483 	mask = mask | ((1 << bit_start) - 1);
7484 	tmp = (field_saved & mask) | (val << bit_start);
7485 
7486 	vmcs_write(field, tmp);
7487 	report_prefix_pushf("%s %lx", field_name, tmp);
7488 	if (valid_val)
7489 		test_vmx_vmlaunch(0);
7490 	else
7491 		test_vmx_vmlaunch(error);
7492 	report_prefix_pop();
7493 
7494 	for (i = bit_start; i <= bit_end; i = i + 2) {
7495 		bit_on = ((1ull < i) & (val << bit_start)) ? 0 : 1;
7496 		if (bit_on)
7497 			tmp = field_saved | (1ull << i);
7498 		else
7499 			tmp = field_saved & ~(1ull << i);
7500 		vmcs_write(field, tmp);
7501 		report_prefix_pushf("%s %lx", field_name, tmp);
7502 		if (valid_val)
7503 			test_vmx_vmlaunch(error);
7504 		else
7505 			test_vmx_vmlaunch(0);
7506 		report_prefix_pop();
7507 	}
7508 
7509 	vmcs_write(field, field_saved);
7510 }
7511 
7512 static void test_canonical(u64 field, const char * field_name, bool host)
7513 {
7514 	u64 addr_saved = vmcs_read(field);
7515 
7516 	/*
7517 	 * Use the existing value if possible.  Writing a random canonical
7518 	 * value is not an option as doing so would corrupt the field being
7519 	 * tested and likely hose the test.
7520 	 */
7521 	if (is_canonical(addr_saved)) {
7522 		if (host) {
7523 			report_prefix_pushf("%s %lx", field_name, addr_saved);
7524 			test_vmx_vmlaunch(0);
7525 			report_prefix_pop();
7526 		} else {
7527 			test_guest_state("Test canonical address", false,
7528 					 addr_saved, field_name);
7529 		}
7530 	}
7531 
7532 	vmcs_write(field, NONCANONICAL);
7533 
7534 	if (host) {
7535 		report_prefix_pushf("%s %llx", field_name, NONCANONICAL);
7536 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7537 		report_prefix_pop();
7538 	} else {
7539 		test_guest_state("Test non-canonical address", true,
7540 				 NONCANONICAL, field_name);
7541 	}
7542 
7543 	vmcs_write(field, addr_saved);
7544 }
7545 
7546 #define TEST_RPL_TI_FLAGS(reg, name)				\
7547 	test_vmcs_field(reg, name, 0, 2, 0x0, true,		\
7548 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7549 
7550 #define TEST_CS_TR_FLAGS(reg, name)				\
7551 	test_vmcs_field(reg, name, 3, 15, 0x0000, false,	\
7552 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7553 
7554 /*
7555  * 1. In the selector field for each of CS, SS, DS, ES, FS, GS and TR, the
7556  *    RPL (bits 1:0) and the TI flag (bit 2) must be 0.
7557  * 2. The selector fields for CS and TR cannot be 0000H.
7558  * 3. The selector field for SS cannot be 0000H if the "host address-space
7559  *    size" VM-exit control is 0.
7560  * 4. On processors that support Intel 64 architecture, the base-address
7561  *    fields for FS, GS and TR must contain canonical addresses.
7562  */
7563 static void test_host_segment_regs(void)
7564 {
7565 	u16 selector_saved;
7566 
7567 	/*
7568 	 * Test RPL and TI flags
7569 	 */
7570 	TEST_RPL_TI_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7571 	TEST_RPL_TI_FLAGS(HOST_SEL_SS, "HOST_SEL_SS");
7572 	TEST_RPL_TI_FLAGS(HOST_SEL_DS, "HOST_SEL_DS");
7573 	TEST_RPL_TI_FLAGS(HOST_SEL_ES, "HOST_SEL_ES");
7574 	TEST_RPL_TI_FLAGS(HOST_SEL_FS, "HOST_SEL_FS");
7575 	TEST_RPL_TI_FLAGS(HOST_SEL_GS, "HOST_SEL_GS");
7576 	TEST_RPL_TI_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7577 
7578 	/*
7579 	 * Test that CS and TR fields can not be 0x0000
7580 	 */
7581 	TEST_CS_TR_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7582 	TEST_CS_TR_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7583 
7584 	/*
7585 	 * SS field can not be 0x0000 if "host address-space size" VM-exit
7586 	 * control is 0
7587 	 */
7588 	selector_saved = vmcs_read(HOST_SEL_SS);
7589 	vmcs_write(HOST_SEL_SS, 0);
7590 	report_prefix_pushf("HOST_SEL_SS 0");
7591 	if (vmcs_read(EXI_CONTROLS) & EXI_HOST_64) {
7592 		test_vmx_vmlaunch(0);
7593 	} else {
7594 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7595 	}
7596 	report_prefix_pop();
7597 
7598 	vmcs_write(HOST_SEL_SS, selector_saved);
7599 
7600 	/*
7601 	 * Base address for FS, GS and TR must be canonical
7602 	 */
7603 	test_canonical(HOST_BASE_FS, "HOST_BASE_FS", true);
7604 	test_canonical(HOST_BASE_GS, "HOST_BASE_GS", true);
7605 	test_canonical(HOST_BASE_TR, "HOST_BASE_TR", true);
7606 }
7607 
7608 /*
7609  *  On processors that support Intel 64 architecture, the base-address
7610  *  fields for GDTR and IDTR must contain canonical addresses.
7611  */
7612 static void test_host_desc_tables(void)
7613 {
7614 	test_canonical(HOST_BASE_GDTR, "HOST_BASE_GDTR", true);
7615 	test_canonical(HOST_BASE_IDTR, "HOST_BASE_IDTR", true);
7616 }
7617 
7618 /*
7619  * If the "host address-space size" VM-exit control is 0, the following must
7620  * hold:
7621  *    - The "IA-32e mode guest" VM-entry control is 0.
7622  *    - Bit 17 of the CR4 field (corresponding to CR4.PCIDE) is 0.
7623  *    - Bits 63:32 in the RIP field are 0.
7624  *
7625  * If the "host address-space size" VM-exit control is 1, the following must
7626  * hold:
7627  *    - Bit 5 of the CR4 field (corresponding to CR4.PAE) is 1.
7628  *    - The RIP field contains a canonical address.
7629  *
7630  */
7631 static void test_host_addr_size(void)
7632 {
7633 	u64 cr4_saved = vmcs_read(HOST_CR4);
7634 	u64 rip_saved = vmcs_read(HOST_RIP);
7635 	u64 entry_ctrl_saved = vmcs_read(ENT_CONTROLS);
7636 	int i;
7637 	u64 tmp;
7638 
7639 	if (vmcs_read(EXI_CONTROLS) & EXI_HOST_64) {
7640 		vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7641 		report_prefix_pushf("\"IA-32e mode guest\" enabled");
7642 		test_vmx_vmlaunch(0);
7643 		report_prefix_pop();
7644 
7645 		vmcs_write(HOST_CR4, cr4_saved | X86_CR4_PCIDE);
7646 		report_prefix_pushf("\"CR4.PCIDE\" set");
7647 		test_vmx_vmlaunch(0);
7648 		report_prefix_pop();
7649 
7650 		for (i = 32; i <= 63; i = i + 4) {
7651 			tmp = rip_saved | 1ull << i;
7652 			vmcs_write(HOST_RIP, tmp);
7653 			report_prefix_pushf("HOST_RIP %lx", tmp);
7654 			test_vmx_vmlaunch(0);
7655 			report_prefix_pop();
7656 		}
7657 
7658 		if (cr4_saved & X86_CR4_PAE) {
7659 			vmcs_write(HOST_CR4, cr4_saved  & ~X86_CR4_PAE);
7660 			report_prefix_pushf("\"CR4.PAE\" unset");
7661 			test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7662 		} else {
7663 			report_prefix_pushf("\"CR4.PAE\" set");
7664 			test_vmx_vmlaunch(0);
7665 		}
7666 		report_prefix_pop();
7667 
7668 		vmcs_write(HOST_RIP, NONCANONICAL);
7669 		report_prefix_pushf("HOST_RIP %llx", NONCANONICAL);
7670 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7671 		report_prefix_pop();
7672 
7673 		vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7674 		vmcs_write(HOST_RIP, rip_saved);
7675 		vmcs_write(HOST_CR4, cr4_saved);
7676 
7677 		/* Restore host's active RIP and CR4 values. */
7678 		report_prefix_pushf("restore host state");
7679 		test_vmx_vmlaunch(0);
7680 		report_prefix_pop();
7681 	}
7682 }
7683 
7684 /*
7685  * Check that the virtual CPU checks the VMX Host State Area as
7686  * documented in the Intel SDM.
7687  */
7688 static void vmx_host_state_area_test(void)
7689 {
7690 	/*
7691 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
7692 	 * fail due to invalid guest state, should we make it that
7693 	 * far.
7694 	 */
7695 	vmcs_write(GUEST_RFLAGS, 0);
7696 
7697 	test_host_ctl_regs();
7698 
7699 	test_canonical(HOST_SYSENTER_ESP, "HOST_SYSENTER_ESP", true);
7700 	test_canonical(HOST_SYSENTER_EIP, "HOST_SYSENTER_EIP", true);
7701 
7702 	test_host_efer();
7703 	test_load_host_pat();
7704 	test_host_segment_regs();
7705 	test_host_desc_tables();
7706 	test_host_addr_size();
7707 	test_load_host_perf_global_ctrl();
7708 }
7709 
7710 /*
7711  * If the "load debug controls" VM-entry control is 1, bits 63:32 in
7712  * the DR7 field must be 0.
7713  *
7714  * [Intel SDM]
7715  */
7716 static void test_guest_dr7(void)
7717 {
7718 	u32 ent_saved = vmcs_read(ENT_CONTROLS);
7719 	u64 dr7_saved = vmcs_read(GUEST_DR7);
7720 	u64 val;
7721 	int i;
7722 
7723 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS) {
7724 		vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7725 		for (i = 0; i < 64; i++) {
7726 			val = 1ull << i;
7727 			vmcs_write(GUEST_DR7, val);
7728 			test_guest_state("ENT_LOAD_DBGCTLS disabled", false,
7729 					 val, "GUEST_DR7");
7730 		}
7731 	}
7732 	if (ctrl_enter_rev.clr & ENT_LOAD_DBGCTLS) {
7733 		vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7734 		for (i = 0; i < 64; i++) {
7735 			val = 1ull << i;
7736 			vmcs_write(GUEST_DR7, val);
7737 			test_guest_state("ENT_LOAD_DBGCTLS enabled", i >= 32,
7738 					 val, "GUEST_DR7");
7739 		}
7740 	}
7741 	vmcs_write(GUEST_DR7, dr7_saved);
7742 	vmcs_write(ENT_CONTROLS, ent_saved);
7743 }
7744 
7745 /*
7746  *  If the "load IA32_PAT" VM-entry control is 1, the value of the field
7747  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7748  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7749  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7750  *  6 (WB), or 7 (UC-).
7751  *
7752  *  [Intel SDM]
7753  */
7754 static void test_load_guest_pat(void)
7755 {
7756 	/*
7757 	 * "load IA32_PAT" VM-entry control
7758 	 */
7759 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
7760 		printf("\"Load-IA32-PAT\" entry control not supported\n");
7761 		return;
7762 	}
7763 
7764 	test_pat(GUEST_PAT, "GUEST_PAT", ENT_CONTROLS, ENT_LOAD_PAT);
7765 }
7766 
7767 #define MSR_IA32_BNDCFGS_RSVD_MASK	0x00000ffc
7768 
7769 /*
7770  * If the “load IA32_BNDCFGS†VM-entry control is 1, the following
7771  * checks are performed on the field for the IA32_BNDCFGS MSR:
7772  *
7773  *   —  Bits reserved in the IA32_BNDCFGS MSR must be 0.
7774  *   —  The linear address in bits 63:12 must be canonical.
7775  *
7776  *  [Intel SDM]
7777  */
7778 static void test_load_guest_bndcfgs(void)
7779 {
7780 	u64 bndcfgs_saved = vmcs_read(GUEST_BNDCFGS);
7781 	u64 bndcfgs;
7782 
7783 	if (!(ctrl_enter_rev.clr & ENT_LOAD_BNDCFGS)) {
7784 		printf("\"Load-IA32-BNDCFGS\" entry control not supported\n");
7785 		return;
7786 	}
7787 
7788 	vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7789 
7790 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7791 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7792 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7793 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7794 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7795 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7796 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7797 
7798 	vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7799 
7800 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7801 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7802 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7803 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7804 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7805 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7806 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7807 
7808 	vmcs_write(GUEST_BNDCFGS, bndcfgs_saved);
7809 }
7810 
7811 /*
7812  * Check that the virtual CPU checks the VMX Guest State Area as
7813  * documented in the Intel SDM.
7814  */
7815 static void vmx_guest_state_area_test(void)
7816 {
7817 	vmx_set_test_stage(1);
7818 	test_set_guest(guest_state_test_main);
7819 
7820 	/*
7821 	 * The IA32_SYSENTER_ESP field and the IA32_SYSENTER_EIP field
7822 	 * must each contain a canonical address.
7823 	 */
7824 	test_canonical(GUEST_SYSENTER_ESP, "GUEST_SYSENTER_ESP", false);
7825 	test_canonical(GUEST_SYSENTER_EIP, "GUEST_SYSENTER_EIP", false);
7826 
7827 	test_guest_dr7();
7828 	test_load_guest_pat();
7829 	test_guest_efer();
7830 	test_load_guest_perf_global_ctrl();
7831 	test_load_guest_bndcfgs();
7832 
7833 	test_canonical(GUEST_BASE_GDTR, "GUEST_BASE_GDTR", false);
7834 	test_canonical(GUEST_BASE_IDTR, "GUEST_BASE_IDTR", false);
7835 
7836 	u32 guest_desc_limit_saved = vmcs_read(GUEST_LIMIT_GDTR);
7837 	int i;
7838 	for (i = 16; i <= 31; i++) {
7839 		u32 tmp = guest_desc_limit_saved | (1ull << i);
7840 		vmcs_write(GUEST_LIMIT_GDTR, tmp);
7841 		test_guest_state("GUEST_LIMIT_GDTR", true, tmp, "GUEST_LIMIT_GDTR");
7842 	}
7843 	vmcs_write(GUEST_LIMIT_GDTR, guest_desc_limit_saved);
7844 
7845 	guest_desc_limit_saved = vmcs_read(GUEST_LIMIT_IDTR);
7846 	for (i = 16; i <= 31; i++) {
7847 		u32 tmp = guest_desc_limit_saved | (1ull << i);
7848 		vmcs_write(GUEST_LIMIT_IDTR, tmp);
7849 		test_guest_state("GUEST_LIMIT_IDTR", true, tmp, "GUEST_LIMIT_IDTR");
7850 	}
7851 	vmcs_write(GUEST_LIMIT_IDTR, guest_desc_limit_saved);
7852 
7853 	/*
7854 	 * Let the guest finish execution
7855 	 */
7856 	vmx_set_test_stage(2);
7857 	enter_guest();
7858 }
7859 
7860 static bool valid_vmcs_for_vmentry(void)
7861 {
7862 	struct vmcs *current_vmcs = NULL;
7863 
7864 	if (vmcs_save(&current_vmcs))
7865 		return false;
7866 
7867 	return current_vmcs && !current_vmcs->hdr.shadow_vmcs;
7868 }
7869 
7870 static void try_vmentry_in_movss_shadow(void)
7871 {
7872 	u32 vm_inst_err;
7873 	u32 flags;
7874 	bool early_failure = false;
7875 	u32 expected_flags = X86_EFLAGS_FIXED;
7876 	bool valid_vmcs = valid_vmcs_for_vmentry();
7877 
7878 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
7879 
7880 	/*
7881 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
7882 	 * unsupported VMCS component").
7883 	 */
7884 	vmcs_write(~0u, 0);
7885 
7886 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
7887 			      "vmwrite %%rsp, %%rdx;"
7888 			      "mov 0f, %%rax;"
7889 			      "mov %[host_rip], %%edx;"
7890 			      "vmwrite %%rax, %%rdx;"
7891 			      "mov $-1, %%ah;"
7892 			      "sahf;"
7893 			      "mov %%ss, %%ax;"
7894 			      "mov %%ax, %%ss;"
7895 			      "vmlaunch;"
7896 			      "mov $1, %[early_failure];"
7897 			      "0: lahf;"
7898 			      "movzbl %%ah, %[flags]"
7899 			      : [early_failure] "+r" (early_failure),
7900 				[flags] "=&a" (flags)
7901 			      : [host_rsp] "i" (HOST_RSP),
7902 				[host_rip] "i" (HOST_RIP)
7903 			      : "rdx", "cc", "memory");
7904 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
7905 
7906 	report(early_failure, "Early VM-entry failure");
7907 	report(flags == expected_flags, "RFLAGS[8:0] is %x (actual %x)",
7908 	       expected_flags, flags);
7909 	if (valid_vmcs)
7910 		report(vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
7911 		       "VM-instruction error is %d (actual %d)",
7912 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
7913 }
7914 
7915 static void vmentry_movss_shadow_test(void)
7916 {
7917 	struct vmcs *orig_vmcs;
7918 
7919 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
7920 
7921 	/*
7922 	 * Set the launched flag on the current VMCS to verify the correct
7923 	 * error priority, below.
7924 	 */
7925 	test_set_guest(v2_null_test_guest);
7926 	enter_guest();
7927 
7928 	/*
7929 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
7930 	 * fail due to invalid guest state (if we make it that far).
7931 	 */
7932 	vmcs_write(GUEST_RFLAGS, 0);
7933 
7934 	/*
7935 	 * "VM entry with events blocked by MOV SS" takes precedence over
7936 	 * "VMLAUNCH with non-clear VMCS."
7937 	 */
7938 	report_prefix_push("valid current-VMCS");
7939 	try_vmentry_in_movss_shadow();
7940 	report_prefix_pop();
7941 
7942 	/*
7943 	 * VMfailInvalid takes precedence over "VM entry with events
7944 	 * blocked by MOV SS."
7945 	 */
7946 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
7947 	report_prefix_push("no current-VMCS");
7948 	try_vmentry_in_movss_shadow();
7949 	report_prefix_pop();
7950 
7951 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
7952 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
7953 }
7954 
7955 static void vmx_cr_load_test(void)
7956 {
7957 	unsigned long cr3, cr4, orig_cr3, orig_cr4;
7958 
7959 	orig_cr4 = read_cr4();
7960 	orig_cr3 = read_cr3();
7961 
7962 	if (!this_cpu_has(X86_FEATURE_PCID)) {
7963 		report_skip("PCID not detected");
7964 		return;
7965 	}
7966 	if (!this_cpu_has(X86_FEATURE_MCE)) {
7967 		report_skip("MCE not detected");
7968 		return;
7969 	}
7970 
7971 	TEST_ASSERT(!(orig_cr3 & X86_CR3_PCID_MASK));
7972 
7973 	/* Enable PCID for L1. */
7974 	cr4 = orig_cr4 | X86_CR4_PCIDE;
7975 	cr3 = orig_cr3 | 0x1;
7976 	TEST_ASSERT(!write_cr4_checking(cr4));
7977 	write_cr3(cr3);
7978 
7979 	test_set_guest(v2_null_test_guest);
7980 	vmcs_write(HOST_CR4, cr4);
7981 	vmcs_write(HOST_CR3, cr3);
7982 	enter_guest();
7983 
7984 	/*
7985 	 * No exception is expected.
7986 	 *
7987 	 * NB. KVM loads the last guest write to CR4 into CR4 read
7988 	 *     shadow. In order to trigger an exit to KVM, we can toggle a
7989 	 *     bit that is owned by KVM. We use CR4.MCE, which shall
7990 	 *     have no side effect because normally no guest MCE (e.g., as the
7991 	 *     result of bad memory) would happen during this test.
7992 	 */
7993 	TEST_ASSERT(!write_cr4_checking(cr4 ^ X86_CR4_MCE));
7994 
7995 	/* Cleanup L1 state. */
7996 	write_cr3(orig_cr3);
7997 	TEST_ASSERT(!write_cr4_checking(orig_cr4));
7998 }
7999 
8000 static void vmx_nm_test_guest(void)
8001 {
8002 	write_cr0(read_cr0() | X86_CR0_TS);
8003 	asm volatile("fnop");
8004 }
8005 
8006 static void check_nm_exit(const char *test)
8007 {
8008 	u32 reason = vmcs_read(EXI_REASON);
8009 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
8010 	const u32 expected = INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8011 		NM_VECTOR;
8012 
8013 	report(reason == VMX_EXC_NMI && intr_info == expected, "%s", test);
8014 }
8015 
8016 /*
8017  * This test checks that:
8018  *
8019  * (a) If L2 launches with CR0.TS clear, but later sets CR0.TS, then
8020  *     a subsequent #NM VM-exit is reflected to L1.
8021  *
8022  * (b) If L2 launches with CR0.TS clear and CR0.EM set, then a
8023  *     subsequent #NM VM-exit is reflected to L1.
8024  */
8025 static void vmx_nm_test(void)
8026 {
8027 	unsigned long cr0 = read_cr0();
8028 
8029 	test_set_guest(vmx_nm_test_guest);
8030 
8031 	/*
8032 	 * L1 wants to intercept #NM exceptions encountered in L2.
8033 	 */
8034 	vmcs_write(EXC_BITMAP, 1 << NM_VECTOR);
8035 
8036 	/*
8037 	 * Launch L2 with CR0.TS clear, but don't claim host ownership of
8038 	 * any CR0 bits. L2 will set CR0.TS and then try to execute fnop,
8039 	 * which will raise #NM. L0 should reflect the #NM VM-exit to L1.
8040 	 */
8041 	vmcs_write(CR0_MASK, 0);
8042 	vmcs_write(GUEST_CR0, cr0 & ~X86_CR0_TS);
8043 	enter_guest();
8044 	check_nm_exit("fnop with CR0.TS set in L2 triggers #NM VM-exit to L1");
8045 
8046 	/*
8047 	 * Re-enter L2 at the fnop instruction, with CR0.TS clear but
8048 	 * CR0.EM set. The fnop will still raise #NM, and L0 should
8049 	 * reflect the #NM VM-exit to L1.
8050 	 */
8051 	vmcs_write(GUEST_CR0, (cr0 & ~X86_CR0_TS) | X86_CR0_EM);
8052 	enter_guest();
8053 	check_nm_exit("fnop with CR0.EM set in L2 triggers #NM VM-exit to L1");
8054 
8055 	/*
8056 	 * Re-enter L2 at the fnop instruction, with both CR0.TS and
8057 	 * CR0.EM clear. There will be no #NM, and the L2 guest should
8058 	 * exit normally.
8059 	 */
8060 	vmcs_write(GUEST_CR0, cr0 & ~(X86_CR0_TS | X86_CR0_EM));
8061 	enter_guest();
8062 }
8063 
8064 bool vmx_pending_event_ipi_fired;
8065 static void vmx_pending_event_ipi_isr(isr_regs_t *regs)
8066 {
8067 	vmx_pending_event_ipi_fired = true;
8068 	eoi();
8069 }
8070 
8071 bool vmx_pending_event_guest_run;
8072 static void vmx_pending_event_guest(void)
8073 {
8074 	vmcall();
8075 	vmx_pending_event_guest_run = true;
8076 }
8077 
8078 static void vmx_pending_event_test_core(bool guest_hlt)
8079 {
8080 	int ipi_vector = 0xf1;
8081 
8082 	vmx_pending_event_ipi_fired = false;
8083 	handle_irq(ipi_vector, vmx_pending_event_ipi_isr);
8084 
8085 	vmx_pending_event_guest_run = false;
8086 	test_set_guest(vmx_pending_event_guest);
8087 
8088 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
8089 
8090 	enter_guest();
8091 	skip_exit_vmcall();
8092 
8093 	if (guest_hlt)
8094 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8095 
8096 	irq_disable();
8097 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
8098 				   APIC_DM_FIXED | ipi_vector,
8099 				   0);
8100 
8101 	enter_guest();
8102 
8103 	assert_exit_reason(VMX_EXTINT);
8104 	report(!vmx_pending_event_guest_run,
8105 	       "Guest did not run before host received IPI");
8106 
8107 	irq_enable();
8108 	asm volatile ("nop");
8109 	irq_disable();
8110 	report(vmx_pending_event_ipi_fired,
8111 	       "Got pending interrupt after IRQ enabled");
8112 
8113 	if (guest_hlt)
8114 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8115 
8116 	enter_guest();
8117 	report(vmx_pending_event_guest_run,
8118 	       "Guest finished running when no interrupt");
8119 }
8120 
8121 static void vmx_pending_event_test(void)
8122 {
8123 	vmx_pending_event_test_core(false);
8124 }
8125 
8126 static void vmx_pending_event_hlt_test(void)
8127 {
8128 	vmx_pending_event_test_core(true);
8129 }
8130 
8131 static int vmx_window_test_db_count;
8132 
8133 static void vmx_window_test_db_handler(struct ex_regs *regs)
8134 {
8135 	vmx_window_test_db_count++;
8136 }
8137 
8138 static void vmx_nmi_window_test_guest(void)
8139 {
8140 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
8141 
8142 	asm volatile("vmcall\n\t"
8143 		     "nop\n\t");
8144 
8145 	handle_exception(DB_VECTOR, NULL);
8146 }
8147 
8148 static void verify_nmi_window_exit(u64 rip)
8149 {
8150 	u32 exit_reason = vmcs_read(EXI_REASON);
8151 
8152 	report(exit_reason == VMX_NMI_WINDOW,
8153 	       "Exit reason (%d) is 'NMI window'", exit_reason);
8154 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8155 	       vmcs_read(GUEST_RIP), rip);
8156 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8157 }
8158 
8159 static void vmx_nmi_window_test(void)
8160 {
8161 	u64 nop_addr;
8162 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8163 
8164 	if (!(ctrl_pin_rev.clr & PIN_VIRT_NMI)) {
8165 		report_skip("CPU does not support the \"Virtual NMIs\" VM-execution control.");
8166 		return;
8167 	}
8168 
8169 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
8170 		report_skip("CPU does not support the \"NMI-window exiting\" VM-execution control.");
8171 		return;
8172 	}
8173 
8174 	vmx_window_test_db_count = 0;
8175 
8176 	report_prefix_push("NMI-window");
8177 	test_set_guest(vmx_nmi_window_test_guest);
8178 	vmcs_set_bits(PIN_CONTROLS, PIN_VIRT_NMI);
8179 	enter_guest();
8180 	skip_exit_vmcall();
8181 	nop_addr = vmcs_read(GUEST_RIP);
8182 
8183 	/*
8184 	 * Ask for "NMI-window exiting," and expect an immediate VM-exit.
8185 	 * RIP will not advance.
8186 	 */
8187 	report_prefix_push("active, no blocking");
8188 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8189 	enter_guest();
8190 	verify_nmi_window_exit(nop_addr);
8191 	report_prefix_pop();
8192 
8193 	/*
8194 	 * Ask for "NMI-window exiting" in a MOV-SS shadow, and expect
8195 	 * a VM-exit on the next instruction after the nop. (The nop
8196 	 * is one byte.)
8197 	 */
8198 	report_prefix_push("active, blocking by MOV-SS");
8199 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8200 	enter_guest();
8201 	verify_nmi_window_exit(nop_addr + 1);
8202 	report_prefix_pop();
8203 
8204 	/*
8205 	 * Ask for "NMI-window exiting" (with event injection), and
8206 	 * expect a VM-exit after the event is injected. (RIP should
8207 	 * be at the address specified in the IDT entry for #DB.)
8208 	 */
8209 	report_prefix_push("active, no blocking, injecting #DB");
8210 	vmcs_write(ENT_INTR_INFO,
8211 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8212 	enter_guest();
8213 	verify_nmi_window_exit((u64)db_fault_addr);
8214 	report_prefix_pop();
8215 
8216 	/*
8217 	 * Ask for "NMI-window exiting" with NMI blocking, and expect
8218 	 * a VM-exit after the next IRET (i.e. after the #DB handler
8219 	 * returns). So, RIP should be back at one byte past the nop.
8220 	 */
8221 	report_prefix_push("active, blocking by NMI");
8222 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_NMI);
8223 	enter_guest();
8224 	verify_nmi_window_exit(nop_addr + 1);
8225 	report(vmx_window_test_db_count == 1,
8226 	       "#DB handler executed once (actual %d times)",
8227 	       vmx_window_test_db_count);
8228 	report_prefix_pop();
8229 
8230 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8231 		report_skip("CPU does not support activity state HLT.");
8232 	} else {
8233 		/*
8234 		 * Ask for "NMI-window exiting" when entering activity
8235 		 * state HLT, and expect an immediate VM-exit. RIP is
8236 		 * still one byte past the nop.
8237 		 */
8238 		report_prefix_push("halted, no blocking");
8239 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8240 		enter_guest();
8241 		verify_nmi_window_exit(nop_addr + 1);
8242 		report_prefix_pop();
8243 
8244 		/*
8245 		 * Ask for "NMI-window exiting" when entering activity
8246 		 * state HLT (with event injection), and expect a
8247 		 * VM-exit after the event is injected. (RIP should be
8248 		 * at the address specified in the IDT entry for #DB.)
8249 		 */
8250 		report_prefix_push("halted, no blocking, injecting #DB");
8251 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8252 		vmcs_write(ENT_INTR_INFO,
8253 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8254 			   DB_VECTOR);
8255 		enter_guest();
8256 		verify_nmi_window_exit((u64)db_fault_addr);
8257 		report_prefix_pop();
8258 	}
8259 
8260 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8261 	enter_guest();
8262 	report_prefix_pop();
8263 }
8264 
8265 static void vmx_intr_window_test_guest(void)
8266 {
8267 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
8268 
8269 	/*
8270 	 * The two consecutive STIs are to ensure that only the first
8271 	 * one has a shadow. Note that NOP and STI are one byte
8272 	 * instructions.
8273 	 */
8274 	asm volatile("vmcall\n\t"
8275 		     "nop\n\t"
8276 		     "sti\n\t"
8277 		     "sti\n\t");
8278 
8279 	handle_exception(DB_VECTOR, NULL);
8280 }
8281 
8282 static void verify_intr_window_exit(u64 rip)
8283 {
8284 	u32 exit_reason = vmcs_read(EXI_REASON);
8285 
8286 	report(exit_reason == VMX_INTR_WINDOW,
8287 	       "Exit reason (%d) is 'interrupt window'", exit_reason);
8288 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8289 	       vmcs_read(GUEST_RIP), rip);
8290 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8291 }
8292 
8293 static void vmx_intr_window_test(void)
8294 {
8295 	u64 vmcall_addr;
8296 	u64 nop_addr;
8297 	unsigned int orig_db_gate_type;
8298 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8299 
8300 	if (!(ctrl_cpu_rev[0].clr & CPU_INTR_WINDOW)) {
8301 		report_skip("CPU does not support the \"interrupt-window exiting\" VM-execution control.");
8302 		return;
8303 	}
8304 
8305 	/*
8306 	 * Change the IDT entry for #DB from interrupt gate to trap gate,
8307 	 * so that it won't clear RFLAGS.IF. We don't want interrupts to
8308 	 * be disabled after vectoring a #DB.
8309 	 */
8310 	orig_db_gate_type = boot_idt[DB_VECTOR].type;
8311 	boot_idt[DB_VECTOR].type = 15;
8312 
8313 	report_prefix_push("interrupt-window");
8314 	test_set_guest(vmx_intr_window_test_guest);
8315 	enter_guest();
8316 	assert_exit_reason(VMX_VMCALL);
8317 	vmcall_addr = vmcs_read(GUEST_RIP);
8318 
8319 	/*
8320 	 * Ask for "interrupt-window exiting" with RFLAGS.IF set and
8321 	 * no blocking; expect an immediate VM-exit. Note that we have
8322 	 * not advanced past the vmcall instruction yet, so RIP should
8323 	 * point to the vmcall instruction.
8324 	 */
8325 	report_prefix_push("active, no blocking, RFLAGS.IF=1");
8326 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8327 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_IF);
8328 	enter_guest();
8329 	verify_intr_window_exit(vmcall_addr);
8330 	report_prefix_pop();
8331 
8332 	/*
8333 	 * Ask for "interrupt-window exiting" (with event injection)
8334 	 * with RFLAGS.IF set and no blocking; expect a VM-exit after
8335 	 * the event is injected. That is, RIP should should be at the
8336 	 * address specified in the IDT entry for #DB.
8337 	 */
8338 	report_prefix_push("active, no blocking, RFLAGS.IF=1, injecting #DB");
8339 	vmcs_write(ENT_INTR_INFO,
8340 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8341 	vmcall_addr = vmcs_read(GUEST_RIP);
8342 	enter_guest();
8343 	verify_intr_window_exit((u64)db_fault_addr);
8344 	report_prefix_pop();
8345 
8346 	/*
8347 	 * Let the L2 guest run through the IRET, back to the VMCALL.
8348 	 * We have to clear the "interrupt-window exiting"
8349 	 * VM-execution control, or it would just keep causing
8350 	 * VM-exits. Then, advance past the VMCALL and set the
8351 	 * "interrupt-window exiting" VM-execution control again.
8352 	 */
8353 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8354 	enter_guest();
8355 	skip_exit_vmcall();
8356 	nop_addr = vmcs_read(GUEST_RIP);
8357 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8358 
8359 	/*
8360 	 * Ask for "interrupt-window exiting" in a MOV-SS shadow with
8361 	 * RFLAGS.IF set, and expect a VM-exit on the next
8362 	 * instruction. (NOP is one byte.)
8363 	 */
8364 	report_prefix_push("active, blocking by MOV-SS, RFLAGS.IF=1");
8365 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8366 	enter_guest();
8367 	verify_intr_window_exit(nop_addr + 1);
8368 	report_prefix_pop();
8369 
8370 	/*
8371 	 * Back up to the NOP and ask for "interrupt-window exiting"
8372 	 * in an STI shadow with RFLAGS.IF set, and expect a VM-exit
8373 	 * on the next instruction. (NOP is one byte.)
8374 	 */
8375 	report_prefix_push("active, blocking by STI, RFLAGS.IF=1");
8376 	vmcs_write(GUEST_RIP, nop_addr);
8377 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_STI);
8378 	enter_guest();
8379 	verify_intr_window_exit(nop_addr + 1);
8380 	report_prefix_pop();
8381 
8382 	/*
8383 	 * Ask for "interrupt-window exiting" with RFLAGS.IF clear,
8384 	 * and expect a VM-exit on the instruction following the STI
8385 	 * shadow. Only the first STI (which is one byte past the NOP)
8386 	 * should have a shadow. The second STI (which is two bytes
8387 	 * past the NOP) has no shadow. Therefore, the interrupt
8388 	 * window opens at three bytes past the NOP.
8389 	 */
8390 	report_prefix_push("active, RFLAGS.IF = 0");
8391 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8392 	enter_guest();
8393 	verify_intr_window_exit(nop_addr + 3);
8394 	report_prefix_pop();
8395 
8396 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8397 		report_skip("CPU does not support activity state HLT.");
8398 	} else {
8399 		/*
8400 		 * Ask for "interrupt-window exiting" when entering
8401 		 * activity state HLT, and expect an immediate
8402 		 * VM-exit. RIP is still three bytes past the nop.
8403 		 */
8404 		report_prefix_push("halted, no blocking");
8405 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8406 		enter_guest();
8407 		verify_intr_window_exit(nop_addr + 3);
8408 		report_prefix_pop();
8409 
8410 		/*
8411 		 * Ask for "interrupt-window exiting" when entering
8412 		 * activity state HLT (with event injection), and
8413 		 * expect a VM-exit after the event is injected. That
8414 		 * is, RIP should should be at the address specified
8415 		 * in the IDT entry for #DB.
8416 		 */
8417 		report_prefix_push("halted, no blocking, injecting #DB");
8418 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8419 		vmcs_write(ENT_INTR_INFO,
8420 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8421 			   DB_VECTOR);
8422 		enter_guest();
8423 		verify_intr_window_exit((u64)db_fault_addr);
8424 		report_prefix_pop();
8425 	}
8426 
8427 	boot_idt[DB_VECTOR].type = orig_db_gate_type;
8428 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8429 	enter_guest();
8430 	report_prefix_pop();
8431 }
8432 
8433 #define GUEST_TSC_OFFSET (1u << 30)
8434 
8435 static u64 guest_tsc;
8436 
8437 static void vmx_store_tsc_test_guest(void)
8438 {
8439 	guest_tsc = rdtsc();
8440 }
8441 
8442 /*
8443  * This test ensures that when IA32_TSC is in the VM-exit MSR-store
8444  * list, the value saved is not subject to the TSC offset that is
8445  * applied to RDTSC/RDTSCP/RDMSR(IA32_TSC) in guest execution.
8446  */
8447 static void vmx_store_tsc_test(void)
8448 {
8449 	struct vmx_msr_entry msr_entry = { .index = MSR_IA32_TSC };
8450 	u64 low, high;
8451 
8452 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET)) {
8453 		report_skip("'Use TSC offsetting' not supported");
8454 		return;
8455 	}
8456 
8457 	test_set_guest(vmx_store_tsc_test_guest);
8458 
8459 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
8460 	vmcs_write(EXI_MSR_ST_CNT, 1);
8461 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(&msr_entry));
8462 	vmcs_write(TSC_OFFSET, GUEST_TSC_OFFSET);
8463 
8464 	low = rdtsc();
8465 	enter_guest();
8466 	high = rdtsc();
8467 
8468 	report(low + GUEST_TSC_OFFSET <= guest_tsc &&
8469 	       guest_tsc <= high + GUEST_TSC_OFFSET,
8470 	       "RDTSC value in the guest (%lu) is in range [%lu, %lu]",
8471 	       guest_tsc, low + GUEST_TSC_OFFSET, high + GUEST_TSC_OFFSET);
8472 	report(low <= msr_entry.value && msr_entry.value <= high,
8473 	       "IA32_TSC value saved in the VM-exit MSR-store list (%lu) is in range [%lu, %lu]",
8474 	       msr_entry.value, low, high);
8475 }
8476 
8477 static void vmx_preemption_timer_zero_test_db_handler(struct ex_regs *regs)
8478 {
8479 }
8480 
8481 static void vmx_preemption_timer_zero_test_guest(void)
8482 {
8483 	while (vmx_get_test_stage() < 3)
8484 		vmcall();
8485 }
8486 
8487 static void vmx_preemption_timer_zero_activate_preemption_timer(void)
8488 {
8489 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
8490 	vmcs_write(PREEMPT_TIMER_VALUE, 0);
8491 }
8492 
8493 static void vmx_preemption_timer_zero_advance_past_vmcall(void)
8494 {
8495 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8496 	enter_guest();
8497 	skip_exit_vmcall();
8498 }
8499 
8500 static void vmx_preemption_timer_zero_inject_db(bool intercept_db)
8501 {
8502 	vmx_preemption_timer_zero_activate_preemption_timer();
8503 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK |
8504 		   INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8505 	vmcs_write(EXC_BITMAP, intercept_db ? 1 << DB_VECTOR : 0);
8506 	enter_guest();
8507 }
8508 
8509 static void vmx_preemption_timer_zero_set_pending_dbg(u32 exception_bitmap)
8510 {
8511 	vmx_preemption_timer_zero_activate_preemption_timer();
8512 	vmcs_write(GUEST_PENDING_DEBUG, BIT(12) | DR_TRAP1);
8513 	vmcs_write(EXC_BITMAP, exception_bitmap);
8514 	enter_guest();
8515 }
8516 
8517 static void vmx_preemption_timer_zero_expect_preempt_at_rip(u64 expected_rip)
8518 {
8519 	u32 reason = (u32)vmcs_read(EXI_REASON);
8520 	u64 guest_rip = vmcs_read(GUEST_RIP);
8521 
8522 	report(reason == VMX_PREEMPT && guest_rip == expected_rip,
8523 	       "Exit reason is 0x%x (expected 0x%x) and guest RIP is %lx (0x%lx expected).",
8524 	       reason, VMX_PREEMPT, guest_rip, expected_rip);
8525 }
8526 
8527 /*
8528  * This test ensures that when the VMX preemption timer is zero at
8529  * VM-entry, a VM-exit occurs after any event injection and after any
8530  * pending debug exceptions are raised, but before execution of any
8531  * guest instructions.
8532  */
8533 static void vmx_preemption_timer_zero_test(void)
8534 {
8535 	u64 db_fault_address = (u64)get_idt_addr(&boot_idt[DB_VECTOR]);
8536 	handler old_db;
8537 	u32 reason;
8538 
8539 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
8540 		report_skip("'Activate VMX-preemption timer' not supported");
8541 		return;
8542 	}
8543 
8544 	/*
8545 	 * Install a custom #DB handler that doesn't abort.
8546 	 */
8547 	old_db = handle_exception(DB_VECTOR,
8548 				  vmx_preemption_timer_zero_test_db_handler);
8549 
8550 	test_set_guest(vmx_preemption_timer_zero_test_guest);
8551 
8552 	/*
8553 	 * VMX-preemption timer should fire after event injection.
8554 	 */
8555 	vmx_set_test_stage(0);
8556 	vmx_preemption_timer_zero_inject_db(0);
8557 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8558 	vmx_preemption_timer_zero_advance_past_vmcall();
8559 
8560 	/*
8561 	 * VMX-preemption timer should fire after event injection.
8562 	 * Exception bitmap is irrelevant, since you can't intercept
8563 	 * an event that you injected.
8564 	 */
8565 	vmx_set_test_stage(1);
8566 	vmx_preemption_timer_zero_inject_db(true);
8567 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8568 	vmx_preemption_timer_zero_advance_past_vmcall();
8569 
8570 	/*
8571 	 * VMX-preemption timer should fire after pending debug exceptions
8572 	 * have delivered a #DB trap.
8573 	 */
8574 	vmx_set_test_stage(2);
8575 	vmx_preemption_timer_zero_set_pending_dbg(0);
8576 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8577 	vmx_preemption_timer_zero_advance_past_vmcall();
8578 
8579 	/*
8580 	 * VMX-preemption timer would fire after pending debug exceptions
8581 	 * have delivered a #DB trap, but in this case, the #DB trap is
8582 	 * intercepted.
8583 	 */
8584 	vmx_set_test_stage(3);
8585 	vmx_preemption_timer_zero_set_pending_dbg(1 << DB_VECTOR);
8586 	reason = (u32)vmcs_read(EXI_REASON);
8587 	report(reason == VMX_EXC_NMI, "Exit reason is 0x%x (expected 0x%x)",
8588 	       reason, VMX_EXC_NMI);
8589 
8590 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8591 	enter_guest();
8592 
8593 	handle_exception(DB_VECTOR, old_db);
8594 }
8595 
8596 static u64 vmx_preemption_timer_tf_test_prev_rip;
8597 
8598 static void vmx_preemption_timer_tf_test_db_handler(struct ex_regs *regs)
8599 {
8600 	extern char vmx_preemption_timer_tf_test_endloop;
8601 
8602 	if (vmx_get_test_stage() == 2) {
8603 		/*
8604 		 * Stage 2 means that we're done, one way or another.
8605 		 * Arrange for the iret to drop us out of the wbinvd
8606 		 * loop and stop single-stepping.
8607 		 */
8608 		regs->rip = (u64)&vmx_preemption_timer_tf_test_endloop;
8609 		regs->rflags &= ~X86_EFLAGS_TF;
8610 	} else if (regs->rip == vmx_preemption_timer_tf_test_prev_rip) {
8611 		/*
8612 		 * The RIP should alternate between the wbinvd and the
8613 		 * jmp instruction in the code below. If we ever see
8614 		 * the same instruction twice in a row, that means a
8615 		 * single-step trap has been dropped. Let the
8616 		 * hypervisor know about the failure by executing a
8617 		 * VMCALL.
8618 		 */
8619 		vmcall();
8620 	}
8621 	vmx_preemption_timer_tf_test_prev_rip = regs->rip;
8622 }
8623 
8624 static void vmx_preemption_timer_tf_test_guest(void)
8625 {
8626 	/*
8627 	 * The hypervisor doesn't intercept WBINVD, so the loop below
8628 	 * shouldn't be a problem--it's just two instructions
8629 	 * executing in VMX non-root mode. However, when the
8630 	 * hypervisor is running in a virtual environment, the parent
8631 	 * hypervisor might intercept WBINVD and emulate it. If the
8632 	 * parent hypervisor is broken, the single-step trap after the
8633 	 * WBINVD might be lost.
8634 	 */
8635 	asm volatile("vmcall\n\t"
8636 		     "0: wbinvd\n\t"
8637 		     "1: jmp 0b\n\t"
8638 		     "vmx_preemption_timer_tf_test_endloop:");
8639 }
8640 
8641 /*
8642  * Ensure that the delivery of a "VMX-preemption timer expired"
8643  * VM-exit doesn't disrupt single-stepping in the guest. Note that
8644  * passing this test doesn't ensure correctness, because the test will
8645  * only fail if the VMX-preemtion timer fires at the right time (or
8646  * the wrong time, as it were).
8647  */
8648 static void vmx_preemption_timer_tf_test(void)
8649 {
8650 	handler old_db;
8651 	u32 reason;
8652 	int i;
8653 
8654 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
8655 		report_skip("'Activate VMX-preemption timer' not supported");
8656 		return;
8657 	}
8658 
8659 	old_db = handle_exception(DB_VECTOR,
8660 				  vmx_preemption_timer_tf_test_db_handler);
8661 
8662 	test_set_guest(vmx_preemption_timer_tf_test_guest);
8663 
8664 	enter_guest();
8665 	skip_exit_vmcall();
8666 
8667 	vmx_set_test_stage(1);
8668 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
8669 	vmcs_write(PREEMPT_TIMER_VALUE, 50000);
8670 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
8671 
8672 	/*
8673 	 * The only exit we should see is "VMX-preemption timer
8674 	 * expired."  If we get a VMCALL exit, that means the #DB
8675 	 * handler has detected a missing single-step trap. It doesn't
8676 	 * matter where the guest RIP is when the VMX-preemption timer
8677 	 * expires (whether it's in the WBINVD loop or in the #DB
8678 	 * handler)--a single-step trap should never be discarded.
8679 	 */
8680 	for (i = 0; i < 10000; i++) {
8681 		enter_guest();
8682 		reason = (u32)vmcs_read(EXI_REASON);
8683 		if (reason == VMX_PREEMPT)
8684 			continue;
8685 		TEST_ASSERT(reason == VMX_VMCALL);
8686 		skip_exit_insn();
8687 		break;
8688 	}
8689 
8690 	report(reason == VMX_PREEMPT, "No single-step traps skipped");
8691 
8692 	vmx_set_test_stage(2);
8693 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8694 	enter_guest();
8695 
8696 	handle_exception(DB_VECTOR, old_db);
8697 }
8698 
8699 #define VMX_PREEMPTION_TIMER_EXPIRY_CYCLES 1000000
8700 
8701 static u64 vmx_preemption_timer_expiry_start;
8702 static u64 vmx_preemption_timer_expiry_finish;
8703 
8704 static void vmx_preemption_timer_expiry_test_guest(void)
8705 {
8706 	vmcall();
8707 	vmx_preemption_timer_expiry_start = fenced_rdtsc();
8708 
8709 	while (vmx_get_test_stage() == 0)
8710 		vmx_preemption_timer_expiry_finish = fenced_rdtsc();
8711 }
8712 
8713 /*
8714  * Test that the VMX-preemption timer is not excessively delayed.
8715  *
8716  * Per the SDM, volume 3, VM-entry starts the VMX-preemption timer
8717  * with the unsigned value in the VMX-preemption timer-value field,
8718  * and the VMX-preemption timer counts down by 1 every time bit X in
8719  * the TSC changes due to a TSC increment (where X is
8720  * IA32_VMX_MISC[4:0]). If the timer counts down to zero in any state
8721  * other than the wait-for-SIPI state, the logical processor
8722  * transitions to the C0 C-state and causes a VM-exit.
8723  *
8724  * The guest code above reads the starting TSC after VM-entry. At this
8725  * point, the VMX-preemption timer has already been activated. Next,
8726  * the guest code reads the current TSC in a loop, storing the value
8727  * read to memory.
8728  *
8729  * If the RDTSC in the loop reads a value past the VMX-preemption
8730  * timer deadline, then the VMX-preemption timer VM-exit must be
8731  * delivered before the next instruction retires. Even if a higher
8732  * priority SMI is delivered first, the VMX-preemption timer VM-exit
8733  * must be delivered before the next instruction retires. Hence, a TSC
8734  * value past the VMX-preemption timer deadline might be read, but it
8735  * cannot be stored. If a TSC value past the deadline *is* stored,
8736  * then the architectural specification has been violated.
8737  */
8738 static void vmx_preemption_timer_expiry_test(void)
8739 {
8740 	u32 preemption_timer_value;
8741 	union vmx_misc misc;
8742 	u64 tsc_deadline;
8743 	u32 reason;
8744 
8745 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
8746 		report_skip("'Activate VMX-preemption timer' not supported");
8747 		return;
8748 	}
8749 
8750 	test_set_guest(vmx_preemption_timer_expiry_test_guest);
8751 
8752 	enter_guest();
8753 	skip_exit_vmcall();
8754 
8755 	misc.val = rdmsr(MSR_IA32_VMX_MISC);
8756 	preemption_timer_value =
8757 		VMX_PREEMPTION_TIMER_EXPIRY_CYCLES >> misc.pt_bit;
8758 
8759 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
8760 	vmcs_write(PREEMPT_TIMER_VALUE, preemption_timer_value);
8761 	vmx_set_test_stage(0);
8762 
8763 	enter_guest();
8764 	reason = (u32)vmcs_read(EXI_REASON);
8765 	TEST_ASSERT(reason == VMX_PREEMPT);
8766 
8767 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8768 	vmx_set_test_stage(1);
8769 	enter_guest();
8770 
8771 	tsc_deadline = ((vmx_preemption_timer_expiry_start >> misc.pt_bit) <<
8772 			misc.pt_bit) + (preemption_timer_value << misc.pt_bit);
8773 
8774 	report(vmx_preemption_timer_expiry_finish < tsc_deadline,
8775 	       "Last stored guest TSC (%lu) < TSC deadline (%lu)",
8776 	       vmx_preemption_timer_expiry_finish, tsc_deadline);
8777 }
8778 
8779 static void vmx_db_test_guest(void)
8780 {
8781 	/*
8782 	 * For a hardware generated single-step #DB.
8783 	 */
8784 	asm volatile("vmcall;"
8785 		     "nop;"
8786 		     ".Lpost_nop:");
8787 	/*
8788 	 * ...in a MOVSS shadow, with pending debug exceptions.
8789 	 */
8790 	asm volatile("vmcall;"
8791 		     "nop;"
8792 		     ".Lpost_movss_nop:");
8793 	/*
8794 	 * For an L0 synthesized single-step #DB. (L0 intercepts WBINVD and
8795 	 * emulates it in software.)
8796 	 */
8797 	asm volatile("vmcall;"
8798 		     "wbinvd;"
8799 		     ".Lpost_wbinvd:");
8800 	/*
8801 	 * ...in a MOVSS shadow, with pending debug exceptions.
8802 	 */
8803 	asm volatile("vmcall;"
8804 		     "wbinvd;"
8805 		     ".Lpost_movss_wbinvd:");
8806 	/*
8807 	 * For a hardware generated single-step #DB in a transactional region.
8808 	 */
8809 	asm volatile("vmcall;"
8810 		     ".Lxbegin: xbegin .Lskip_rtm;"
8811 		     "xend;"
8812 		     ".Lskip_rtm:");
8813 }
8814 
8815 /*
8816  * Clear the pending debug exceptions and RFLAGS.TF and re-enter
8817  * L2. No #DB is delivered and L2 continues to the next point of
8818  * interest.
8819  */
8820 static void dismiss_db(void)
8821 {
8822 	vmcs_write(GUEST_PENDING_DEBUG, 0);
8823 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8824 	enter_guest();
8825 }
8826 
8827 /*
8828  * Check a variety of VMCS fields relevant to an intercepted #DB exception.
8829  * Then throw away the #DB exception and resume L2.
8830  */
8831 static void check_db_exit(bool xfail_qual, bool xfail_dr6, bool xfail_pdbg,
8832 			  void *expected_rip, u64 expected_exit_qual,
8833 			  u64 expected_dr6)
8834 {
8835 	u32 reason = vmcs_read(EXI_REASON);
8836 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
8837 	u64 exit_qual = vmcs_read(EXI_QUALIFICATION);
8838 	u64 guest_rip = vmcs_read(GUEST_RIP);
8839 	u64 guest_pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
8840 	u64 dr6 = read_dr6();
8841 	const u32 expected_intr_info = INTR_INFO_VALID_MASK |
8842 		INTR_TYPE_HARD_EXCEPTION | DB_VECTOR;
8843 
8844 	report(reason == VMX_EXC_NMI && intr_info == expected_intr_info,
8845 	       "Expected #DB VM-exit");
8846 	report((u64)expected_rip == guest_rip, "Expected RIP %p (actual %lx)",
8847 	       expected_rip, guest_rip);
8848 	report_xfail(xfail_pdbg, 0 == guest_pending_dbg,
8849 		     "Expected pending debug exceptions 0 (actual %lx)",
8850 		     guest_pending_dbg);
8851 	report_xfail(xfail_qual, expected_exit_qual == exit_qual,
8852 		     "Expected exit qualification %lx (actual %lx)",
8853 		     expected_exit_qual, exit_qual);
8854 	report_xfail(xfail_dr6, expected_dr6 == dr6,
8855 		     "Expected DR6 %lx (actual %lx)", expected_dr6, dr6);
8856 	dismiss_db();
8857 }
8858 
8859 /*
8860  * Assuming the guest has just exited on a VMCALL instruction, skip
8861  * over the vmcall, and set the guest's RFLAGS.TF in the VMCS. If
8862  * pending debug exceptions are non-zero, set the VMCS up as if the
8863  * previous instruction was a MOVSS that generated the indicated
8864  * pending debug exceptions. Then enter L2.
8865  */
8866 static void single_step_guest(const char *test_name, u64 starting_dr6,
8867 			      u64 pending_debug_exceptions)
8868 {
8869 	printf("\n%s\n", test_name);
8870 	skip_exit_vmcall();
8871 	write_dr6(starting_dr6);
8872 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
8873 	if (pending_debug_exceptions) {
8874 		vmcs_write(GUEST_PENDING_DEBUG, pending_debug_exceptions);
8875 		vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8876 	}
8877 	enter_guest();
8878 }
8879 
8880 /*
8881  * When L1 intercepts #DB, verify that a single-step trap clears
8882  * pending debug exceptions, populates the exit qualification field
8883  * properly, and that DR6 is not prematurely clobbered. In a
8884  * (simulated) MOVSS shadow, make sure that the pending debug
8885  * exception bits are properly accumulated into the exit qualification
8886  * field.
8887  */
8888 static void vmx_db_test(void)
8889 {
8890 	/*
8891 	 * We are going to set a few arbitrary bits in DR6 to verify that
8892 	 * (a) DR6 is not modified by an intercepted #DB, and
8893 	 * (b) stale bits in DR6 (DR6.BD, in particular) don't leak into
8894          *     the exit qualification field for a subsequent #DB exception.
8895 	 */
8896 	const u64 starting_dr6 = DR6_RESERVED | BIT(13) | DR_TRAP3 | DR_TRAP1;
8897 	extern char post_nop asm(".Lpost_nop");
8898 	extern char post_movss_nop asm(".Lpost_movss_nop");
8899 	extern char post_wbinvd asm(".Lpost_wbinvd");
8900 	extern char post_movss_wbinvd asm(".Lpost_movss_wbinvd");
8901 	extern char xbegin asm(".Lxbegin");
8902 	extern char skip_rtm asm(".Lskip_rtm");
8903 
8904 	/*
8905 	 * L1 wants to intercept #DB exceptions encountered in L2.
8906 	 */
8907 	vmcs_write(EXC_BITMAP, BIT(DB_VECTOR));
8908 
8909 	/*
8910 	 * Start L2 and run it up to the first point of interest.
8911 	 */
8912 	test_set_guest(vmx_db_test_guest);
8913 	enter_guest();
8914 
8915 	/*
8916 	 * Hardware-delivered #DB trap for single-step sets the
8917 	 * standard that L0 has to follow for emulated instructions.
8918 	 */
8919 	single_step_guest("Hardware delivered single-step", starting_dr6, 0);
8920 	check_db_exit(false, false, false, &post_nop, DR_STEP, starting_dr6);
8921 
8922 	/*
8923 	 * Hardware-delivered #DB trap for single-step in MOVSS shadow
8924 	 * also sets the standard that L0 has to follow for emulated
8925 	 * instructions. Here, we establish the VMCS pending debug
8926 	 * exceptions to indicate that the simulated MOVSS triggered a
8927 	 * data breakpoint as well as the single-step trap.
8928 	 */
8929 	single_step_guest("Hardware delivered single-step in MOVSS shadow",
8930 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0 );
8931 	check_db_exit(false, false, false, &post_movss_nop, DR_STEP | DR_TRAP0,
8932 		      starting_dr6);
8933 
8934 	/*
8935 	 * L0 synthesized #DB trap for single-step is buggy, because
8936 	 * kvm (a) clobbers DR6 too early, and (b) tries its best to
8937 	 * reconstitute the exit qualification from the prematurely
8938 	 * modified DR6, but fails miserably.
8939 	 */
8940 	single_step_guest("Software synthesized single-step", starting_dr6, 0);
8941 	check_db_exit(false, false, false, &post_wbinvd, DR_STEP, starting_dr6);
8942 
8943 	/*
8944 	 * L0 synthesized #DB trap for single-step in MOVSS shadow is
8945 	 * even worse, because L0 also leaves the pending debug
8946 	 * exceptions in the VMCS instead of accumulating them into
8947 	 * the exit qualification field for the #DB exception.
8948 	 */
8949 	single_step_guest("Software synthesized single-step in MOVSS shadow",
8950 			  starting_dr6, BIT(12) | DR_STEP | DR_TRAP0);
8951 	check_db_exit(true, false, true, &post_movss_wbinvd, DR_STEP | DR_TRAP0,
8952 		      starting_dr6);
8953 
8954 	/*
8955 	 * Optional RTM test for hardware that supports RTM, to
8956 	 * demonstrate that the current volume 3 of the SDM
8957 	 * (325384-067US), table 27-1 is incorrect. Bit 16 of the exit
8958 	 * qualification for debug exceptions is not reserved. It is
8959 	 * set to 1 if a debug exception (#DB) or a breakpoint
8960 	 * exception (#BP) occurs inside an RTM region while advanced
8961 	 * debugging of RTM transactional regions is enabled.
8962 	 */
8963 	if (this_cpu_has(X86_FEATURE_RTM)) {
8964 		vmcs_write(ENT_CONTROLS,
8965 			   vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
8966 		/*
8967 		 * Set DR7.RTM[bit 11] and IA32_DEBUGCTL.RTM[bit 15]
8968 		 * in the guest to enable advanced debugging of RTM
8969 		 * transactional regions.
8970 		 */
8971 		vmcs_write(GUEST_DR7, BIT(11));
8972 		vmcs_write(GUEST_DEBUGCTL, BIT(15));
8973 		single_step_guest("Hardware delivered single-step in "
8974 				  "transactional region", starting_dr6, 0);
8975 		check_db_exit(false, false, false, &xbegin, BIT(16),
8976 			      starting_dr6);
8977 	} else {
8978 		vmcs_write(GUEST_RIP, (u64)&skip_rtm);
8979 		enter_guest();
8980 	}
8981 }
8982 
8983 static void enable_vid(void)
8984 {
8985 	void *virtual_apic_page;
8986 
8987 	assert(cpu_has_apicv());
8988 
8989 	disable_intercept_for_x2apic_msrs();
8990 
8991 	virtual_apic_page = alloc_page();
8992 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
8993 
8994 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
8995 
8996 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
8997 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
8998 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
8999 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
9000 
9001 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY | CPU_TPR_SHADOW);
9002 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VINTD | CPU_VIRT_X2APIC);
9003 }
9004 
9005 static void trigger_ioapic_scan_thread(void *data)
9006 {
9007 	/* Wait until other CPU entered L2 */
9008 	while (vmx_get_test_stage() != 1)
9009 		;
9010 
9011 	/* Trigger ioapic scan */
9012 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
9013 	vmx_set_test_stage(2);
9014 }
9015 
9016 static void irq_79_handler_guest(isr_regs_t *regs)
9017 {
9018 	eoi();
9019 
9020 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
9021 	vmcall();
9022 }
9023 
9024 /*
9025  * Constant for num of busy-loop iterations after which
9026  * a timer interrupt should have happened in host
9027  */
9028 #define TIMER_INTERRUPT_DELAY 100000000
9029 
9030 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
9031 {
9032 	handle_irq(0x79, irq_79_handler_guest);
9033 	irq_enable();
9034 
9035 	/* Signal to L1 CPU to trigger ioapic scan */
9036 	vmx_set_test_stage(1);
9037 	/* Wait until L1 CPU to trigger ioapic scan */
9038 	while (vmx_get_test_stage() != 2)
9039 		;
9040 
9041 	/*
9042 	 * Wait for L0 timer interrupt to be raised while we run in L2
9043 	 * such that L0 will process the IOAPIC scan request before
9044 	 * resuming L2
9045 	 */
9046 	delay(TIMER_INTERRUPT_DELAY);
9047 
9048 	asm volatile ("int $0x79");
9049 }
9050 
9051 static void vmx_eoi_bitmap_ioapic_scan_test(void)
9052 {
9053 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
9054 		report_skip(__func__);
9055 		return;
9056 	}
9057 
9058 	enable_vid();
9059 
9060 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
9061 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
9062 
9063 	/*
9064 	 * Launch L2.
9065 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
9066 	 * In case the reason isn't VMX_VMCALL, the asserion inside
9067 	 * skip_exit_vmcall() will fail.
9068 	 */
9069 	enter_guest();
9070 	skip_exit_vmcall();
9071 
9072 	/* Let L2 finish */
9073 	enter_guest();
9074 	report(1, __func__);
9075 }
9076 
9077 #define HLT_WITH_RVI_VECTOR		(0xf1)
9078 
9079 bool vmx_hlt_with_rvi_guest_isr_fired;
9080 static void vmx_hlt_with_rvi_guest_isr(isr_regs_t *regs)
9081 {
9082 	vmx_hlt_with_rvi_guest_isr_fired = true;
9083 	eoi();
9084 }
9085 
9086 static void vmx_hlt_with_rvi_guest(void)
9087 {
9088 	handle_irq(HLT_WITH_RVI_VECTOR, vmx_hlt_with_rvi_guest_isr);
9089 
9090 	irq_enable();
9091 	asm volatile ("nop");
9092 
9093 	vmcall();
9094 }
9095 
9096 static void vmx_hlt_with_rvi_test(void)
9097 {
9098 	if (!cpu_has_apicv()) {
9099 		report_skip(__func__);
9100 		return;
9101 	}
9102 
9103 	enable_vid();
9104 
9105 	vmx_hlt_with_rvi_guest_isr_fired = false;
9106 	test_set_guest(vmx_hlt_with_rvi_guest);
9107 
9108 	enter_guest();
9109 	skip_exit_vmcall();
9110 
9111 	vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
9112 	vmcs_write(GUEST_INT_STATUS, HLT_WITH_RVI_VECTOR);
9113 	enter_guest();
9114 
9115 	report(vmx_hlt_with_rvi_guest_isr_fired, "Interrupt raised in guest");
9116 }
9117 
9118 static void set_irq_line_thread(void *data)
9119 {
9120 	/* Wait until other CPU entered L2 */
9121 	while (vmx_get_test_stage() != 1)
9122 		;
9123 
9124 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
9125 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
9126 	vmx_set_test_stage(2);
9127 }
9128 
9129 static bool irq_78_handler_vmcall_before_eoi;
9130 static void irq_78_handler_guest(isr_regs_t *regs)
9131 {
9132 	set_irq_line(0xf, 0);
9133 	if (irq_78_handler_vmcall_before_eoi)
9134 		vmcall();
9135 	eoi();
9136 	vmcall();
9137 }
9138 
9139 static void vmx_apic_passthrough_guest(void)
9140 {
9141 	handle_irq(0x78, irq_78_handler_guest);
9142 	irq_enable();
9143 
9144 	/* If requested, wait for other CPU to trigger ioapic scan */
9145 	if (vmx_get_test_stage() < 1) {
9146 		vmx_set_test_stage(1);
9147 		while (vmx_get_test_stage() != 2)
9148 			;
9149 	}
9150 
9151 	set_irq_line(0xf, 1);
9152 }
9153 
9154 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
9155 {
9156 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
9157 		report_skip(__func__);
9158 		return;
9159 	}
9160 
9161 	/* Test device is required for generating IRQs */
9162 	if (!test_device_enabled()) {
9163 		report_skip(__func__);
9164 		return;
9165 	}
9166 	u64 cpu_ctrl_0 = CPU_SECONDARY;
9167 	u64 cpu_ctrl_1 = 0;
9168 
9169 	disable_intercept_for_x2apic_msrs();
9170 
9171 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
9172 
9173 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
9174 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
9175 
9176 	if (set_irq_line_from_thread) {
9177 		irq_78_handler_vmcall_before_eoi = false;
9178 		on_cpu_async(1, set_irq_line_thread, NULL);
9179 	} else {
9180 		irq_78_handler_vmcall_before_eoi = true;
9181 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
9182 		vmx_set_test_stage(2);
9183 	}
9184 	test_set_guest(vmx_apic_passthrough_guest);
9185 
9186 	if (irq_78_handler_vmcall_before_eoi) {
9187 		/* Before EOI remote_irr should still be set */
9188 		enter_guest();
9189 		skip_exit_vmcall();
9190 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
9191 			"IOAPIC pass-through: remote_irr=1 before EOI");
9192 	}
9193 
9194 	/* After EOI remote_irr should be cleared */
9195 	enter_guest();
9196 	skip_exit_vmcall();
9197 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
9198 		"IOAPIC pass-through: remote_irr=0 after EOI");
9199 
9200 	/* Let L2 finish */
9201 	enter_guest();
9202 	report(1, __func__);
9203 }
9204 
9205 static void vmx_apic_passthrough_test(void)
9206 {
9207 	vmx_apic_passthrough(false);
9208 }
9209 
9210 static void vmx_apic_passthrough_thread_test(void)
9211 {
9212 	vmx_apic_passthrough(true);
9213 }
9214 
9215 static void vmx_apic_passthrough_tpr_threshold_guest(void)
9216 {
9217 	cli();
9218 	apic_set_tpr(0);
9219 }
9220 
9221 static bool vmx_apic_passthrough_tpr_threshold_ipi_isr_fired;
9222 static void vmx_apic_passthrough_tpr_threshold_ipi_isr(isr_regs_t *regs)
9223 {
9224 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = true;
9225 	eoi();
9226 }
9227 
9228 static void vmx_apic_passthrough_tpr_threshold_test(void)
9229 {
9230 	int ipi_vector = 0xe1;
9231 
9232 	disable_intercept_for_x2apic_msrs();
9233 	vmcs_clear_bits(PIN_CONTROLS, PIN_EXTINT);
9234 
9235 	/* Raise L0 TPR-threshold by queueing vector in LAPIC IRR */
9236 	cli();
9237 	apic_set_tpr((ipi_vector >> 4) + 1);
9238 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
9239 			APIC_DM_FIXED | ipi_vector,
9240 			0);
9241 
9242 	test_set_guest(vmx_apic_passthrough_tpr_threshold_guest);
9243 	enter_guest();
9244 
9245 	report(apic_get_tpr() == 0, "TPR was zero by guest");
9246 
9247 	/* Clean pending self-IPI */
9248 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = false;
9249 	handle_irq(ipi_vector, vmx_apic_passthrough_tpr_threshold_ipi_isr);
9250 	sti();
9251 	asm volatile ("nop");
9252 	report(vmx_apic_passthrough_tpr_threshold_ipi_isr_fired, "self-IPI fired");
9253 
9254 	report(1, __func__);
9255 }
9256 
9257 static u64 init_signal_test_exit_reason;
9258 static bool init_signal_test_thread_continued;
9259 
9260 static void init_signal_test_thread(void *data)
9261 {
9262 	struct vmcs *test_vmcs = data;
9263 
9264 	/* Enter VMX operation (i.e. exec VMXON) */
9265 	u64 *ap_vmxon_region = alloc_page();
9266 	enable_vmx();
9267 	init_vmx(ap_vmxon_region);
9268 	_vmx_on(ap_vmxon_region);
9269 
9270 	/* Signal CPU have entered VMX operation */
9271 	vmx_set_test_stage(1);
9272 
9273 	/* Wait for BSP CPU to send INIT signal */
9274 	while (vmx_get_test_stage() != 2)
9275 		;
9276 
9277 	/*
9278 	 * Signal that we continue as usual as INIT signal
9279 	 * should be blocked while CPU is in VMX operation
9280 	 */
9281 	vmx_set_test_stage(3);
9282 
9283 	/* Wait for signal to enter VMX non-root mode */
9284 	while (vmx_get_test_stage() != 4)
9285 		;
9286 
9287 	/* Enter VMX non-root mode */
9288 	test_set_guest(v2_null_test_guest);
9289 	make_vmcs_current(test_vmcs);
9290 	enter_guest();
9291 	/* Save exit reason for BSP CPU to compare to expected result */
9292 	init_signal_test_exit_reason = vmcs_read(EXI_REASON);
9293 	/* VMCLEAR test-vmcs so it could be loaded by BSP CPU */
9294 	vmcs_clear(test_vmcs);
9295 	launched = false;
9296 	/* Signal that CPU exited to VMX root mode */
9297 	vmx_set_test_stage(5);
9298 
9299 	/* Wait for BSP CPU to signal to exit VMX operation */
9300 	while (vmx_get_test_stage() != 6)
9301 		;
9302 
9303 	/* Exit VMX operation (i.e. exec VMXOFF) */
9304 	vmx_off();
9305 
9306 	/*
9307 	 * Signal to BSP CPU that we continue as usual as INIT signal
9308 	 * should have been consumed by VMX_INIT exit from guest
9309 	 */
9310 	vmx_set_test_stage(7);
9311 
9312 	/* Wait for BSP CPU to signal to enter VMX operation */
9313 	while (vmx_get_test_stage() != 8)
9314 		;
9315 	/* Enter VMX operation (i.e. exec VMXON) */
9316 	_vmx_on(ap_vmxon_region);
9317 	/* Signal to BSP we are in VMX operation */
9318 	vmx_set_test_stage(9);
9319 
9320 	/* Wait for BSP CPU to send INIT signal */
9321 	while (vmx_get_test_stage() != 10)
9322 		;
9323 
9324 	/* Exit VMX operation (i.e. exec VMXOFF) */
9325 	vmx_off();
9326 
9327 	/*
9328 	 * Exiting VMX operation should result in latched
9329 	 * INIT signal being processed. Therefore, we should
9330 	 * never reach the below code. Thus, signal to BSP
9331 	 * CPU if we have reached here so it is able to
9332 	 * report an issue if it happens.
9333 	 */
9334 	init_signal_test_thread_continued = true;
9335 }
9336 
9337 #define INIT_SIGNAL_TEST_DELAY	100000000ULL
9338 
9339 static void vmx_init_signal_test(void)
9340 {
9341 	struct vmcs *test_vmcs;
9342 
9343 	if (cpu_count() < 2) {
9344 		report_skip(__func__);
9345 		return;
9346 	}
9347 
9348 	/* VMCLEAR test-vmcs so it could be loaded by other CPU */
9349 	vmcs_save(&test_vmcs);
9350 	vmcs_clear(test_vmcs);
9351 
9352 	vmx_set_test_stage(0);
9353 	on_cpu_async(1, init_signal_test_thread, test_vmcs);
9354 
9355 	/* Wait for other CPU to enter VMX operation */
9356 	while (vmx_get_test_stage() != 1)
9357 		;
9358 
9359 	/* Send INIT signal to other CPU */
9360 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9361 				   id_map[1]);
9362 	/* Signal other CPU we have sent INIT signal */
9363 	vmx_set_test_stage(2);
9364 
9365 	/*
9366 	 * Wait reasonable amount of time for INIT signal to
9367 	 * be received on other CPU and verify that other CPU
9368 	 * have proceed as usual to next test stage as INIT
9369 	 * signal should be blocked while other CPU in
9370 	 * VMX operation
9371 	 */
9372 	delay(INIT_SIGNAL_TEST_DELAY);
9373 	report(vmx_get_test_stage() == 3,
9374 	       "INIT signal blocked when CPU in VMX operation");
9375 	/* No point to continue if we failed at this point */
9376 	if (vmx_get_test_stage() != 3)
9377 		return;
9378 
9379 	/* Signal other CPU to enter VMX non-root mode */
9380 	init_signal_test_exit_reason = -1ull;
9381 	vmx_set_test_stage(4);
9382 	/*
9383 	 * Wait reasonable amont of time for other CPU
9384 	 * to exit to VMX root mode
9385 	 */
9386 	delay(INIT_SIGNAL_TEST_DELAY);
9387 	if (vmx_get_test_stage() != 5) {
9388 		report(false, "Pending INIT signal didn't result in VMX exit");
9389 		return;
9390 	}
9391 	report(init_signal_test_exit_reason == VMX_INIT,
9392 			"INIT signal during VMX non-root mode result in exit-reason %s (%lu)",
9393 			exit_reason_description(init_signal_test_exit_reason),
9394 			init_signal_test_exit_reason);
9395 
9396 	/* Run guest to completion */
9397 	make_vmcs_current(test_vmcs);
9398 	enter_guest();
9399 
9400 	/* Signal other CPU to exit VMX operation */
9401 	init_signal_test_thread_continued = false;
9402 	vmx_set_test_stage(6);
9403 
9404 	/* Wait reasonable amount of time for other CPU to exit VMX operation */
9405 	delay(INIT_SIGNAL_TEST_DELAY);
9406 	report(vmx_get_test_stage() == 7,
9407 	       "INIT signal consumed on VMX_INIT exit");
9408 	/* No point to continue if we failed at this point */
9409 	if (vmx_get_test_stage() != 7)
9410 		return;
9411 
9412 	/* Signal other CPU to enter VMX operation */
9413 	vmx_set_test_stage(8);
9414 	/* Wait for other CPU to enter VMX operation */
9415 	while (vmx_get_test_stage() != 9)
9416 		;
9417 
9418 	/* Send INIT signal to other CPU */
9419 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9420 				   id_map[1]);
9421 	/* Signal other CPU we have sent INIT signal */
9422 	vmx_set_test_stage(10);
9423 
9424 	/*
9425 	 * Wait reasonable amount of time for other CPU
9426 	 * to exit VMX operation and process INIT signal
9427 	 */
9428 	delay(INIT_SIGNAL_TEST_DELAY);
9429 	report(!init_signal_test_thread_continued,
9430 	       "INIT signal processed after exit VMX operation");
9431 
9432 	/*
9433 	 * TODO: Send SIPI to other CPU to sipi_entry (See x86/cstart64.S)
9434 	 * to re-init it to kvm-unit-tests standard environment.
9435 	 * Somehow (?) verify that SIPI was indeed received.
9436 	 */
9437 }
9438 
9439 enum vmcs_access {
9440 	ACCESS_VMREAD,
9441 	ACCESS_VMWRITE,
9442 	ACCESS_NONE,
9443 };
9444 
9445 struct vmcs_shadow_test_common {
9446 	enum vmcs_access op;
9447 	enum Reason reason;
9448 	u64 field;
9449 	u64 value;
9450 	u64 flags;
9451 	u64 time;
9452 } l1_l2_common;
9453 
9454 static inline u64 vmread_flags(u64 field, u64 *val)
9455 {
9456 	u64 flags;
9457 
9458 	asm volatile ("vmread %2, %1; pushf; pop %0"
9459 		      : "=r" (flags), "=rm" (*val) : "r" (field) : "cc");
9460 	return flags & X86_EFLAGS_ALU;
9461 }
9462 
9463 static inline u64 vmwrite_flags(u64 field, u64 val)
9464 {
9465 	u64 flags;
9466 
9467 	asm volatile ("vmwrite %1, %2; pushf; pop %0"
9468 		      : "=r"(flags) : "rm" (val), "r" (field) : "cc");
9469 	return flags & X86_EFLAGS_ALU;
9470 }
9471 
9472 static void vmx_vmcs_shadow_test_guest(void)
9473 {
9474 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9475 	u64 start;
9476 
9477 	while (c->op != ACCESS_NONE) {
9478 		start = rdtsc();
9479 		switch (c->op) {
9480 		default:
9481 			c->flags = -1ull;
9482 			break;
9483 		case ACCESS_VMREAD:
9484 			c->flags = vmread_flags(c->field, &c->value);
9485 			break;
9486 		case ACCESS_VMWRITE:
9487 			c->flags = vmwrite_flags(c->field, 0);
9488 			break;
9489 		}
9490 		c->time = rdtsc() - start;
9491 		vmcall();
9492 	}
9493 }
9494 
9495 static u64 vmread_from_shadow(u64 field)
9496 {
9497 	struct vmcs *primary;
9498 	struct vmcs *shadow;
9499 	u64 value;
9500 
9501 	TEST_ASSERT(!vmcs_save(&primary));
9502 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9503 	TEST_ASSERT(!make_vmcs_current(shadow));
9504 	value = vmcs_read(field);
9505 	TEST_ASSERT(!make_vmcs_current(primary));
9506 	return value;
9507 }
9508 
9509 static u64 vmwrite_to_shadow(u64 field, u64 value)
9510 {
9511 	struct vmcs *primary;
9512 	struct vmcs *shadow;
9513 
9514 	TEST_ASSERT(!vmcs_save(&primary));
9515 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9516 	TEST_ASSERT(!make_vmcs_current(shadow));
9517 	vmcs_write(field, value);
9518 	value = vmcs_read(field);
9519 	TEST_ASSERT(!make_vmcs_current(primary));
9520 	return value;
9521 }
9522 
9523 static void vmcs_shadow_test_access(u8 *bitmap[2], enum vmcs_access access)
9524 {
9525 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9526 
9527 	c->op = access;
9528 	vmcs_write(VMX_INST_ERROR, 0);
9529 	enter_guest();
9530 	c->reason = vmcs_read(EXI_REASON) & 0xffff;
9531 	if (c->reason != VMX_VMCALL) {
9532 		skip_exit_insn();
9533 		enter_guest();
9534 	}
9535 	skip_exit_vmcall();
9536 }
9537 
9538 static void vmcs_shadow_test_field(u8 *bitmap[2], u64 field)
9539 {
9540 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9541 	struct vmcs *shadow;
9542 	u64 value;
9543 	uintptr_t flags[2];
9544 	bool good_shadow;
9545 	u32 vmx_inst_error;
9546 
9547 	report_prefix_pushf("field %lx", field);
9548 	c->field = field;
9549 
9550 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
9551 	if (shadow != (struct vmcs *)-1ull) {
9552 		flags[ACCESS_VMREAD] = vmread_flags(field, &value);
9553 		flags[ACCESS_VMWRITE] = vmwrite_flags(field, value);
9554 		good_shadow = !flags[ACCESS_VMREAD] && !flags[ACCESS_VMWRITE];
9555 	} else {
9556 		/*
9557 		 * When VMCS link pointer is -1ull, VMWRITE/VMREAD on
9558 		 * shadowed-fields should fail with setting RFLAGS.CF.
9559 		 */
9560 		flags[ACCESS_VMREAD] = X86_EFLAGS_CF;
9561 		flags[ACCESS_VMWRITE] = X86_EFLAGS_CF;
9562 		good_shadow = false;
9563 	}
9564 
9565 	/* Intercept both VMREAD and VMWRITE. */
9566 	report_prefix_push("no VMREAD/VMWRITE permission");
9567 	/* VMWRITE/VMREAD done on reserved-bit should always intercept */
9568 	if (!(field >> VMCS_FIELD_RESERVED_SHIFT)) {
9569 		set_bit(field, bitmap[ACCESS_VMREAD]);
9570 		set_bit(field, bitmap[ACCESS_VMWRITE]);
9571 	}
9572 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9573 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
9574 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9575 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
9576 	report_prefix_pop();
9577 
9578 	if (field >> VMCS_FIELD_RESERVED_SHIFT)
9579 		goto out;
9580 
9581 	/* Permit shadowed VMREAD. */
9582 	report_prefix_push("VMREAD permission only");
9583 	clear_bit(field, bitmap[ACCESS_VMREAD]);
9584 	set_bit(field, bitmap[ACCESS_VMWRITE]);
9585 	if (good_shadow)
9586 		value = vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9587 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9588 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
9589 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9590 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9591 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
9592 	       c->time);
9593 	report(c->flags == flags[ACCESS_VMREAD],
9594 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
9595 	       c->flags, flags[ACCESS_VMREAD]);
9596 	if (good_shadow)
9597 		report(c->value == value,
9598 		       "value read from shadow (%lx) is as expected (%lx)",
9599 		       c->value, value);
9600 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
9601 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9602 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9603 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9604 	report_prefix_pop();
9605 
9606 	/* Permit shadowed VMWRITE. */
9607 	report_prefix_push("VMWRITE permission only");
9608 	set_bit(field, bitmap[ACCESS_VMREAD]);
9609 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
9610 	if (good_shadow)
9611 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9612 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9613 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9614 	report(c->reason == VMX_VMCALL,
9615 		"shadowed for VMWRITE (in %ld cycles)",
9616 		c->time);
9617 	report(c->flags == flags[ACCESS_VMREAD],
9618 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
9619 	       c->flags, flags[ACCESS_VMREAD]);
9620 	if (good_shadow) {
9621 		value = vmread_from_shadow(field);
9622 		report(value == 0,
9623 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
9624 		       0ul);
9625 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
9626 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9627 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9628 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9629 	}
9630 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9631 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
9632 	report_prefix_pop();
9633 
9634 	/* Permit shadowed VMREAD and VMWRITE. */
9635 	report_prefix_push("VMREAD and VMWRITE permission");
9636 	clear_bit(field, bitmap[ACCESS_VMREAD]);
9637 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
9638 	if (good_shadow)
9639 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
9640 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
9641 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9642 	report(c->reason == VMX_VMCALL,
9643 		"shadowed for VMWRITE (in %ld cycles)",
9644 		c->time);
9645 	report(c->flags == flags[ACCESS_VMREAD],
9646 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
9647 	       c->flags, flags[ACCESS_VMREAD]);
9648 	if (good_shadow) {
9649 		value = vmread_from_shadow(field);
9650 		report(value == 0,
9651 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
9652 		       0ul);
9653 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
9654 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9655 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9656 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9657 	}
9658 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
9659 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
9660 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
9661 	       c->time);
9662 	report(c->flags == flags[ACCESS_VMREAD],
9663 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
9664 	       c->flags, flags[ACCESS_VMREAD]);
9665 	if (good_shadow)
9666 		report(c->value == 0,
9667 		       "value read from shadow (%lx) is as expected (%lx)",
9668 		       c->value, 0ul);
9669 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
9670 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
9671 		       "VMX_INST_ERROR (%d) is as expected (%d)",
9672 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
9673 	report_prefix_pop();
9674 
9675 out:
9676 	report_prefix_pop();
9677 }
9678 
9679 static void vmx_vmcs_shadow_test_body(u8 *bitmap[2])
9680 {
9681 	unsigned base;
9682 	unsigned index;
9683 	unsigned bit;
9684 	unsigned highest_index = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
9685 
9686 	/* Run test on all possible valid VMCS fields */
9687 	for (base = 0;
9688 	     base < (1 << VMCS_FIELD_RESERVED_SHIFT);
9689 	     base += (1 << VMCS_FIELD_TYPE_SHIFT))
9690 		for (index = 0; index <= highest_index; index++)
9691 			vmcs_shadow_test_field(bitmap, base + index);
9692 
9693 	/*
9694 	 * Run tests on some invalid VMCS fields
9695 	 * (Have reserved bit set).
9696 	 */
9697 	for (bit = VMCS_FIELD_RESERVED_SHIFT; bit < VMCS_FIELD_BIT_SIZE; bit++)
9698 		vmcs_shadow_test_field(bitmap, (1ull << bit));
9699 }
9700 
9701 static void vmx_vmcs_shadow_test(void)
9702 {
9703 	u8 *bitmap[2];
9704 	struct vmcs *shadow;
9705 
9706 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
9707 		printf("\t'Activate secondary controls' not supported.\n");
9708 		return;
9709 	}
9710 
9711 	if (!(ctrl_cpu_rev[1].clr & CPU_SHADOW_VMCS)) {
9712 		printf("\t'VMCS shadowing' not supported.\n");
9713 		return;
9714 	}
9715 
9716 	if (!(rdmsr(MSR_IA32_VMX_MISC) &
9717 	      MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) {
9718 		printf("\tVMWRITE can't modify VM-exit information fields.\n");
9719 		return;
9720 	}
9721 
9722 	test_set_guest(vmx_vmcs_shadow_test_guest);
9723 
9724 	bitmap[ACCESS_VMREAD] = alloc_page();
9725 	bitmap[ACCESS_VMWRITE] = alloc_page();
9726 
9727 	vmcs_write(VMREAD_BITMAP, virt_to_phys(bitmap[ACCESS_VMREAD]));
9728 	vmcs_write(VMWRITE_BITMAP, virt_to_phys(bitmap[ACCESS_VMWRITE]));
9729 
9730 	shadow = alloc_page();
9731 	shadow->hdr.revision_id = basic.revision;
9732 	shadow->hdr.shadow_vmcs = 1;
9733 	TEST_ASSERT(!vmcs_clear(shadow));
9734 
9735 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_RDTSC);
9736 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
9737 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_SHADOW_VMCS);
9738 
9739 	vmcs_write(VMCS_LINK_PTR, virt_to_phys(shadow));
9740 	report_prefix_push("valid link pointer");
9741 	vmx_vmcs_shadow_test_body(bitmap);
9742 	report_prefix_pop();
9743 
9744 	vmcs_write(VMCS_LINK_PTR, -1ull);
9745 	report_prefix_push("invalid link pointer");
9746 	vmx_vmcs_shadow_test_body(bitmap);
9747 	report_prefix_pop();
9748 
9749 	l1_l2_common.op = ACCESS_NONE;
9750 	enter_guest();
9751 }
9752 
9753 /*
9754  * This test monitors the difference between a guest RDTSC instruction
9755  * and the IA32_TIME_STAMP_COUNTER MSR value stored in the VMCS12
9756  * VM-exit MSR-store list when taking a VM-exit on the instruction
9757  * following RDTSC.
9758  */
9759 #define RDTSC_DIFF_ITERS 100000
9760 #define RDTSC_DIFF_FAILS 100
9761 #define HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD 750
9762 
9763 /*
9764  * Set 'use TSC offsetting' and set the guest offset to the
9765  * inverse of the host's current TSC value, so that the guest starts running
9766  * with an effective TSC value of 0.
9767  */
9768 static void reset_guest_tsc_to_zero(void)
9769 {
9770 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
9771 	vmcs_write(TSC_OFFSET, -rdtsc());
9772 }
9773 
9774 static void rdtsc_vmexit_diff_test_guest(void)
9775 {
9776 	int i;
9777 
9778 	for (i = 0; i < RDTSC_DIFF_ITERS; i++)
9779 		/* Ensure rdtsc is the last instruction before the vmcall. */
9780 		asm volatile("rdtsc; vmcall" : : : "eax", "edx");
9781 }
9782 
9783 /*
9784  * This function only considers the "use TSC offsetting" VM-execution
9785  * control.  It does not handle "use TSC scaling" (because the latter
9786  * isn't available to the host today.)
9787  */
9788 static unsigned long long host_time_to_guest_time(unsigned long long t)
9789 {
9790 	TEST_ASSERT(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
9791 		    !(vmcs_read(CPU_EXEC_CTRL1) & CPU_USE_TSC_SCALING));
9792 
9793 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_USE_TSC_OFFSET)
9794 		t += vmcs_read(TSC_OFFSET);
9795 
9796 	return t;
9797 }
9798 
9799 static unsigned long long rdtsc_vmexit_diff_test_iteration(void)
9800 {
9801 	unsigned long long guest_tsc, host_to_guest_tsc;
9802 
9803 	enter_guest();
9804 	skip_exit_vmcall();
9805 	guest_tsc = (u32) regs.rax + (regs.rdx << 32);
9806 	host_to_guest_tsc = host_time_to_guest_time(exit_msr_store[0].value);
9807 
9808 	return host_to_guest_tsc - guest_tsc;
9809 }
9810 
9811 static void rdtsc_vmexit_diff_test(void)
9812 {
9813 	unsigned long long delta;
9814 	int fail = 0;
9815 	int i;
9816 
9817 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET))
9818 		test_skip("CPU doesn't support the 'use TSC offsetting' processor-based VM-execution control.\n");
9819 
9820 	test_set_guest(rdtsc_vmexit_diff_test_guest);
9821 
9822 	reset_guest_tsc_to_zero();
9823 
9824 	/*
9825 	 * Set up the VMCS12 VM-exit MSR-store list to store just one
9826 	 * MSR: IA32_TIME_STAMP_COUNTER. Note that the value stored is
9827 	 * in the host time domain (i.e., it is not adjusted according
9828 	 * to the TSC multiplier and TSC offset fields in the VMCS12,
9829 	 * as a guest RDTSC would be.)
9830 	 */
9831 	exit_msr_store = alloc_page();
9832 	exit_msr_store[0].index = MSR_IA32_TSC;
9833 	vmcs_write(EXI_MSR_ST_CNT, 1);
9834 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(exit_msr_store));
9835 
9836 	for (i = 0; i < RDTSC_DIFF_ITERS && fail < RDTSC_DIFF_FAILS; i++) {
9837 		delta = rdtsc_vmexit_diff_test_iteration();
9838 		if (delta >= HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD)
9839 			fail++;
9840 	}
9841 
9842 	enter_guest();
9843 
9844 	report(fail < RDTSC_DIFF_FAILS,
9845 	       "RDTSC to VM-exit delta too high in %d of %d iterations, last = %llu",
9846 	       fail, i, delta);
9847 }
9848 
9849 static int invalid_msr_init(struct vmcs *vmcs)
9850 {
9851 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
9852 		printf("\tPreemption timer is not supported\n");
9853 		return VMX_TEST_EXIT;
9854 	}
9855 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
9856 	preempt_val = 10000000;
9857 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
9858 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
9859 
9860 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
9861 		printf("\tSave preemption value is not supported\n");
9862 
9863 	vmcs_write(ENT_MSR_LD_CNT, 1);
9864 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)0x13370000);
9865 
9866 	return VMX_TEST_START;
9867 }
9868 
9869 
9870 static void invalid_msr_main(void)
9871 {
9872 	report(0, "Invalid MSR load");
9873 }
9874 
9875 static int invalid_msr_exit_handler(union exit_reason exit_reason)
9876 {
9877 	report(0, "Invalid MSR load");
9878 	print_vmexit_info(exit_reason);
9879 	return VMX_TEST_EXIT;
9880 }
9881 
9882 static int invalid_msr_entry_failure(struct vmentry_result *result)
9883 {
9884 	report(result->exit_reason.failed_vmentry &&
9885 	       result->exit_reason.basic == VMX_FAIL_MSR, "Invalid MSR load");
9886 	return VMX_TEST_VMEXIT;
9887 }
9888 
9889 /*
9890  * The max number of MSRs in an atomic switch MSR list is:
9891  * (111B + 1) * 512 = 4096
9892  *
9893  * Each list entry consumes:
9894  * 4-byte MSR index + 4 bytes reserved + 8-byte data = 16 bytes
9895  *
9896  * Allocate 128 kB to cover max_msr_list_size (i.e., 64 kB) and then some.
9897  */
9898 static const u32 msr_list_page_order = 5;
9899 
9900 static void atomic_switch_msr_limit_test_guest(void)
9901 {
9902 	vmcall();
9903 }
9904 
9905 static void populate_msr_list(struct vmx_msr_entry *msr_list,
9906 			      size_t byte_capacity, int count)
9907 {
9908 	int i;
9909 
9910 	for (i = 0; i < count; i++) {
9911 		msr_list[i].index = MSR_IA32_TSC;
9912 		msr_list[i].reserved = 0;
9913 		msr_list[i].value = 0x1234567890abcdef;
9914 	}
9915 
9916 	memset(msr_list + count, 0xff,
9917 	       byte_capacity - count * sizeof(*msr_list));
9918 }
9919 
9920 static int max_msr_list_size(void)
9921 {
9922 	u32 vmx_misc = rdmsr(MSR_IA32_VMX_MISC);
9923 	u32 factor = ((vmx_misc & GENMASK(27, 25)) >> 25) + 1;
9924 
9925 	return factor * 512;
9926 }
9927 
9928 static void atomic_switch_msrs_test(int count)
9929 {
9930 	struct vmx_msr_entry *vm_enter_load;
9931         struct vmx_msr_entry *vm_exit_load;
9932         struct vmx_msr_entry *vm_exit_store;
9933 	int max_allowed = max_msr_list_size();
9934 	int byte_capacity = 1ul << (msr_list_page_order + PAGE_SHIFT);
9935 	/* Exceeding the max MSR list size at exit trigers KVM to abort. */
9936 	int exit_count = count > max_allowed ? max_allowed : count;
9937 	int cleanup_count = count > max_allowed ? 2 : 1;
9938 	int i;
9939 
9940 	/*
9941 	 * Check for the IA32_TSC MSR,
9942 	 * available with the "TSC flag" and used to populate the MSR lists.
9943 	 */
9944 	if (!(cpuid(1).d & (1 << 4))) {
9945 		report_skip(__func__);
9946 		return;
9947 	}
9948 
9949 	/* Set L2 guest. */
9950 	test_set_guest(atomic_switch_msr_limit_test_guest);
9951 
9952 	/* Setup atomic MSR switch lists. */
9953 	vm_enter_load = alloc_pages(msr_list_page_order);
9954 	vm_exit_load = alloc_pages(msr_list_page_order);
9955 	vm_exit_store = alloc_pages(msr_list_page_order);
9956 
9957 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)vm_enter_load);
9958 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)vm_exit_load);
9959 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)vm_exit_store);
9960 
9961 	/*
9962 	 * VM-Enter should succeed up to the max number of MSRs per list, and
9963 	 * should not consume junk beyond the last entry.
9964 	 */
9965 	populate_msr_list(vm_enter_load, byte_capacity, count);
9966 	populate_msr_list(vm_exit_load, byte_capacity, exit_count);
9967 	populate_msr_list(vm_exit_store, byte_capacity, exit_count);
9968 
9969 	vmcs_write(ENT_MSR_LD_CNT, count);
9970 	vmcs_write(EXI_MSR_LD_CNT, exit_count);
9971 	vmcs_write(EXI_MSR_ST_CNT, exit_count);
9972 
9973 	if (count <= max_allowed) {
9974 		enter_guest();
9975 		assert_exit_reason(VMX_VMCALL);
9976 		skip_exit_vmcall();
9977 	} else {
9978 		u32 exit_qual;
9979 
9980 		test_guest_state("Invalid MSR Load Count", true, count,
9981 				 "ENT_MSR_LD_CNT");
9982 
9983 		exit_qual = vmcs_read(EXI_QUALIFICATION);
9984 		report(exit_qual == max_allowed + 1, "exit_qual, %u, is %u.",
9985 		       exit_qual, max_allowed + 1);
9986 	}
9987 
9988 	/* Cleanup. */
9989 	vmcs_write(ENT_MSR_LD_CNT, 0);
9990 	vmcs_write(EXI_MSR_LD_CNT, 0);
9991 	vmcs_write(EXI_MSR_ST_CNT, 0);
9992 	for (i = 0; i < cleanup_count; i++) {
9993 		enter_guest();
9994 		skip_exit_vmcall();
9995 	}
9996 	free_pages_by_order(vm_enter_load, msr_list_page_order);
9997 	free_pages_by_order(vm_exit_load, msr_list_page_order);
9998 	free_pages_by_order(vm_exit_store, msr_list_page_order);
9999 }
10000 
10001 static void atomic_switch_max_msrs_test(void)
10002 {
10003 	atomic_switch_msrs_test(max_msr_list_size());
10004 }
10005 
10006 static void atomic_switch_overflow_msrs_test(void)
10007 {
10008 	if (test_device_enabled())
10009 		atomic_switch_msrs_test(max_msr_list_size() + 1);
10010 	else
10011 		test_skip("Test is only supported on KVM");
10012 }
10013 
10014 #define TEST(name) { #name, .v2 = name }
10015 
10016 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
10017 struct vmx_test vmx_tests[] = {
10018 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
10019 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
10020 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
10021 		preemption_timer_exit_handler, NULL, {0} },
10022 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
10023 		test_ctrl_pat_exit_handler, NULL, {0} },
10024 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
10025 		test_ctrl_efer_exit_handler, NULL, {0} },
10026 	{ "CR shadowing", NULL, cr_shadowing_main,
10027 		cr_shadowing_exit_handler, NULL, {0} },
10028 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
10029 		NULL, {0} },
10030 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
10031 		insn_intercept_exit_handler, NULL, {0} },
10032 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
10033 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
10034 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
10035 	{ "VPID", vpid_init, vpid_main, vpid_exit_handler, NULL, {0} },
10036 	{ "interrupt", interrupt_init, interrupt_main,
10037 		interrupt_exit_handler, NULL, {0} },
10038 	{ "nmi_hlt", nmi_hlt_init, nmi_hlt_main,
10039 		nmi_hlt_exit_handler, NULL, {0} },
10040 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
10041 		NULL, {0} },
10042 	{ "MSR switch", msr_switch_init, msr_switch_main,
10043 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
10044 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
10045 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
10046 		disable_rdtscp_exit_handler, NULL, {0} },
10047 	{ "int3", int3_init, int3_guest_main, int3_exit_handler, NULL, {0} },
10048 	{ "into", into_init, into_guest_main, into_exit_handler, NULL, {0} },
10049 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
10050 		exit_monitor_from_l2_handler, NULL, {0} },
10051 	{ "invalid_msr", invalid_msr_init, invalid_msr_main,
10052 		invalid_msr_exit_handler, NULL, {0}, invalid_msr_entry_failure},
10053 	/* Basic V2 tests. */
10054 	TEST(v2_null_test),
10055 	TEST(v2_multiple_entries_test),
10056 	TEST(fixture_test_case1),
10057 	TEST(fixture_test_case2),
10058 	/* Opcode tests. */
10059 	TEST(invvpid_test_v2),
10060 	/* VM-entry tests */
10061 	TEST(vmx_controls_test),
10062 	TEST(vmx_host_state_area_test),
10063 	TEST(vmx_guest_state_area_test),
10064 	TEST(vmentry_movss_shadow_test),
10065 	/* APICv tests */
10066 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
10067 	TEST(vmx_hlt_with_rvi_test),
10068 	TEST(apic_reg_virt_test),
10069 	TEST(virt_x2apic_mode_test),
10070 	/* APIC pass-through tests */
10071 	TEST(vmx_apic_passthrough_test),
10072 	TEST(vmx_apic_passthrough_thread_test),
10073 	TEST(vmx_apic_passthrough_tpr_threshold_test),
10074 	TEST(vmx_init_signal_test),
10075 	/* VMCS Shadowing tests */
10076 	TEST(vmx_vmcs_shadow_test),
10077 	/* Regression tests */
10078 	TEST(vmx_cr_load_test),
10079 	TEST(vmx_nm_test),
10080 	TEST(vmx_db_test),
10081 	TEST(vmx_nmi_window_test),
10082 	TEST(vmx_intr_window_test),
10083 	TEST(vmx_pending_event_test),
10084 	TEST(vmx_pending_event_hlt_test),
10085 	TEST(vmx_store_tsc_test),
10086 	TEST(vmx_preemption_timer_zero_test),
10087 	TEST(vmx_preemption_timer_tf_test),
10088 	TEST(vmx_preemption_timer_expiry_test),
10089 	/* EPT access tests. */
10090 	TEST(ept_access_test_not_present),
10091 	TEST(ept_access_test_read_only),
10092 	TEST(ept_access_test_write_only),
10093 	TEST(ept_access_test_read_write),
10094 	TEST(ept_access_test_execute_only),
10095 	TEST(ept_access_test_read_execute),
10096 	TEST(ept_access_test_write_execute),
10097 	TEST(ept_access_test_read_write_execute),
10098 	TEST(ept_access_test_reserved_bits),
10099 	TEST(ept_access_test_ignored_bits),
10100 	TEST(ept_access_test_paddr_not_present_ad_disabled),
10101 	TEST(ept_access_test_paddr_not_present_ad_enabled),
10102 	TEST(ept_access_test_paddr_read_only_ad_disabled),
10103 	TEST(ept_access_test_paddr_read_only_ad_enabled),
10104 	TEST(ept_access_test_paddr_read_write),
10105 	TEST(ept_access_test_paddr_read_write_execute),
10106 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
10107 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
10108 	TEST(ept_access_test_paddr_not_present_page_fault),
10109 	TEST(ept_access_test_force_2m_page),
10110 	/* Atomic MSR switch tests. */
10111 	TEST(atomic_switch_max_msrs_test),
10112 	TEST(atomic_switch_overflow_msrs_test),
10113 	TEST(rdtsc_vmexit_diff_test),
10114 	TEST(vmx_mtf_test),
10115 	{ NULL, NULL, NULL, NULL, NULL, {0} },
10116 };
10117