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