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