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