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