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