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