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