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