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