xref: /kvm-unit-tests/x86/vmx_tests.c (revision 0a6b8b7d601a2ce8b7b770a580db8009e800999e)
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 		eptp &= ~EPTP_AD_FLAG;
4755 	}
4756 
4757 	/*
4758 	 * Reserved bits [11:7] and [63:N]
4759 	 */
4760 	for (i = 0; i < 32; i++) {
4761 		eptp = (eptp &
4762 		    ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT)) |
4763 		    (i << EPTP_RESERV_BITS_SHIFT);
4764 		vmcs_write(EPTP, eptp);
4765 		report_prefix_pushf("Enable-EPT enabled; reserved bits [11:7] %lu",
4766 		    (eptp >> EPTP_RESERV_BITS_SHIFT) &
4767 		    EPTP_RESERV_BITS_MASK);
4768 		if (i == 0)
4769 			test_vmx_valid_controls();
4770 		else
4771 			test_vmx_invalid_controls();
4772 		report_prefix_pop();
4773 	}
4774 
4775 	eptp = (eptp & ~(EPTP_RESERV_BITS_MASK << EPTP_RESERV_BITS_SHIFT));
4776 
4777 	maxphysaddr = cpuid_maxphyaddr();
4778 	for (i = 0; i < (63 - maxphysaddr + 1); i++) {
4779 		resv_bits_mask |= 1ul << i;
4780 	}
4781 
4782 	for (j = maxphysaddr - 1; j <= 63; j++) {
4783 		eptp = (eptp & ~(resv_bits_mask << maxphysaddr)) |
4784 		    (j < maxphysaddr ? 0 : 1ul << j);
4785 		vmcs_write(EPTP, eptp);
4786 		report_prefix_pushf("Enable-EPT enabled; reserved bits [63:N] %lu",
4787 		    (eptp >> maxphysaddr) & resv_bits_mask);
4788 		if (j < maxphysaddr)
4789 			test_vmx_valid_controls();
4790 		else
4791 			test_vmx_invalid_controls();
4792 		report_prefix_pop();
4793 	}
4794 
4795 	secondary &= ~(CPU_EPT | CPU_URG);
4796 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4797 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest disabled");
4798 	test_vmx_valid_controls();
4799 	report_prefix_pop();
4800 
4801 	if (!(ctrl_cpu_rev[1].clr & CPU_URG))
4802 		goto skip_unrestricted_guest;
4803 
4804 	secondary |= CPU_URG;
4805 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4806 	report_prefix_pushf("Enable-EPT disabled, unrestricted-guest enabled");
4807 	test_vmx_invalid_controls();
4808 	report_prefix_pop();
4809 
4810 	secondary |= CPU_EPT;
4811 	setup_dummy_ept();
4812 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest enabled");
4813 	test_vmx_valid_controls();
4814 	report_prefix_pop();
4815 
4816 skip_unrestricted_guest:
4817 	secondary &= ~CPU_URG;
4818 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4819 	report_prefix_pushf("Enable-EPT enabled, unrestricted-guest disabled");
4820 	test_vmx_valid_controls();
4821 	report_prefix_pop();
4822 
4823 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4824 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4825 	vmcs_write(EPTP, eptp_saved);
4826 }
4827 
4828 /*
4829  * If the 'enable PML' VM-execution control is 1, the 'enable EPT'
4830  * VM-execution control must also be 1. In addition, the PML address
4831  * must satisfy the following checks:
4832  *
4833  *    * Bits 11:0 of the address must be 0.
4834  *    * The address should not set any bits beyond the processor's
4835  *	physical-address width.
4836  *
4837  *  [Intel SDM]
4838  */
4839 static void test_pml(void)
4840 {
4841 	u32 primary_saved = vmcs_read(CPU_EXEC_CTRL0);
4842 	u32 secondary_saved = vmcs_read(CPU_EXEC_CTRL1);
4843 	u32 primary = primary_saved;
4844 	u32 secondary = secondary_saved;
4845 
4846 	if (!((ctrl_cpu_rev[0].clr & CPU_SECONDARY) &&
4847 	    (ctrl_cpu_rev[1].clr & CPU_EPT) && (ctrl_cpu_rev[1].clr & CPU_PML))) {
4848 		report_skip("%s : \"Secondary execution\" or \"enable EPT\" or \"enable PML\" control not supported", __func__);
4849 		return;
4850 	}
4851 
4852 	primary |= CPU_SECONDARY;
4853 	vmcs_write(CPU_EXEC_CTRL0, primary);
4854 	secondary &= ~(CPU_PML | CPU_EPT);
4855 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4856 	report_prefix_pushf("enable-PML disabled, enable-EPT disabled");
4857 	test_vmx_valid_controls();
4858 	report_prefix_pop();
4859 
4860 	secondary |= CPU_PML;
4861 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4862 	report_prefix_pushf("enable-PML enabled, enable-EPT disabled");
4863 	test_vmx_invalid_controls();
4864 	report_prefix_pop();
4865 
4866 	secondary |= CPU_EPT;
4867 	setup_dummy_ept();
4868 	report_prefix_pushf("enable-PML enabled, enable-EPT enabled");
4869 	test_vmx_valid_controls();
4870 	report_prefix_pop();
4871 
4872 	secondary &= ~CPU_PML;
4873 	vmcs_write(CPU_EXEC_CTRL1, secondary);
4874 	report_prefix_pushf("enable-PML disabled, enable EPT enabled");
4875 	test_vmx_valid_controls();
4876 	report_prefix_pop();
4877 
4878 	test_vmcs_addr_reference(CPU_PML, PMLADDR, "PML address", "PML",
4879 				 PAGE_SIZE, false, false);
4880 
4881 	vmcs_write(CPU_EXEC_CTRL0, primary_saved);
4882 	vmcs_write(CPU_EXEC_CTRL1, secondary_saved);
4883 }
4884 
4885  /*
4886  * If the "activate VMX-preemption timer" VM-execution control is 0, the
4887  * the "save VMX-preemption timer value" VM-exit control must also be 0.
4888  *
4889  *  [Intel SDM]
4890  */
4891 static void test_vmx_preemption_timer(void)
4892 {
4893 	u32 saved_pin = vmcs_read(PIN_CONTROLS);
4894 	u32 saved_exit = vmcs_read(EXI_CONTROLS);
4895 	u32 pin = saved_pin;
4896 	u32 exit = saved_exit;
4897 
4898 	if (!((ctrl_exit_rev.clr & EXI_SAVE_PREEMPT) ||
4899 	    (ctrl_pin_rev.clr & PIN_PREEMPT))) {
4900 		report_skip("%s : \"Save-VMX-preemption-timer\" and/or \"Enable-VMX-preemption-timer\" control not supported", __func__);
4901 		return;
4902 	}
4903 
4904 	pin |= PIN_PREEMPT;
4905 	vmcs_write(PIN_CONTROLS, pin);
4906 	exit &= ~EXI_SAVE_PREEMPT;
4907 	vmcs_write(EXI_CONTROLS, exit);
4908 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer disabled");
4909 	test_vmx_valid_controls();
4910 	report_prefix_pop();
4911 
4912 	exit |= EXI_SAVE_PREEMPT;
4913 	vmcs_write(EXI_CONTROLS, exit);
4914 	report_prefix_pushf("enable-VMX-preemption-timer enabled, save-VMX-preemption-timer enabled");
4915 	test_vmx_valid_controls();
4916 	report_prefix_pop();
4917 
4918 	pin &= ~PIN_PREEMPT;
4919 	vmcs_write(PIN_CONTROLS, pin);
4920 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer enabled");
4921 	test_vmx_invalid_controls();
4922 	report_prefix_pop();
4923 
4924 	exit &= ~EXI_SAVE_PREEMPT;
4925 	vmcs_write(EXI_CONTROLS, exit);
4926 	report_prefix_pushf("enable-VMX-preemption-timer disabled, save-VMX-preemption-timer disabled");
4927 	test_vmx_valid_controls();
4928 	report_prefix_pop();
4929 
4930 	vmcs_write(PIN_CONTROLS, saved_pin);
4931 	vmcs_write(EXI_CONTROLS, saved_exit);
4932 }
4933 
4934 extern unsigned char test_mtf1;
4935 extern unsigned char test_mtf2;
4936 extern unsigned char test_mtf3;
4937 extern unsigned char test_mtf4;
4938 
4939 static void test_mtf_guest(void)
4940 {
4941 	asm ("vmcall;\n\t"
4942 	     "out %al, $0x80;\n\t"
4943 	     "test_mtf1:\n\t"
4944 	     "vmcall;\n\t"
4945 	     "out %al, $0x80;\n\t"
4946 	     "test_mtf2:\n\t"
4947 	     /*
4948 	      * Prepare for the 'MOV CR3' test. Attempt to induce a
4949 	      * general-protection fault by moving a non-canonical address into
4950 	      * CR3. The 'MOV CR3' instruction does not take an imm64 operand,
4951 	      * so we must MOV the desired value into a register first.
4952 	      *
4953 	      * MOV RAX is done before the VMCALL such that MTF is only enabled
4954 	      * for the instruction under test.
4955 	      */
4956 	     "mov $0xaaaaaaaaaaaaaaaa, %rax;\n\t"
4957 	     "vmcall;\n\t"
4958 	     "mov %rax, %cr3;\n\t"
4959 	     "test_mtf3:\n\t"
4960 	     "vmcall;\n\t"
4961 	     /*
4962 	      * ICEBP/INT1 instruction. Though the instruction is now
4963 	      * documented, don't rely on assemblers enumerating the
4964 	      * instruction. Resort to hand assembly.
4965 	      */
4966 	     ".byte 0xf1;\n\t"
4967 	     "vmcall;\n\t"
4968 	     "test_mtf4:\n\t"
4969 	     "mov $0, %eax;\n\t");
4970 }
4971 
4972 static void test_mtf_gp_handler(struct ex_regs *regs)
4973 {
4974 	regs->rip = (unsigned long) &test_mtf3;
4975 }
4976 
4977 static void test_mtf_db_handler(struct ex_regs *regs)
4978 {
4979 }
4980 
4981 static void enable_mtf(void)
4982 {
4983 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
4984 
4985 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 | CPU_MTF);
4986 }
4987 
4988 static void disable_mtf(void)
4989 {
4990 	u32 ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
4991 
4992 	vmcs_write(CPU_EXEC_CTRL0, ctrl0 & ~CPU_MTF);
4993 }
4994 
4995 static void enable_tf(void)
4996 {
4997 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
4998 
4999 	vmcs_write(GUEST_RFLAGS, rflags | X86_EFLAGS_TF);
5000 }
5001 
5002 static void disable_tf(void)
5003 {
5004 	unsigned long rflags = vmcs_read(GUEST_RFLAGS);
5005 
5006 	vmcs_write(GUEST_RFLAGS, rflags & ~X86_EFLAGS_TF);
5007 }
5008 
5009 static void report_mtf(const char *insn_name, unsigned long exp_rip)
5010 {
5011 	unsigned long rip = vmcs_read(GUEST_RIP);
5012 
5013 	assert_exit_reason(VMX_MTF);
5014 	report(rip == exp_rip, "MTF VM-exit after %s. RIP: 0x%lx (expected 0x%lx)",
5015 	       insn_name, rip, exp_rip);
5016 }
5017 
5018 static void vmx_mtf_test(void)
5019 {
5020 	unsigned long pending_dbg;
5021 	handler old_gp, old_db;
5022 
5023 	if (!(ctrl_cpu_rev[0].clr & CPU_MTF)) {
5024 		report_skip("%s : \"Monitor trap flag\" exec control not supported", __func__);
5025 		return;
5026 	}
5027 
5028 	test_set_guest(test_mtf_guest);
5029 
5030 	/* Expect an MTF VM-exit after OUT instruction */
5031 	enter_guest();
5032 	skip_exit_vmcall();
5033 
5034 	enable_mtf();
5035 	enter_guest();
5036 	report_mtf("OUT", (unsigned long) &test_mtf1);
5037 	disable_mtf();
5038 
5039 	/*
5040 	 * Concurrent #DB trap and MTF on instruction boundary. Expect MTF
5041 	 * VM-exit with populated 'pending debug exceptions' VMCS field.
5042 	 */
5043 	enter_guest();
5044 	skip_exit_vmcall();
5045 
5046 	enable_mtf();
5047 	enable_tf();
5048 
5049 	enter_guest();
5050 	report_mtf("OUT", (unsigned long) &test_mtf2);
5051 	pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
5052 	report(pending_dbg & DR6_BS,
5053 	       "'pending debug exceptions' field after MTF VM-exit: 0x%lx (expected 0x%lx)",
5054 	       pending_dbg, (unsigned long) DR6_BS);
5055 
5056 	disable_mtf();
5057 	disable_tf();
5058 	vmcs_write(GUEST_PENDING_DEBUG, 0);
5059 
5060 	/*
5061 	 * #GP exception takes priority over MTF. Expect MTF VM-exit with RIP
5062 	 * advanced to first instruction of #GP handler.
5063 	 */
5064 	enter_guest();
5065 	skip_exit_vmcall();
5066 
5067 	old_gp = handle_exception(GP_VECTOR, test_mtf_gp_handler);
5068 
5069 	enable_mtf();
5070 	enter_guest();
5071 	report_mtf("MOV CR3", (unsigned long) get_idt_addr(&boot_idt[GP_VECTOR]));
5072 	disable_mtf();
5073 
5074 	/*
5075 	 * Concurrent MTF and privileged software exception (i.e. ICEBP/INT1).
5076 	 * MTF should follow the delivery of #DB trap, though the SDM doesn't
5077 	 * provide clear indication of the relative priority.
5078 	 */
5079 	enter_guest();
5080 	skip_exit_vmcall();
5081 
5082 	handle_exception(GP_VECTOR, old_gp);
5083 	old_db = handle_exception(DB_VECTOR, test_mtf_db_handler);
5084 
5085 	enable_mtf();
5086 	enter_guest();
5087 	report_mtf("INT1", (unsigned long) get_idt_addr(&boot_idt[DB_VECTOR]));
5088 	disable_mtf();
5089 
5090 	enter_guest();
5091 	skip_exit_vmcall();
5092 	handle_exception(DB_VECTOR, old_db);
5093 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK | INTR_TYPE_OTHER_EVENT);
5094 	enter_guest();
5095 	report_mtf("injected MTF", (unsigned long) &test_mtf4);
5096 	enter_guest();
5097 }
5098 
5099 extern char vmx_mtf_pdpte_guest_begin;
5100 extern char vmx_mtf_pdpte_guest_end;
5101 
5102 asm("vmx_mtf_pdpte_guest_begin:\n\t"
5103     "mov %cr0, %rax\n\t"    /* save CR0 with PG=1                 */
5104     "vmcall\n\t"            /* on return from this CR0.PG=0       */
5105     "mov %rax, %cr0\n\t"    /* restore CR0.PG=1 to enter PAE mode */
5106     "vmcall\n\t"
5107     "retq\n\t"
5108     "vmx_mtf_pdpte_guest_end:");
5109 
5110 static void vmx_mtf_pdpte_test(void)
5111 {
5112 	void *test_mtf_pdpte_guest;
5113 	pteval_t *pdpt;
5114 	u32 guest_ar_cs;
5115 	u64 guest_efer;
5116 	pteval_t *pte;
5117 	u64 guest_cr0;
5118 	u64 guest_cr3;
5119 	u64 guest_cr4;
5120 	u64 ent_ctls;
5121 	int i;
5122 
5123 	if (setup_ept(false))
5124 		return;
5125 
5126 	if (!(ctrl_cpu_rev[0].clr & CPU_MTF)) {
5127 		report_skip("%s : \"Monitor trap flag\" exec control not supported", __func__);
5128 		return;
5129 	}
5130 
5131 	if (!(ctrl_cpu_rev[1].clr & CPU_URG)) {
5132 		report_skip("%s : \"Unrestricted guest\" exec control not supported", __func__);
5133 		return;
5134 	}
5135 
5136 	vmcs_write(EXC_BITMAP, ~0);
5137 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | CPU_URG);
5138 
5139 	/*
5140 	 * Copy the guest code to an identity-mapped page.
5141 	 */
5142 	test_mtf_pdpte_guest = alloc_page();
5143 	memcpy(test_mtf_pdpte_guest, &vmx_mtf_pdpte_guest_begin,
5144 	       &vmx_mtf_pdpte_guest_end - &vmx_mtf_pdpte_guest_begin);
5145 
5146 	test_set_guest(test_mtf_pdpte_guest);
5147 
5148 	enter_guest();
5149 	skip_exit_vmcall();
5150 
5151 	/*
5152 	 * Put the guest in non-paged 32-bit protected mode, ready to enter
5153 	 * PAE mode when CR0.PG is set. CR4.PAE will already have been set
5154 	 * when the guest started out in long mode.
5155 	 */
5156 	ent_ctls = vmcs_read(ENT_CONTROLS);
5157 	vmcs_write(ENT_CONTROLS, ent_ctls & ~ENT_GUEST_64);
5158 
5159 	guest_efer = vmcs_read(GUEST_EFER);
5160 	vmcs_write(GUEST_EFER, guest_efer & ~(EFER_LMA | EFER_LME));
5161 
5162 	/*
5163 	 * Set CS access rights bits for 32-bit protected mode:
5164 	 * 3:0    B execute/read/accessed
5165 	 * 4      1 code or data
5166 	 * 6:5    0 descriptor privilege level
5167 	 * 7      1 present
5168 	 * 11:8   0 reserved
5169 	 * 12     0 available for use by system software
5170 	 * 13     0 64 bit mode not active
5171 	 * 14     1 default operation size 32-bit segment
5172 	 * 15     1 page granularity: segment limit in 4K units
5173 	 * 16     0 segment usable
5174 	 * 31:17  0 reserved
5175 	 */
5176 	guest_ar_cs = vmcs_read(GUEST_AR_CS);
5177 	vmcs_write(GUEST_AR_CS, 0xc09b);
5178 
5179 	guest_cr0 = vmcs_read(GUEST_CR0);
5180 	vmcs_write(GUEST_CR0, guest_cr0 & ~X86_CR0_PG);
5181 
5182 	guest_cr4 = vmcs_read(GUEST_CR4);
5183 	vmcs_write(GUEST_CR4, guest_cr4 & ~X86_CR4_PCIDE);
5184 
5185 	guest_cr3 = vmcs_read(GUEST_CR3);
5186 
5187 	/*
5188 	 * Turn the 4-level page table into a PAE page table by following the 0th
5189 	 * PML4 entry to a PDPT page, and grab the first four PDPTEs from that
5190 	 * page.
5191 	 *
5192 	 * Why does this work?
5193 	 *
5194 	 * PAE uses 32-bit addressing which implies:
5195 	 * Bits 11:0   page offset
5196 	 * Bits 20:12  entry into 512-entry page table
5197 	 * Bits 29:21  entry into a 512-entry directory table
5198 	 * Bits 31:30  entry into the page directory pointer table.
5199 	 * Bits 63:32  zero
5200 	 *
5201 	 * As only 2 bits are needed to select the PDPTEs for the entire
5202 	 * 32-bit address space, take the first 4 PDPTEs in the level 3 page
5203 	 * directory pointer table. It doesn't matter which of these PDPTEs
5204 	 * are present because they must cover the guest code given that it
5205 	 * has already run successfully.
5206 	 *
5207 	 * Get a pointer to PTE for GVA=0 in the page directory pointer table
5208 	 */
5209 	pte = get_pte_level(
5210             (pgd_t *)phys_to_virt(guest_cr3 & ~X86_CR3_PCID_MASK), 0,
5211             PDPT_LEVEL);
5212 
5213 	/*
5214 	 * Need some memory for the 4-entry PAE page directory pointer
5215 	 * table. Use the end of the identity-mapped page where the guest code
5216 	 * is stored. There is definitely space as the guest code is only a
5217 	 * few bytes.
5218 	 */
5219 	pdpt = test_mtf_pdpte_guest + PAGE_SIZE - 4 * sizeof(pteval_t);
5220 
5221 	/*
5222 	 * Copy the first four PDPTEs into the PAE page table with reserved
5223 	 * bits cleared. Note that permission bits from the PML4E and PDPTE
5224 	 * are not propagated.
5225 	 */
5226 	for (i = 0; i < 4; i++) {
5227 		TEST_ASSERT_EQ_MSG(0, (pte[i] & PDPTE64_RSVD_MASK),
5228 				   "PDPTE has invalid reserved bits");
5229 		TEST_ASSERT_EQ_MSG(0, (pte[i] & PDPTE64_PAGE_SIZE_MASK),
5230 				   "Cannot use 1GB super pages for PAE");
5231 		pdpt[i] = pte[i] & ~(PAE_PDPTE_RSVD_MASK);
5232 	}
5233 	vmcs_write(GUEST_CR3, virt_to_phys(pdpt));
5234 
5235 	enable_mtf();
5236 	enter_guest();
5237 	assert_exit_reason(VMX_MTF);
5238 	disable_mtf();
5239 
5240 	/*
5241 	 * The four PDPTEs should have been loaded into the VMCS when
5242 	 * the guest set CR0.PG to enter PAE mode.
5243 	 */
5244 	for (i = 0; i < 4; i++) {
5245 		u64 pdpte = vmcs_read(GUEST_PDPTE + 2 * i);
5246 
5247 		report(pdpte == pdpt[i], "PDPTE%d is 0x%lx (expected 0x%lx)",
5248 		       i, pdpte, pdpt[i]);
5249 	}
5250 
5251 	/*
5252 	 * Now, try to enter the guest in PAE mode. If the PDPTEs in the
5253 	 * vmcs are wrong, this will fail.
5254 	 */
5255 	enter_guest();
5256 	skip_exit_vmcall();
5257 
5258 	/*
5259 	 * Return guest to 64-bit mode and wrap up.
5260 	 */
5261 	vmcs_write(ENT_CONTROLS, ent_ctls);
5262 	vmcs_write(GUEST_EFER, guest_efer);
5263 	vmcs_write(GUEST_AR_CS, guest_ar_cs);
5264 	vmcs_write(GUEST_CR0, guest_cr0);
5265 	vmcs_write(GUEST_CR4, guest_cr4);
5266 	vmcs_write(GUEST_CR3, guest_cr3);
5267 
5268 	enter_guest();
5269 }
5270 
5271 /*
5272  * Tests for VM-execution control fields
5273  */
5274 static void test_vm_execution_ctls(void)
5275 {
5276 	test_pin_based_ctls();
5277 	test_primary_processor_based_ctls();
5278 	test_secondary_processor_based_ctls();
5279 	test_cr3_targets();
5280 	test_io_bitmaps();
5281 	test_msr_bitmap();
5282 	test_apic_ctls();
5283 	test_tpr_threshold();
5284 	test_nmi_ctrls();
5285 	test_pml();
5286 	test_vpid();
5287 	test_ept_eptp();
5288 	test_vmx_preemption_timer();
5289 }
5290 
5291  /*
5292   * The following checks are performed for the VM-entry MSR-load address if
5293   * the VM-entry MSR-load count field is non-zero:
5294   *
5295   *    - The lower 4 bits of the VM-entry MSR-load address must be 0.
5296   *      The address should not set any bits beyond the processor's
5297   *      physical-address width.
5298   *
5299   *    - The address of the last byte in the VM-entry MSR-load area
5300   *      should not set any bits beyond the processor's physical-address
5301   *      width. The address of this last byte is VM-entry MSR-load address
5302   *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5303   *      uses more bits than the processor's physical-address width.)
5304   *
5305   *
5306   *  [Intel SDM]
5307   */
5308 static void test_entry_msr_load(void)
5309 {
5310 	entry_msr_load = alloc_page();
5311 	u64 tmp;
5312 	u32 entry_msr_ld_cnt = 1;
5313 	int i;
5314 	u32 addr_len = 64;
5315 
5316 	vmcs_write(ENT_MSR_LD_CNT, entry_msr_ld_cnt);
5317 
5318 	/* Check first 4 bits of VM-entry MSR-load address */
5319 	for (i = 0; i < 4; i++) {
5320 		tmp = (u64)entry_msr_load | 1ull << i;
5321 		vmcs_write(ENTER_MSR_LD_ADDR, tmp);
5322 		report_prefix_pushf("VM-entry MSR-load addr [4:0] %lx",
5323 				    tmp & 0xf);
5324 		test_vmx_invalid_controls();
5325 		report_prefix_pop();
5326 	}
5327 
5328 	if (basic_msr.val & (1ul << 48))
5329 		addr_len = 32;
5330 
5331 	test_vmcs_addr_values("VM-entry-MSR-load address",
5332 				ENTER_MSR_LD_ADDR, 16, false, false,
5333 				4, addr_len - 1);
5334 
5335 	/*
5336 	 * Check last byte of VM-entry MSR-load address
5337 	 */
5338 	entry_msr_load = (struct vmx_msr_entry *)((u64)entry_msr_load & ~0xf);
5339 
5340 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5341 							i < 64; i++) {
5342 		tmp = ((u64)entry_msr_load + entry_msr_ld_cnt * 16 - 1) |
5343 			1ul << i;
5344 		vmcs_write(ENTER_MSR_LD_ADDR,
5345 			   tmp - (entry_msr_ld_cnt * 16 - 1));
5346 		test_vmx_invalid_controls();
5347 	}
5348 
5349 	vmcs_write(ENT_MSR_LD_CNT, 2);
5350 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5351 	test_vmx_invalid_controls();
5352 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5353 	test_vmx_valid_controls();
5354 	vmcs_write(ENTER_MSR_LD_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5355 	test_vmx_valid_controls();
5356 }
5357 
5358 static struct vmx_state_area_test_data {
5359 	u32 msr;
5360 	u64 exp;
5361 	bool enabled;
5362 } vmx_state_area_test_data;
5363 
5364 static void guest_state_test_main(void)
5365 {
5366 	u64 obs;
5367 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
5368 
5369 	while (1) {
5370 		if (vmx_get_test_stage() == 2)
5371 			break;
5372 
5373 		if (data->enabled) {
5374 			obs = rdmsr(data->msr);
5375 			report(data->exp == obs,
5376 			       "Guest state is 0x%lx (expected 0x%lx)",
5377 			       obs, data->exp);
5378 		}
5379 
5380 		vmcall();
5381 	}
5382 
5383 	asm volatile("fnop");
5384 }
5385 
5386 static void test_guest_state(const char *test, bool xfail, u64 field,
5387 			     const char * field_name)
5388 {
5389 	struct vmentry_result result;
5390 	u8 abort_flags;
5391 
5392 	abort_flags = ABORT_ON_EARLY_VMENTRY_FAIL;
5393 	if (!xfail)
5394 		abort_flags = ABORT_ON_INVALID_GUEST_STATE;
5395 
5396 	__enter_guest(abort_flags, &result);
5397 
5398 	report(result.exit_reason.failed_vmentry == xfail &&
5399 	       ((xfail && result.exit_reason.basic == VMX_FAIL_STATE) ||
5400 	        (!xfail && result.exit_reason.basic == VMX_VMCALL)) &&
5401 		(!xfail || vmcs_read(EXI_QUALIFICATION) == ENTRY_FAIL_DEFAULT),
5402 	        "%s, %s = %lx", test, field_name, field);
5403 
5404 	if (!result.exit_reason.failed_vmentry)
5405 		skip_exit_insn();
5406 }
5407 
5408 /*
5409  * Tests for VM-entry control fields
5410  */
5411 static void test_vm_entry_ctls(void)
5412 {
5413 	test_invalid_event_injection();
5414 	test_entry_msr_load();
5415 }
5416 
5417 /*
5418  * The following checks are performed for the VM-exit MSR-store address if
5419  * the VM-exit MSR-store count field is non-zero:
5420  *
5421  *    - The lower 4 bits of the VM-exit MSR-store address must be 0.
5422  *      The address should not set any bits beyond the processor's
5423  *      physical-address width.
5424  *
5425  *    - The address of the last byte in the VM-exit MSR-store area
5426  *      should not set any bits beyond the processor's physical-address
5427  *      width. The address of this last byte is VM-exit MSR-store address
5428  *      + (MSR count * 16) - 1. (The arithmetic used for the computation
5429  *      uses more bits than the processor's physical-address width.)
5430  *
5431  * If IA32_VMX_BASIC[48] is read as 1, neither address should set any bits
5432  * in the range 63:32.
5433  *
5434  *  [Intel SDM]
5435  */
5436 static void test_exit_msr_store(void)
5437 {
5438 	exit_msr_store = alloc_page();
5439 	u64 tmp;
5440 	u32 exit_msr_st_cnt = 1;
5441 	int i;
5442 	u32 addr_len = 64;
5443 
5444 	vmcs_write(EXI_MSR_ST_CNT, exit_msr_st_cnt);
5445 
5446 	/* Check first 4 bits of VM-exit MSR-store address */
5447 	for (i = 0; i < 4; i++) {
5448 		tmp = (u64)exit_msr_store | 1ull << i;
5449 		vmcs_write(EXIT_MSR_ST_ADDR, tmp);
5450 		report_prefix_pushf("VM-exit MSR-store addr [4:0] %lx",
5451 				    tmp & 0xf);
5452 		test_vmx_invalid_controls();
5453 		report_prefix_pop();
5454 	}
5455 
5456 	if (basic_msr.val & (1ul << 48))
5457 		addr_len = 32;
5458 
5459 	test_vmcs_addr_values("VM-exit-MSR-store address",
5460 				EXIT_MSR_ST_ADDR, 16, false, false,
5461 				4, addr_len - 1);
5462 
5463 	/*
5464 	 * Check last byte of VM-exit MSR-store address
5465 	 */
5466 	exit_msr_store = (struct vmx_msr_entry *)((u64)exit_msr_store & ~0xf);
5467 
5468 	for (i = (addr_len == 64 ? cpuid_maxphyaddr(): addr_len);
5469 							i < 64; i++) {
5470 		tmp = ((u64)exit_msr_store + exit_msr_st_cnt * 16 - 1) |
5471 			1ul << i;
5472 		vmcs_write(EXIT_MSR_ST_ADDR,
5473 			   tmp - (exit_msr_st_cnt * 16 - 1));
5474 		test_vmx_invalid_controls();
5475 	}
5476 
5477 	vmcs_write(EXI_MSR_ST_CNT, 2);
5478 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 16);
5479 	test_vmx_invalid_controls();
5480 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 32);
5481 	test_vmx_valid_controls();
5482 	vmcs_write(EXIT_MSR_ST_ADDR, (1ULL << cpuid_maxphyaddr()) - 48);
5483 	test_vmx_valid_controls();
5484 }
5485 
5486 /*
5487  * Tests for VM-exit controls
5488  */
5489 static void test_vm_exit_ctls(void)
5490 {
5491 	test_exit_msr_store();
5492 }
5493 
5494 /*
5495  * Check that the virtual CPU checks all of the VMX controls as
5496  * documented in the Intel SDM.
5497  */
5498 static void vmx_controls_test(void)
5499 {
5500 	/*
5501 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
5502 	 * fail due to invalid guest state, should we make it that
5503 	 * far.
5504 	 */
5505 	vmcs_write(GUEST_RFLAGS, 0);
5506 
5507 	test_vm_execution_ctls();
5508 	test_vm_exit_ctls();
5509 	test_vm_entry_ctls();
5510 }
5511 
5512 struct apic_reg_virt_config {
5513 	bool apic_register_virtualization;
5514 	bool use_tpr_shadow;
5515 	bool virtualize_apic_accesses;
5516 	bool virtualize_x2apic_mode;
5517 	bool activate_secondary_controls;
5518 };
5519 
5520 struct apic_reg_test {
5521 	const char *name;
5522 	struct apic_reg_virt_config apic_reg_virt_config;
5523 };
5524 
5525 struct apic_reg_virt_expectation {
5526 	enum Reason rd_exit_reason;
5527 	enum Reason wr_exit_reason;
5528 	u32 val;
5529 	u32 (*virt_fn)(u32);
5530 
5531 	/*
5532 	 * If false, accessing the APIC access address from L2 is treated as a
5533 	 * normal memory operation, rather than triggering virtualization.
5534 	 */
5535 	bool virtualize_apic_accesses;
5536 };
5537 
5538 static u32 apic_virt_identity(u32 val)
5539 {
5540 	return val;
5541 }
5542 
5543 static u32 apic_virt_nibble1(u32 val)
5544 {
5545 	return val & 0xf0;
5546 }
5547 
5548 static u32 apic_virt_byte3(u32 val)
5549 {
5550 	return val & (0xff << 24);
5551 }
5552 
5553 static bool apic_reg_virt_exit_expectation(
5554 	u32 reg, struct apic_reg_virt_config *config,
5555 	struct apic_reg_virt_expectation *expectation)
5556 {
5557 	/* Good configs, where some L2 APIC accesses are virtualized. */
5558 	bool virtualize_apic_accesses_only =
5559 		config->virtualize_apic_accesses &&
5560 		!config->use_tpr_shadow &&
5561 		!config->apic_register_virtualization &&
5562 		!config->virtualize_x2apic_mode &&
5563 		config->activate_secondary_controls;
5564 	bool virtualize_apic_accesses_and_use_tpr_shadow =
5565 		config->virtualize_apic_accesses &&
5566 		config->use_tpr_shadow &&
5567 		!config->apic_register_virtualization &&
5568 		!config->virtualize_x2apic_mode &&
5569 		config->activate_secondary_controls;
5570 	bool apic_register_virtualization =
5571 		config->virtualize_apic_accesses &&
5572 		config->use_tpr_shadow &&
5573 		config->apic_register_virtualization &&
5574 		!config->virtualize_x2apic_mode &&
5575 		config->activate_secondary_controls;
5576 
5577 	expectation->val = MAGIC_VAL_1;
5578 	expectation->virt_fn = apic_virt_identity;
5579 	expectation->virtualize_apic_accesses =
5580 		config->virtualize_apic_accesses &&
5581 		config->activate_secondary_controls;
5582 	if (virtualize_apic_accesses_only) {
5583 		expectation->rd_exit_reason = VMX_APIC_ACCESS;
5584 		expectation->wr_exit_reason = VMX_APIC_ACCESS;
5585 	} else if (virtualize_apic_accesses_and_use_tpr_shadow) {
5586 		switch (reg) {
5587 		case APIC_TASKPRI:
5588 			expectation->rd_exit_reason = VMX_VMCALL;
5589 			expectation->wr_exit_reason = VMX_VMCALL;
5590 			expectation->virt_fn = apic_virt_nibble1;
5591 			break;
5592 		default:
5593 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5594 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5595 		}
5596 	} else if (apic_register_virtualization) {
5597 		expectation->rd_exit_reason = VMX_VMCALL;
5598 
5599 		switch (reg) {
5600 		case APIC_ID:
5601 		case APIC_EOI:
5602 		case APIC_LDR:
5603 		case APIC_DFR:
5604 		case APIC_SPIV:
5605 		case APIC_ESR:
5606 		case APIC_ICR:
5607 		case APIC_LVTT:
5608 		case APIC_LVTTHMR:
5609 		case APIC_LVTPC:
5610 		case APIC_LVT0:
5611 		case APIC_LVT1:
5612 		case APIC_LVTERR:
5613 		case APIC_TMICT:
5614 		case APIC_TDCR:
5615 			expectation->wr_exit_reason = VMX_APIC_WRITE;
5616 			break;
5617 		case APIC_LVR:
5618 		case APIC_ISR ... APIC_ISR + 0x70:
5619 		case APIC_TMR ... APIC_TMR + 0x70:
5620 		case APIC_IRR ... APIC_IRR + 0x70:
5621 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5622 			break;
5623 		case APIC_TASKPRI:
5624 			expectation->wr_exit_reason = VMX_VMCALL;
5625 			expectation->virt_fn = apic_virt_nibble1;
5626 			break;
5627 		case APIC_ICR2:
5628 			expectation->wr_exit_reason = VMX_VMCALL;
5629 			expectation->virt_fn = apic_virt_byte3;
5630 			break;
5631 		default:
5632 			expectation->rd_exit_reason = VMX_APIC_ACCESS;
5633 			expectation->wr_exit_reason = VMX_APIC_ACCESS;
5634 		}
5635 	} else if (!expectation->virtualize_apic_accesses) {
5636 		/*
5637 		 * No APIC registers are directly virtualized. This includes
5638 		 * VTPR, which can be virtualized through MOV to/from CR8 via
5639 		 * the use TPR shadow control, but not through directly
5640 		 * accessing VTPR.
5641 		 */
5642 		expectation->rd_exit_reason = VMX_VMCALL;
5643 		expectation->wr_exit_reason = VMX_VMCALL;
5644 	} else {
5645 		printf("Cannot parse APIC register virtualization config:\n"
5646 		       "\tvirtualize_apic_accesses: %d\n"
5647 		       "\tuse_tpr_shadow: %d\n"
5648 		       "\tapic_register_virtualization: %d\n"
5649 		       "\tvirtualize_x2apic_mode: %d\n"
5650 		       "\tactivate_secondary_controls: %d\n",
5651 		       config->virtualize_apic_accesses,
5652 		       config->use_tpr_shadow,
5653 		       config->apic_register_virtualization,
5654 		       config->virtualize_x2apic_mode,
5655 		       config->activate_secondary_controls);
5656 
5657 		return false;
5658 	}
5659 
5660 	return true;
5661 }
5662 
5663 struct apic_reg_test apic_reg_tests[] = {
5664 	/* Good configs, where some L2 APIC accesses are virtualized. */
5665 	{
5666 		.name = "Virtualize APIC accesses",
5667 		.apic_reg_virt_config = {
5668 			.virtualize_apic_accesses = true,
5669 			.use_tpr_shadow = false,
5670 			.apic_register_virtualization = false,
5671 			.virtualize_x2apic_mode = false,
5672 			.activate_secondary_controls = true,
5673 		},
5674 	},
5675 	{
5676 		.name = "Virtualize APIC accesses + Use TPR shadow",
5677 		.apic_reg_virt_config = {
5678 			.virtualize_apic_accesses = true,
5679 			.use_tpr_shadow = true,
5680 			.apic_register_virtualization = false,
5681 			.virtualize_x2apic_mode = false,
5682 			.activate_secondary_controls = true,
5683 		},
5684 	},
5685 	{
5686 		.name = "APIC-register virtualization",
5687 		.apic_reg_virt_config = {
5688 			.virtualize_apic_accesses = true,
5689 			.use_tpr_shadow = true,
5690 			.apic_register_virtualization = true,
5691 			.virtualize_x2apic_mode = false,
5692 			.activate_secondary_controls = true,
5693 		},
5694 	},
5695 
5696 	/*
5697 	 * Test that the secondary processor-based VM-execution controls are
5698 	 * correctly ignored when "activate secondary controls" is disabled.
5699 	 */
5700 	{
5701 		.name = "Activate secondary controls off",
5702 		.apic_reg_virt_config = {
5703 			.virtualize_apic_accesses = true,
5704 			.use_tpr_shadow = false,
5705 			.apic_register_virtualization = true,
5706 			.virtualize_x2apic_mode = true,
5707 			.activate_secondary_controls = false,
5708 		},
5709 	},
5710 	{
5711 		.name = "Activate secondary controls off + Use TPR shadow",
5712 		.apic_reg_virt_config = {
5713 			.virtualize_apic_accesses = true,
5714 			.use_tpr_shadow = true,
5715 			.apic_register_virtualization = true,
5716 			.virtualize_x2apic_mode = true,
5717 			.activate_secondary_controls = false,
5718 		},
5719 	},
5720 
5721 	/*
5722 	 * Test that the APIC access address is treated like an arbitrary memory
5723 	 * address when "virtualize APIC accesses" is disabled.
5724 	 */
5725 	{
5726 		.name = "Virtualize APIC accesses off + Use TPR shadow",
5727 		.apic_reg_virt_config = {
5728 			.virtualize_apic_accesses = false,
5729 			.use_tpr_shadow = true,
5730 			.apic_register_virtualization = true,
5731 			.virtualize_x2apic_mode = true,
5732 			.activate_secondary_controls = true,
5733 		},
5734 	},
5735 
5736 	/*
5737 	 * Test that VM entry fails due to invalid controls when
5738 	 * "APIC-register virtualization" is enabled while "use TPR shadow" is
5739 	 * disabled.
5740 	 */
5741 	{
5742 		.name = "APIC-register virtualization + Use TPR shadow off",
5743 		.apic_reg_virt_config = {
5744 			.virtualize_apic_accesses = true,
5745 			.use_tpr_shadow = false,
5746 			.apic_register_virtualization = true,
5747 			.virtualize_x2apic_mode = false,
5748 			.activate_secondary_controls = true,
5749 		},
5750 	},
5751 
5752 	/*
5753 	 * Test that VM entry fails due to invalid controls when
5754 	 * "Virtualize x2APIC mode" is enabled while "use TPR shadow" is
5755 	 * disabled.
5756 	 */
5757 	{
5758 		.name = "Virtualize x2APIC mode + Use TPR shadow off",
5759 		.apic_reg_virt_config = {
5760 			.virtualize_apic_accesses = false,
5761 			.use_tpr_shadow = false,
5762 			.apic_register_virtualization = false,
5763 			.virtualize_x2apic_mode = true,
5764 			.activate_secondary_controls = true,
5765 		},
5766 	},
5767 	{
5768 		.name = "Virtualize x2APIC mode + Use TPR shadow off v2",
5769 		.apic_reg_virt_config = {
5770 			.virtualize_apic_accesses = false,
5771 			.use_tpr_shadow = false,
5772 			.apic_register_virtualization = true,
5773 			.virtualize_x2apic_mode = true,
5774 			.activate_secondary_controls = true,
5775 		},
5776 	},
5777 
5778 	/*
5779 	 * Test that VM entry fails due to invalid controls when
5780 	 * "virtualize x2APIC mode" is enabled while "virtualize APIC accesses"
5781 	 * is enabled.
5782 	 */
5783 	{
5784 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses",
5785 		.apic_reg_virt_config = {
5786 			.virtualize_apic_accesses = true,
5787 			.use_tpr_shadow = true,
5788 			.apic_register_virtualization = false,
5789 			.virtualize_x2apic_mode = true,
5790 			.activate_secondary_controls = true,
5791 		},
5792 	},
5793 	{
5794 		.name = "Virtualize x2APIC mode + Virtualize APIC accesses v2",
5795 		.apic_reg_virt_config = {
5796 			.virtualize_apic_accesses = true,
5797 			.use_tpr_shadow = true,
5798 			.apic_register_virtualization = true,
5799 			.virtualize_x2apic_mode = true,
5800 			.activate_secondary_controls = true,
5801 		},
5802 	},
5803 };
5804 
5805 enum Apic_op {
5806 	APIC_OP_XAPIC_RD,
5807 	APIC_OP_XAPIC_WR,
5808 	TERMINATE,
5809 };
5810 
5811 static u32 vmx_xapic_read(u32 *apic_access_address, u32 reg)
5812 {
5813 	return *(volatile u32 *)((uintptr_t)apic_access_address + reg);
5814 }
5815 
5816 static void vmx_xapic_write(u32 *apic_access_address, u32 reg, u32 val)
5817 {
5818 	*(volatile u32 *)((uintptr_t)apic_access_address + reg) = val;
5819 }
5820 
5821 struct apic_reg_virt_guest_args {
5822 	enum Apic_op op;
5823 	u32 *apic_access_address;
5824 	u32 reg;
5825 	u32 val;
5826 	bool check_rd;
5827 	u32 (*virt_fn)(u32);
5828 } apic_reg_virt_guest_args;
5829 
5830 static void apic_reg_virt_guest(void)
5831 {
5832 	volatile struct apic_reg_virt_guest_args *args =
5833 		&apic_reg_virt_guest_args;
5834 
5835 	for (;;) {
5836 		enum Apic_op op = args->op;
5837 		u32 *apic_access_address = args->apic_access_address;
5838 		u32 reg = args->reg;
5839 		u32 val = args->val;
5840 		bool check_rd = args->check_rd;
5841 		u32 (*virt_fn)(u32) = args->virt_fn;
5842 
5843 		if (op == TERMINATE)
5844 			break;
5845 
5846 		if (op == APIC_OP_XAPIC_RD) {
5847 			u32 ret = vmx_xapic_read(apic_access_address, reg);
5848 
5849 			if (check_rd) {
5850 				u32 want = virt_fn(val);
5851 				u32 got = virt_fn(ret);
5852 
5853 				report(got == want,
5854 				       "read 0x%x, expected 0x%x.", got, want);
5855 			}
5856 		} else if (op == APIC_OP_XAPIC_WR) {
5857 			vmx_xapic_write(apic_access_address, reg, val);
5858 		}
5859 
5860 		/*
5861 		 * The L1 should always execute a vmcall after it's done testing
5862 		 * an individual APIC operation. This helps to validate that the
5863 		 * L1 and L2 are in sync with each other, as expected.
5864 		 */
5865 		vmcall();
5866 	}
5867 }
5868 
5869 static void test_xapic_rd(
5870 	u32 reg, struct apic_reg_virt_expectation *expectation,
5871 	u32 *apic_access_address, u32 *virtual_apic_page)
5872 {
5873 	u32 val = expectation->val;
5874 	u32 exit_reason_want = expectation->rd_exit_reason;
5875 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5876 
5877 	report_prefix_pushf("xapic - reading 0x%03x", reg);
5878 
5879 	/* Configure guest to do an xapic read */
5880 	args->op = APIC_OP_XAPIC_RD;
5881 	args->apic_access_address = apic_access_address;
5882 	args->reg = reg;
5883 	args->val = val;
5884 	args->check_rd = exit_reason_want == VMX_VMCALL;
5885 	args->virt_fn = expectation->virt_fn;
5886 
5887 	/* Setup virtual APIC page */
5888 	if (!expectation->virtualize_apic_accesses) {
5889 		apic_access_address[apic_reg_index(reg)] = val;
5890 		virtual_apic_page[apic_reg_index(reg)] = 0;
5891 	} else if (exit_reason_want == VMX_VMCALL) {
5892 		apic_access_address[apic_reg_index(reg)] = 0;
5893 		virtual_apic_page[apic_reg_index(reg)] = val;
5894 	}
5895 
5896 	/* Enter guest */
5897 	enter_guest();
5898 
5899 	/*
5900 	 * Validate the behavior and
5901 	 * pass a magic value back to the guest.
5902 	 */
5903 	if (exit_reason_want == VMX_APIC_ACCESS) {
5904 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5905 
5906 		assert_exit_reason(exit_reason_want);
5907 		report(apic_page_offset == reg,
5908 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5909 		       apic_page_offset, reg);
5910 		skip_exit_insn();
5911 
5912 		/* Reenter guest so it can consume/check rcx and exit again. */
5913 		enter_guest();
5914 	} else if (exit_reason_want != VMX_VMCALL) {
5915 		report_fail("Oops, bad exit expectation: %u.", exit_reason_want);
5916 	}
5917 
5918 	skip_exit_vmcall();
5919 	report_prefix_pop();
5920 }
5921 
5922 static void test_xapic_wr(
5923 	u32 reg, struct apic_reg_virt_expectation *expectation,
5924 	u32 *apic_access_address, u32 *virtual_apic_page)
5925 {
5926 	u32 val = expectation->val;
5927 	u32 exit_reason_want = expectation->wr_exit_reason;
5928 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
5929 	bool virtualized =
5930 		expectation->virtualize_apic_accesses &&
5931 		(exit_reason_want == VMX_APIC_WRITE ||
5932 		 exit_reason_want == VMX_VMCALL);
5933 	bool checked = false;
5934 
5935 	report_prefix_pushf("xapic - writing 0x%x to 0x%03x", val, reg);
5936 
5937 	/* Configure guest to do an xapic read */
5938 	args->op = APIC_OP_XAPIC_WR;
5939 	args->apic_access_address = apic_access_address;
5940 	args->reg = reg;
5941 	args->val = val;
5942 
5943 	/* Setup virtual APIC page */
5944 	if (virtualized || !expectation->virtualize_apic_accesses) {
5945 		apic_access_address[apic_reg_index(reg)] = 0;
5946 		virtual_apic_page[apic_reg_index(reg)] = 0;
5947 	}
5948 
5949 	/* Enter guest */
5950 	enter_guest();
5951 
5952 	/*
5953 	 * Validate the behavior and
5954 	 * pass a magic value back to the guest.
5955 	 */
5956 	if (exit_reason_want == VMX_APIC_ACCESS) {
5957 		u32 apic_page_offset = vmcs_read(EXI_QUALIFICATION) & 0xfff;
5958 
5959 		assert_exit_reason(exit_reason_want);
5960 		report(apic_page_offset == reg,
5961 		       "got APIC access exit @ page offset 0x%03x, want 0x%03x",
5962 		       apic_page_offset, reg);
5963 		skip_exit_insn();
5964 
5965 		/* Reenter guest so it can consume/check rcx and exit again. */
5966 		enter_guest();
5967 	} else if (exit_reason_want == VMX_APIC_WRITE) {
5968 		assert_exit_reason(exit_reason_want);
5969 		report(virtual_apic_page[apic_reg_index(reg)] == val,
5970 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%x",
5971 		       apic_reg_index(reg),
5972 		       virtual_apic_page[apic_reg_index(reg)], val);
5973 		checked = true;
5974 
5975 		/* Reenter guest so it can consume/check rcx and exit again. */
5976 		enter_guest();
5977 	} else if (exit_reason_want != VMX_VMCALL) {
5978 		report_fail("Oops, bad exit expectation: %u.", exit_reason_want);
5979 	}
5980 
5981 	assert_exit_reason(VMX_VMCALL);
5982 	if (virtualized && !checked) {
5983 		u32 want = expectation->virt_fn(val);
5984 		u32 got = virtual_apic_page[apic_reg_index(reg)];
5985 		got = expectation->virt_fn(got);
5986 
5987 		report(got == want, "exitless write; val is 0x%x, want 0x%x",
5988 		       got, want);
5989 	} else if (!expectation->virtualize_apic_accesses && !checked) {
5990 		u32 got = apic_access_address[apic_reg_index(reg)];
5991 
5992 		report(got == val,
5993 		       "non-virtualized write; val is 0x%x, want 0x%x", got,
5994 		       val);
5995 	} else if (!expectation->virtualize_apic_accesses && checked) {
5996 		report_fail("Non-virtualized write was prematurely checked!");
5997 	}
5998 
5999 	skip_exit_vmcall();
6000 	report_prefix_pop();
6001 }
6002 
6003 enum Config_type {
6004 	CONFIG_TYPE_GOOD,
6005 	CONFIG_TYPE_UNSUPPORTED,
6006 	CONFIG_TYPE_VMENTRY_FAILS_EARLY,
6007 };
6008 
6009 static enum Config_type configure_apic_reg_virt_test(
6010 	struct apic_reg_virt_config *apic_reg_virt_config)
6011 {
6012 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6013 	u32 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6014 	/* Configs where L2 entry fails early, due to invalid controls. */
6015 	bool use_tpr_shadow_incorrectly_off =
6016 		!apic_reg_virt_config->use_tpr_shadow &&
6017 		(apic_reg_virt_config->apic_register_virtualization ||
6018 		 apic_reg_virt_config->virtualize_x2apic_mode) &&
6019 		apic_reg_virt_config->activate_secondary_controls;
6020 	bool virtualize_apic_accesses_incorrectly_on =
6021 		apic_reg_virt_config->virtualize_apic_accesses &&
6022 		apic_reg_virt_config->virtualize_x2apic_mode &&
6023 		apic_reg_virt_config->activate_secondary_controls;
6024 	bool vmentry_fails_early =
6025 		use_tpr_shadow_incorrectly_off ||
6026 		virtualize_apic_accesses_incorrectly_on;
6027 
6028 	if (apic_reg_virt_config->activate_secondary_controls) {
6029 		if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
6030 			printf("VM-execution control \"activate secondary controls\" NOT supported.\n");
6031 			return CONFIG_TYPE_UNSUPPORTED;
6032 		}
6033 		cpu_exec_ctrl0 |= CPU_SECONDARY;
6034 	} else {
6035 		cpu_exec_ctrl0 &= ~CPU_SECONDARY;
6036 	}
6037 
6038 	if (apic_reg_virt_config->virtualize_apic_accesses) {
6039 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_APIC_ACCESSES)) {
6040 			printf("VM-execution control \"virtualize APIC accesses\" NOT supported.\n");
6041 			return CONFIG_TYPE_UNSUPPORTED;
6042 		}
6043 		cpu_exec_ctrl1 |= CPU_VIRT_APIC_ACCESSES;
6044 	} else {
6045 		cpu_exec_ctrl1 &= ~CPU_VIRT_APIC_ACCESSES;
6046 	}
6047 
6048 	if (apic_reg_virt_config->use_tpr_shadow) {
6049 		if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
6050 			printf("VM-execution control \"use TPR shadow\" NOT supported.\n");
6051 			return CONFIG_TYPE_UNSUPPORTED;
6052 		}
6053 		cpu_exec_ctrl0 |= CPU_TPR_SHADOW;
6054 	} else {
6055 		cpu_exec_ctrl0 &= ~CPU_TPR_SHADOW;
6056 	}
6057 
6058 	if (apic_reg_virt_config->apic_register_virtualization) {
6059 		if (!(ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT)) {
6060 			printf("VM-execution control \"APIC-register virtualization\" NOT supported.\n");
6061 			return CONFIG_TYPE_UNSUPPORTED;
6062 		}
6063 		cpu_exec_ctrl1 |= CPU_APIC_REG_VIRT;
6064 	} else {
6065 		cpu_exec_ctrl1 &= ~CPU_APIC_REG_VIRT;
6066 	}
6067 
6068 	if (apic_reg_virt_config->virtualize_x2apic_mode) {
6069 		if (!(ctrl_cpu_rev[1].clr & CPU_VIRT_X2APIC)) {
6070 			printf("VM-execution control \"virtualize x2APIC mode\" NOT supported.\n");
6071 			return CONFIG_TYPE_UNSUPPORTED;
6072 		}
6073 		cpu_exec_ctrl1 |= CPU_VIRT_X2APIC;
6074 	} else {
6075 		cpu_exec_ctrl1 &= ~CPU_VIRT_X2APIC;
6076 	}
6077 
6078 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6079 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6080 
6081 	if (vmentry_fails_early)
6082 		return CONFIG_TYPE_VMENTRY_FAILS_EARLY;
6083 
6084 	return CONFIG_TYPE_GOOD;
6085 }
6086 
6087 static bool cpu_has_apicv(void)
6088 {
6089 	return ((ctrl_cpu_rev[1].clr & CPU_APIC_REG_VIRT) &&
6090 		(ctrl_cpu_rev[1].clr & CPU_VINTD) &&
6091 		(ctrl_pin_rev.clr & PIN_POST_INTR));
6092 }
6093 
6094 /* Validates APIC register access across valid virtualization configurations. */
6095 static void apic_reg_virt_test(void)
6096 {
6097 	u32 *apic_access_address;
6098 	u32 *virtual_apic_page;
6099 	u64 control;
6100 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6101 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6102 	int i;
6103 	struct apic_reg_virt_guest_args *args = &apic_reg_virt_guest_args;
6104 
6105 	if (!cpu_has_apicv()) {
6106 		report_skip("%s : Not all required APICv bits supported", __func__);
6107 		return;
6108 	}
6109 
6110 	control = cpu_exec_ctrl1;
6111 	control &= ~CPU_VINTD;
6112 	vmcs_write(CPU_EXEC_CTRL1, control);
6113 
6114 	test_set_guest(apic_reg_virt_guest);
6115 
6116 	/*
6117 	 * From the SDM: The 1-setting of the "virtualize APIC accesses"
6118 	 * VM-execution is guaranteed to apply only if translations to the
6119 	 * APIC-access address use a 4-KByte page.
6120 	 */
6121 	apic_access_address = alloc_page();
6122 	force_4k_page(apic_access_address);
6123 	vmcs_write(APIC_ACCS_ADDR, virt_to_phys(apic_access_address));
6124 
6125 	virtual_apic_page = alloc_page();
6126 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
6127 
6128 	for (i = 0; i < ARRAY_SIZE(apic_reg_tests); i++) {
6129 		struct apic_reg_test *apic_reg_test = &apic_reg_tests[i];
6130 		struct apic_reg_virt_config *apic_reg_virt_config =
6131 				&apic_reg_test->apic_reg_virt_config;
6132 		enum Config_type config_type;
6133 		u32 reg;
6134 
6135 		printf("--- %s test ---\n", apic_reg_test->name);
6136 		config_type =
6137 			configure_apic_reg_virt_test(apic_reg_virt_config);
6138 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
6139 			printf("Skip because of missing features.\n");
6140 			continue;
6141 		}
6142 
6143 		if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6144 			enter_guest_with_bad_controls();
6145 			continue;
6146 		}
6147 
6148 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6149 			struct apic_reg_virt_expectation expectation = {};
6150 			bool ok;
6151 
6152 			ok = apic_reg_virt_exit_expectation(
6153 				reg, apic_reg_virt_config, &expectation);
6154 			if (!ok) {
6155 				report_fail("Malformed test.");
6156 				break;
6157 			}
6158 
6159 			test_xapic_rd(reg, &expectation, apic_access_address,
6160 				      virtual_apic_page);
6161 			test_xapic_wr(reg, &expectation, apic_access_address,
6162 				      virtual_apic_page);
6163 		}
6164 	}
6165 
6166 	/* Terminate the guest */
6167 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6168 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6169 	args->op = TERMINATE;
6170 	enter_guest();
6171 	assert_exit_reason(VMX_VMCALL);
6172 }
6173 
6174 struct virt_x2apic_mode_config {
6175 	struct apic_reg_virt_config apic_reg_virt_config;
6176 	bool virtual_interrupt_delivery;
6177 	bool use_msr_bitmaps;
6178 	bool disable_x2apic_msr_intercepts;
6179 	bool disable_x2apic;
6180 };
6181 
6182 struct virt_x2apic_mode_test_case {
6183 	const char *name;
6184 	struct virt_x2apic_mode_config virt_x2apic_mode_config;
6185 };
6186 
6187 enum Virt_x2apic_mode_behavior_type {
6188 	X2APIC_ACCESS_VIRTUALIZED,
6189 	X2APIC_ACCESS_PASSED_THROUGH,
6190 	X2APIC_ACCESS_TRIGGERS_GP,
6191 };
6192 
6193 struct virt_x2apic_mode_expectation {
6194 	enum Reason rd_exit_reason;
6195 	enum Reason wr_exit_reason;
6196 
6197 	/*
6198 	 * RDMSR and WRMSR handle 64-bit values. However, except for ICR, all of
6199 	 * the x2APIC registers are 32 bits. Notice:
6200 	 *   1. vmx_x2apic_read() clears the upper 32 bits for 32-bit registers.
6201 	 *   2. vmx_x2apic_write() expects the val arg to be well-formed.
6202 	 */
6203 	u64 rd_val;
6204 	u64 wr_val;
6205 
6206 	/*
6207 	 * Compares input to virtualized output;
6208 	 * 1st arg is pointer to return expected virtualization output.
6209 	 */
6210 	u64 (*virt_fn)(u64);
6211 
6212 	enum Virt_x2apic_mode_behavior_type rd_behavior;
6213 	enum Virt_x2apic_mode_behavior_type wr_behavior;
6214 	bool wr_only;
6215 };
6216 
6217 static u64 virt_x2apic_mode_identity(u64 val)
6218 {
6219 	return val;
6220 }
6221 
6222 static u64 virt_x2apic_mode_nibble1(u64 val)
6223 {
6224 	return val & 0xf0;
6225 }
6226 
6227 static void virt_x2apic_mode_rd_expectation(
6228 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6229 	bool apic_register_virtualization, bool virtual_interrupt_delivery,
6230 	struct virt_x2apic_mode_expectation *expectation)
6231 {
6232 	enum x2apic_reg_semantics semantics = get_x2apic_reg_semantics(reg);
6233 
6234 	expectation->rd_exit_reason = VMX_VMCALL;
6235 	expectation->virt_fn = virt_x2apic_mode_identity;
6236 	if (virt_x2apic_mode_on && apic_register_virtualization) {
6237 		expectation->rd_val = MAGIC_VAL_1;
6238 		if (reg == APIC_PROCPRI && virtual_interrupt_delivery)
6239 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6240 		else if (reg == APIC_TASKPRI)
6241 			expectation->virt_fn = virt_x2apic_mode_nibble1;
6242 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6243 	} else if (virt_x2apic_mode_on && !apic_register_virtualization &&
6244 		   reg == APIC_TASKPRI) {
6245 		expectation->rd_val = MAGIC_VAL_1;
6246 		expectation->virt_fn = virt_x2apic_mode_nibble1;
6247 		expectation->rd_behavior = X2APIC_ACCESS_VIRTUALIZED;
6248 	} else if (!disable_x2apic && (semantics & X2APIC_READABLE)) {
6249 		expectation->rd_val = apic_read(reg);
6250 		expectation->rd_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6251 	} else {
6252 		expectation->rd_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6253 	}
6254 }
6255 
6256 /*
6257  * get_x2apic_wr_val() creates an innocuous write value for an x2APIC register.
6258  *
6259  * For writable registers, get_x2apic_wr_val() deposits the write value into the
6260  * val pointer arg and returns true. For non-writable registers, val is not
6261  * modified and get_x2apic_wr_val() returns false.
6262  */
6263 static bool get_x2apic_wr_val(u32 reg, u64 *val)
6264 {
6265 	switch (reg) {
6266 	case APIC_TASKPRI:
6267 		/* Bits 31:8 are reserved. */
6268 		*val &= 0xff;
6269 		break;
6270 	case APIC_EOI:
6271 	case APIC_ESR:
6272 	case APIC_TMICT:
6273 		/*
6274 		 * EOI, ESR: WRMSR of a non-zero value causes #GP(0).
6275 		 * TMICT: A write of 0 to the initial-count register effectively
6276 		 *        stops the local APIC timer, in both one-shot and
6277 		 *        periodic mode.
6278 		 */
6279 		*val = 0;
6280 		break;
6281 	case APIC_SPIV:
6282 	case APIC_LVTT:
6283 	case APIC_LVTTHMR:
6284 	case APIC_LVTPC:
6285 	case APIC_LVT0:
6286 	case APIC_LVT1:
6287 	case APIC_LVTERR:
6288 	case APIC_TDCR:
6289 		/*
6290 		 * To avoid writing a 1 to a reserved bit or causing some other
6291 		 * unintended side effect, read the current value and use it as
6292 		 * the write value.
6293 		 */
6294 		*val = apic_read(reg);
6295 		break;
6296 	case APIC_CMCI:
6297 		if (!apic_lvt_entry_supported(6))
6298 			return false;
6299 		*val = apic_read(reg);
6300 		break;
6301 	case APIC_ICR:
6302 		*val = 0x40000 | 0xf1;
6303 		break;
6304 	case APIC_SELF_IPI:
6305 		/*
6306 		 * With special processing (i.e., virtualize x2APIC mode +
6307 		 * virtual interrupt delivery), writing zero causes an
6308 		 * APIC-write VM exit. We plan to add a test for enabling
6309 		 * "virtual-interrupt delivery" in VMCS12, and that's where we
6310 		 * will test a self IPI with special processing.
6311 		 */
6312 		*val = 0x0;
6313 		break;
6314 	default:
6315 		return false;
6316 	}
6317 
6318 	return true;
6319 }
6320 
6321 static bool special_processing_applies(u32 reg, u64 *val,
6322 				       bool virt_int_delivery)
6323 {
6324 	bool special_processing =
6325 		(reg == APIC_TASKPRI) ||
6326 		(virt_int_delivery &&
6327 		 (reg == APIC_EOI || reg == APIC_SELF_IPI));
6328 
6329 	if (special_processing) {
6330 		TEST_ASSERT(get_x2apic_wr_val(reg, val));
6331 		return true;
6332 	}
6333 
6334 	return false;
6335 }
6336 
6337 static void virt_x2apic_mode_wr_expectation(
6338 	u32 reg, bool virt_x2apic_mode_on, bool disable_x2apic,
6339 	bool virt_int_delivery,
6340 	struct virt_x2apic_mode_expectation *expectation)
6341 {
6342 	expectation->wr_exit_reason = VMX_VMCALL;
6343 	expectation->wr_val = MAGIC_VAL_1;
6344 	expectation->wr_only = false;
6345 
6346 	if (virt_x2apic_mode_on &&
6347 	    special_processing_applies(reg, &expectation->wr_val,
6348 				       virt_int_delivery)) {
6349 		expectation->wr_behavior = X2APIC_ACCESS_VIRTUALIZED;
6350 		if (reg == APIC_SELF_IPI)
6351 			expectation->wr_exit_reason = VMX_APIC_WRITE;
6352 	} else if (!disable_x2apic &&
6353 		   get_x2apic_wr_val(reg, &expectation->wr_val)) {
6354 		expectation->wr_behavior = X2APIC_ACCESS_PASSED_THROUGH;
6355 		if (reg == APIC_EOI || reg == APIC_SELF_IPI)
6356 			expectation->wr_only = true;
6357 		if (reg == APIC_ICR)
6358 			expectation->wr_exit_reason = VMX_EXTINT;
6359 	} else {
6360 		expectation->wr_behavior = X2APIC_ACCESS_TRIGGERS_GP;
6361 		/*
6362 		 * Writing 1 to a reserved bit triggers a #GP.
6363 		 * Thus, set the write value to 0, which seems
6364 		 * the most likely to detect a missed #GP.
6365 		 */
6366 		expectation->wr_val = 0;
6367 	}
6368 }
6369 
6370 static void virt_x2apic_mode_exit_expectation(
6371 	u32 reg, struct virt_x2apic_mode_config *config,
6372 	struct virt_x2apic_mode_expectation *expectation)
6373 {
6374 	struct apic_reg_virt_config *base_config =
6375 		&config->apic_reg_virt_config;
6376 	bool virt_x2apic_mode_on =
6377 		base_config->virtualize_x2apic_mode &&
6378 		config->use_msr_bitmaps &&
6379 		config->disable_x2apic_msr_intercepts &&
6380 		base_config->activate_secondary_controls;
6381 
6382 	virt_x2apic_mode_wr_expectation(
6383 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6384 		config->virtual_interrupt_delivery, expectation);
6385 	virt_x2apic_mode_rd_expectation(
6386 		reg, virt_x2apic_mode_on, config->disable_x2apic,
6387 		base_config->apic_register_virtualization,
6388 		config->virtual_interrupt_delivery, expectation);
6389 }
6390 
6391 struct virt_x2apic_mode_test_case virt_x2apic_mode_tests[] = {
6392 	/*
6393 	 * Baseline "virtualize x2APIC mode" configuration:
6394 	 *   - virtualize x2APIC mode
6395 	 *   - virtual-interrupt delivery
6396 	 *   - APIC-register virtualization
6397 	 *   - x2APIC MSR intercepts disabled
6398 	 *
6399 	 * Reads come from virtual APIC page, special processing applies to
6400 	 * VTPR, EOI, and SELF IPI, and all other writes pass through to L1
6401 	 * APIC.
6402 	 */
6403 	{
6404 		.name = "Baseline",
6405 		.virt_x2apic_mode_config = {
6406 			.virtual_interrupt_delivery = true,
6407 			.use_msr_bitmaps = true,
6408 			.disable_x2apic_msr_intercepts = true,
6409 			.disable_x2apic = false,
6410 			.apic_reg_virt_config = {
6411 				.apic_register_virtualization = true,
6412 				.use_tpr_shadow = true,
6413 				.virtualize_apic_accesses = false,
6414 				.virtualize_x2apic_mode = true,
6415 				.activate_secondary_controls = true,
6416 			},
6417 		},
6418 	},
6419 	{
6420 		.name = "Baseline w/ x2apic disabled",
6421 		.virt_x2apic_mode_config = {
6422 			.virtual_interrupt_delivery = true,
6423 			.use_msr_bitmaps = true,
6424 			.disable_x2apic_msr_intercepts = true,
6425 			.disable_x2apic = true,
6426 			.apic_reg_virt_config = {
6427 				.apic_register_virtualization = true,
6428 				.use_tpr_shadow = true,
6429 				.virtualize_apic_accesses = false,
6430 				.virtualize_x2apic_mode = true,
6431 				.activate_secondary_controls = true,
6432 			},
6433 		},
6434 	},
6435 
6436 	/*
6437 	 * Baseline, minus virtual-interrupt delivery. Reads come from virtual
6438 	 * APIC page, special processing applies to VTPR, and all other writes
6439 	 * pass through to L1 APIC.
6440 	 */
6441 	{
6442 		.name = "Baseline - virtual interrupt delivery",
6443 		.virt_x2apic_mode_config = {
6444 			.virtual_interrupt_delivery = false,
6445 			.use_msr_bitmaps = true,
6446 			.disable_x2apic_msr_intercepts = true,
6447 			.disable_x2apic = false,
6448 			.apic_reg_virt_config = {
6449 				.apic_register_virtualization = true,
6450 				.use_tpr_shadow = true,
6451 				.virtualize_apic_accesses = false,
6452 				.virtualize_x2apic_mode = true,
6453 				.activate_secondary_controls = true,
6454 			},
6455 		},
6456 	},
6457 
6458 	/*
6459 	 * Baseline, minus APIC-register virtualization. x2APIC reads pass
6460 	 * through to L1's APIC, unless reading VTPR
6461 	 */
6462 	{
6463 		.name = "Virtualize x2APIC mode, no APIC reg virt",
6464 		.virt_x2apic_mode_config = {
6465 			.virtual_interrupt_delivery = true,
6466 			.use_msr_bitmaps = true,
6467 			.disable_x2apic_msr_intercepts = true,
6468 			.disable_x2apic = false,
6469 			.apic_reg_virt_config = {
6470 				.apic_register_virtualization = false,
6471 				.use_tpr_shadow = true,
6472 				.virtualize_apic_accesses = false,
6473 				.virtualize_x2apic_mode = true,
6474 				.activate_secondary_controls = true,
6475 			},
6476 		},
6477 	},
6478 	{
6479 		.name = "Virtualize x2APIC mode, no APIC reg virt, x2APIC off",
6480 		.virt_x2apic_mode_config = {
6481 			.virtual_interrupt_delivery = true,
6482 			.use_msr_bitmaps = true,
6483 			.disable_x2apic_msr_intercepts = true,
6484 			.disable_x2apic = true,
6485 			.apic_reg_virt_config = {
6486 				.apic_register_virtualization = false,
6487 				.use_tpr_shadow = true,
6488 				.virtualize_apic_accesses = false,
6489 				.virtualize_x2apic_mode = true,
6490 				.activate_secondary_controls = true,
6491 			},
6492 		},
6493 	},
6494 
6495 	/*
6496 	 * Enable "virtualize x2APIC mode" and "APIC-register virtualization",
6497 	 * and disable intercepts for the x2APIC MSRs, but fail to enable
6498 	 * "activate secondary controls" (i.e. L2 gets access to L1's x2APIC
6499 	 * MSRs).
6500 	 */
6501 	{
6502 		.name = "Fail to enable activate secondary controls",
6503 		.virt_x2apic_mode_config = {
6504 			.virtual_interrupt_delivery = true,
6505 			.use_msr_bitmaps = true,
6506 			.disable_x2apic_msr_intercepts = true,
6507 			.disable_x2apic = false,
6508 			.apic_reg_virt_config = {
6509 				.apic_register_virtualization = true,
6510 				.use_tpr_shadow = true,
6511 				.virtualize_apic_accesses = false,
6512 				.virtualize_x2apic_mode = true,
6513 				.activate_secondary_controls = false,
6514 			},
6515 		},
6516 	},
6517 
6518 	/*
6519 	 * Enable "APIC-register virtualization" and enable "activate secondary
6520 	 * controls" and disable intercepts for the x2APIC MSRs, but do not
6521 	 * enable the "virtualize x2APIC mode" VM-execution control (i.e. L2
6522 	 * gets access to L1's x2APIC MSRs).
6523 	 */
6524 	{
6525 		.name = "Fail to enable virtualize x2APIC mode",
6526 		.virt_x2apic_mode_config = {
6527 			.virtual_interrupt_delivery = true,
6528 			.use_msr_bitmaps = true,
6529 			.disable_x2apic_msr_intercepts = true,
6530 			.disable_x2apic = false,
6531 			.apic_reg_virt_config = {
6532 				.apic_register_virtualization = true,
6533 				.use_tpr_shadow = true,
6534 				.virtualize_apic_accesses = false,
6535 				.virtualize_x2apic_mode = false,
6536 				.activate_secondary_controls = true,
6537 			},
6538 		},
6539 	},
6540 
6541 	/*
6542 	 * Disable "Virtualize x2APIC mode", disable x2APIC MSR intercepts, and
6543 	 * enable "APIC-register virtualization" --> L2 gets L1's x2APIC MSRs.
6544 	 */
6545 	{
6546 		.name = "Baseline",
6547 		.virt_x2apic_mode_config = {
6548 			.virtual_interrupt_delivery = true,
6549 			.use_msr_bitmaps = true,
6550 			.disable_x2apic_msr_intercepts = true,
6551 			.disable_x2apic = false,
6552 			.apic_reg_virt_config = {
6553 				.apic_register_virtualization = true,
6554 				.use_tpr_shadow = true,
6555 				.virtualize_apic_accesses = false,
6556 				.virtualize_x2apic_mode = false,
6557 				.activate_secondary_controls = true,
6558 			},
6559 		},
6560 	},
6561 };
6562 
6563 enum X2apic_op {
6564 	X2APIC_OP_RD,
6565 	X2APIC_OP_WR,
6566 	X2APIC_TERMINATE,
6567 };
6568 
6569 static u64 vmx_x2apic_read(u32 reg)
6570 {
6571 	u32 msr_addr = x2apic_msr(reg);
6572 	u64 val;
6573 
6574 	val = rdmsr(msr_addr);
6575 
6576 	return val;
6577 }
6578 
6579 static void vmx_x2apic_write(u32 reg, u64 val)
6580 {
6581 	u32 msr_addr = x2apic_msr(reg);
6582 
6583 	wrmsr(msr_addr, val);
6584 }
6585 
6586 struct virt_x2apic_mode_guest_args {
6587 	enum X2apic_op op;
6588 	u32 reg;
6589 	u64 val;
6590 	bool should_gp;
6591 	u64 (*virt_fn)(u64);
6592 } virt_x2apic_mode_guest_args;
6593 
6594 static volatile bool handle_x2apic_gp_ran;
6595 static volatile u32 handle_x2apic_gp_insn_len;
6596 static void handle_x2apic_gp(struct ex_regs *regs)
6597 {
6598 	handle_x2apic_gp_ran = true;
6599 	regs->rip += handle_x2apic_gp_insn_len;
6600 }
6601 
6602 static handler setup_x2apic_gp_handler(void)
6603 {
6604 	handler old_handler;
6605 
6606 	old_handler = handle_exception(GP_VECTOR, handle_x2apic_gp);
6607 	/* RDMSR and WRMSR are both 2 bytes, assuming no prefixes. */
6608 	handle_x2apic_gp_insn_len = 2;
6609 
6610 	return old_handler;
6611 }
6612 
6613 static void teardown_x2apic_gp_handler(handler old_handler)
6614 {
6615 	handle_exception(GP_VECTOR, old_handler);
6616 
6617 	/*
6618 	 * Defensively reset instruction length, so that if the handler is
6619 	 * incorrectly used, it will loop infinitely, rather than run off into
6620 	 * la la land.
6621 	 */
6622 	handle_x2apic_gp_insn_len = 0;
6623 	handle_x2apic_gp_ran = false;
6624 }
6625 
6626 static void virt_x2apic_mode_guest(void)
6627 {
6628 	volatile struct virt_x2apic_mode_guest_args *args =
6629 		&virt_x2apic_mode_guest_args;
6630 
6631 	for (;;) {
6632 		enum X2apic_op op = args->op;
6633 		u32 reg = args->reg;
6634 		u64 val = args->val;
6635 		bool should_gp = args->should_gp;
6636 		u64 (*virt_fn)(u64) = args->virt_fn;
6637 		handler old_handler;
6638 
6639 		if (op == X2APIC_TERMINATE)
6640 			break;
6641 
6642 		if (should_gp) {
6643 			TEST_ASSERT(!handle_x2apic_gp_ran);
6644 			old_handler = setup_x2apic_gp_handler();
6645 		}
6646 
6647 		if (op == X2APIC_OP_RD) {
6648 			u64 ret = vmx_x2apic_read(reg);
6649 
6650 			if (!should_gp) {
6651 				u64 want = virt_fn(val);
6652 				u64 got = virt_fn(ret);
6653 
6654 				report(got == want,
6655 				       "APIC read; got 0x%lx, want 0x%lx.",
6656 				       got, want);
6657 			}
6658 		} else if (op == X2APIC_OP_WR) {
6659 			vmx_x2apic_write(reg, val);
6660 		}
6661 
6662 		if (should_gp) {
6663 			report(handle_x2apic_gp_ran,
6664 			       "x2APIC op triggered GP.");
6665 			teardown_x2apic_gp_handler(old_handler);
6666 		}
6667 
6668 		/*
6669 		 * The L1 should always execute a vmcall after it's done testing
6670 		 * an individual APIC operation. This helps to validate that the
6671 		 * L1 and L2 are in sync with each other, as expected.
6672 		 */
6673 		vmcall();
6674 	}
6675 }
6676 
6677 static void test_x2apic_rd(
6678 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6679 	u32 *virtual_apic_page)
6680 {
6681 	u64 val = expectation->rd_val;
6682 	u32 exit_reason_want = expectation->rd_exit_reason;
6683 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6684 
6685 	report_prefix_pushf("x2apic - reading 0x%03x", reg);
6686 
6687 	/* Configure guest to do an x2apic read */
6688 	args->op = X2APIC_OP_RD;
6689 	args->reg = reg;
6690 	args->val = val;
6691 	args->should_gp = expectation->rd_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6692 	args->virt_fn = expectation->virt_fn;
6693 
6694 	/* Setup virtual APIC page */
6695 	if (expectation->rd_behavior == X2APIC_ACCESS_VIRTUALIZED)
6696 		virtual_apic_page[apic_reg_index(reg)] = (u32)val;
6697 
6698 	/* Enter guest */
6699 	enter_guest();
6700 
6701 	if (exit_reason_want != VMX_VMCALL) {
6702 		report_fail("Oops, bad exit expectation: %u.", exit_reason_want);
6703 	}
6704 
6705 	skip_exit_vmcall();
6706 	report_prefix_pop();
6707 }
6708 
6709 static volatile bool handle_x2apic_ipi_ran;
6710 static void handle_x2apic_ipi(isr_regs_t *regs)
6711 {
6712 	handle_x2apic_ipi_ran = true;
6713 	eoi();
6714 }
6715 
6716 static void test_x2apic_wr(
6717 	u32 reg, struct virt_x2apic_mode_expectation *expectation,
6718 	u32 *virtual_apic_page)
6719 {
6720 	u64 val = expectation->wr_val;
6721 	u32 exit_reason_want = expectation->wr_exit_reason;
6722 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6723 	int ipi_vector = 0xf1;
6724 	u32 restore_val = 0;
6725 
6726 	report_prefix_pushf("x2apic - writing 0x%lx to 0x%03x", val, reg);
6727 
6728 	/* Configure guest to do an x2apic read */
6729 	args->op = X2APIC_OP_WR;
6730 	args->reg = reg;
6731 	args->val = val;
6732 	args->should_gp = expectation->wr_behavior == X2APIC_ACCESS_TRIGGERS_GP;
6733 
6734 	/* Setup virtual APIC page */
6735 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED)
6736 		virtual_apic_page[apic_reg_index(reg)] = 0;
6737 	if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH && !expectation->wr_only)
6738 		restore_val = apic_read(reg);
6739 
6740 	/* Setup IPI handler */
6741 	handle_x2apic_ipi_ran = false;
6742 	handle_irq(ipi_vector, handle_x2apic_ipi);
6743 
6744 	/* Enter guest */
6745 	enter_guest();
6746 
6747 	/*
6748 	 * Validate the behavior and
6749 	 * pass a magic value back to the guest.
6750 	 */
6751 	if (exit_reason_want == VMX_EXTINT) {
6752 		assert_exit_reason(exit_reason_want);
6753 
6754 		/* Clear the external interrupt. */
6755 		sti_nop_cli();
6756 		report(handle_x2apic_ipi_ran,
6757 		       "Got pending interrupt after IRQ enabled.");
6758 
6759 		enter_guest();
6760 	} else if (exit_reason_want == VMX_APIC_WRITE) {
6761 		assert_exit_reason(exit_reason_want);
6762 		report(virtual_apic_page[apic_reg_index(reg)] == val,
6763 		       "got APIC write exit @ page offset 0x%03x; val is 0x%x, want 0x%lx",
6764 		       apic_reg_index(reg),
6765 		       virtual_apic_page[apic_reg_index(reg)], val);
6766 
6767 		/* Reenter guest so it can consume/check rcx and exit again. */
6768 		enter_guest();
6769 	} else if (exit_reason_want != VMX_VMCALL) {
6770 		report_fail("Oops, bad exit expectation: %u.", exit_reason_want);
6771 	}
6772 
6773 	assert_exit_reason(VMX_VMCALL);
6774 	if (expectation->wr_behavior == X2APIC_ACCESS_VIRTUALIZED) {
6775 		u64 want = val;
6776 		u32 got = virtual_apic_page[apic_reg_index(reg)];
6777 
6778 		report(got == want, "x2APIC write; got 0x%x, want 0x%lx", got,
6779 		       want);
6780 	} else if (expectation->wr_behavior == X2APIC_ACCESS_PASSED_THROUGH) {
6781 		if (!expectation->wr_only) {
6782 			u32 got = apic_read(reg);
6783 			bool ok;
6784 
6785 			/*
6786 			 * When L1's TPR is passed through to L2, the lower
6787 			 * nibble can be lost. For example, if L2 executes
6788 			 * WRMSR(0x808, 0x78), then, L1 might read 0x70.
6789 			 *
6790 			 * Here's how the lower nibble can get lost:
6791 			 *   1. L2 executes WRMSR(0x808, 0x78).
6792 			 *   2. L2 exits to L0 with a WRMSR exit.
6793 			 *   3. L0 emulates WRMSR, by writing L1's TPR.
6794 			 *   4. L0 re-enters L2.
6795 			 *   5. L2 exits to L0 (reason doesn't matter).
6796 			 *   6. L0 reflects L2's exit to L1.
6797 			 *   7. Before entering L1, L0 exits to user-space
6798 			 *      (e.g., to satisfy TPR access reporting).
6799 			 *   8. User-space executes KVM_SET_REGS ioctl, which
6800 			 *      clears the lower nibble of L1's TPR.
6801 			 */
6802 			if (reg == APIC_TASKPRI) {
6803 				got = apic_virt_nibble1(got);
6804 				val = apic_virt_nibble1(val);
6805 			}
6806 
6807 			ok = got == val;
6808 			report(ok,
6809 			       "non-virtualized write; val is 0x%x, want 0x%lx",
6810 			       got, val);
6811 			apic_write(reg, restore_val);
6812 		} else {
6813 			report_pass("non-virtualized and write-only OK");
6814 		}
6815 	}
6816 	skip_exit_insn();
6817 
6818 	report_prefix_pop();
6819 }
6820 
6821 static enum Config_type configure_virt_x2apic_mode_test(
6822 	struct virt_x2apic_mode_config *virt_x2apic_mode_config,
6823 	u8 *msr_bitmap_page)
6824 {
6825 	int msr;
6826 	u32 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6827 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6828 
6829 	/* x2apic-specific VMCS config */
6830 	if (virt_x2apic_mode_config->use_msr_bitmaps) {
6831 		/* virt_x2apic_mode_test() checks for MSR bitmaps support */
6832 		cpu_exec_ctrl0 |= CPU_MSR_BITMAP;
6833 	} else {
6834 		cpu_exec_ctrl0 &= ~CPU_MSR_BITMAP;
6835 	}
6836 
6837 	if (virt_x2apic_mode_config->virtual_interrupt_delivery) {
6838 		if (!(ctrl_cpu_rev[1].clr & CPU_VINTD)) {
6839 			report_skip("%s : \"virtual-interrupt delivery\" exec control not supported", __func__);
6840 			return CONFIG_TYPE_UNSUPPORTED;
6841 		}
6842 		cpu_exec_ctrl1 |= CPU_VINTD;
6843 	} else {
6844 		cpu_exec_ctrl1 &= ~CPU_VINTD;
6845 	}
6846 
6847 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6848 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6849 
6850 	/* x2APIC MSR intercepts are usually off for "Virtualize x2APIC mode" */
6851 	for (msr = 0x800; msr <= 0x8ff; msr++) {
6852 		if (virt_x2apic_mode_config->disable_x2apic_msr_intercepts) {
6853 			clear_bit(msr, msr_bitmap_page + 0x000);
6854 			clear_bit(msr, msr_bitmap_page + 0x800);
6855 		} else {
6856 			set_bit(msr, msr_bitmap_page + 0x000);
6857 			set_bit(msr, msr_bitmap_page + 0x800);
6858 		}
6859 	}
6860 
6861 	/* x2APIC mode can impact virtualization */
6862 	reset_apic();
6863 	if (!virt_x2apic_mode_config->disable_x2apic)
6864 		enable_x2apic();
6865 
6866 	return configure_apic_reg_virt_test(
6867 		&virt_x2apic_mode_config->apic_reg_virt_config);
6868 }
6869 
6870 static void virt_x2apic_mode_test(void)
6871 {
6872 	u32 *virtual_apic_page;
6873 	u8 *msr_bitmap_page;
6874 	u64 cpu_exec_ctrl0 = vmcs_read(CPU_EXEC_CTRL0);
6875 	u64 cpu_exec_ctrl1 = vmcs_read(CPU_EXEC_CTRL1);
6876 	int i;
6877 	struct virt_x2apic_mode_guest_args *args = &virt_x2apic_mode_guest_args;
6878 
6879 	if (!cpu_has_apicv()) {
6880 		report_skip("%s : Not all required APICv bits supported", __func__);
6881 		return;
6882 	}
6883 
6884 	/*
6885 	 * This is to exercise an issue in KVM's logic to merge L0's and L1's
6886 	 * MSR bitmaps. Previously, an L1 could get at L0's x2APIC MSRs by
6887 	 * writing the IA32_SPEC_CTRL MSR or the IA32_PRED_CMD MSRs. KVM would
6888 	 * then proceed to manipulate the MSR bitmaps, as if VMCS12 had the
6889 	 * "Virtualize x2APIC mod" control set, even when it didn't.
6890 	 */
6891 	if (this_cpu_has(X86_FEATURE_SPEC_CTRL))
6892 		wrmsr(MSR_IA32_SPEC_CTRL, 1);
6893 
6894 	/*
6895 	 * Check that VMCS12 supports:
6896 	 *   - "Virtual-APIC address", indicated by "use TPR shadow"
6897 	 *   - "MSR-bitmap address", indicated by "use MSR bitmaps"
6898 	 */
6899 	if (!(ctrl_cpu_rev[0].clr & CPU_TPR_SHADOW)) {
6900 		report_skip("%s : \"Use TPR shadow\" exec control not supported", __func__);
6901 		return;
6902 	} else if (!(ctrl_cpu_rev[0].clr & CPU_MSR_BITMAP)) {
6903 		report_skip("%s : \"Use MSR bitmaps\" exec control not supported", __func__);
6904 		return;
6905 	}
6906 
6907 	test_set_guest(virt_x2apic_mode_guest);
6908 
6909 	virtual_apic_page = alloc_page();
6910 	vmcs_write(APIC_VIRT_ADDR, virt_to_phys(virtual_apic_page));
6911 
6912 	msr_bitmap_page = alloc_page();
6913 	memset(msr_bitmap_page, 0xff, PAGE_SIZE);
6914 	vmcs_write(MSR_BITMAP, virt_to_phys(msr_bitmap_page));
6915 
6916 	for (i = 0; i < ARRAY_SIZE(virt_x2apic_mode_tests); i++) {
6917 		struct virt_x2apic_mode_test_case *virt_x2apic_mode_test_case =
6918 			&virt_x2apic_mode_tests[i];
6919 		struct virt_x2apic_mode_config *virt_x2apic_mode_config =
6920 			&virt_x2apic_mode_test_case->virt_x2apic_mode_config;
6921 		enum Config_type config_type;
6922 		u32 reg;
6923 
6924 		printf("--- %s test ---\n", virt_x2apic_mode_test_case->name);
6925 		config_type =
6926 			configure_virt_x2apic_mode_test(virt_x2apic_mode_config,
6927 							msr_bitmap_page);
6928 		if (config_type == CONFIG_TYPE_UNSUPPORTED) {
6929 			report_skip("Skip because of missing features.");
6930 			continue;
6931 		} else if (config_type == CONFIG_TYPE_VMENTRY_FAILS_EARLY) {
6932 			enter_guest_with_bad_controls();
6933 			continue;
6934 		}
6935 
6936 		for (reg = 0; reg < PAGE_SIZE / sizeof(u32); reg += 0x10) {
6937 			struct virt_x2apic_mode_expectation expectation;
6938 
6939 			virt_x2apic_mode_exit_expectation(
6940 				reg, virt_x2apic_mode_config, &expectation);
6941 
6942 			test_x2apic_rd(reg, &expectation, virtual_apic_page);
6943 			test_x2apic_wr(reg, &expectation, virtual_apic_page);
6944 		}
6945 	}
6946 
6947 
6948 	/* Terminate the guest */
6949 	vmcs_write(CPU_EXEC_CTRL0, cpu_exec_ctrl0);
6950 	vmcs_write(CPU_EXEC_CTRL1, cpu_exec_ctrl1);
6951 	args->op = X2APIC_TERMINATE;
6952 	enter_guest();
6953 	assert_exit_reason(VMX_VMCALL);
6954 }
6955 
6956 static void test_ctl_reg(const char *cr_name, u64 cr, u64 fixed0, u64 fixed1)
6957 {
6958 	u64 val;
6959 	u64 cr_saved = vmcs_read(cr);
6960 	int i;
6961 
6962 	val = fixed0 & fixed1;
6963 	if (cr == HOST_CR4)
6964 		vmcs_write(cr, val | X86_CR4_PAE);
6965 	else
6966 		vmcs_write(cr, val);
6967 	report_prefix_pushf("%s %lx", cr_name, val);
6968 	if (val == fixed0)
6969 		test_vmx_vmlaunch(0);
6970 	else
6971 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6972 	report_prefix_pop();
6973 
6974 	for (i = 0; i < 64; i++) {
6975 
6976 		/* Set a bit when the corresponding bit in fixed1 is 0 */
6977 		if ((fixed1 & (1ull << i)) == 0) {
6978 			if (cr == HOST_CR4 && ((1ull << i) & X86_CR4_SMEP ||
6979 					       (1ull << i) & X86_CR4_SMAP))
6980 				continue;
6981 
6982 			vmcs_write(cr, cr_saved | (1ull << i));
6983 			report_prefix_pushf("%s %llx", cr_name,
6984 						cr_saved | (1ull << i));
6985 			test_vmx_vmlaunch(
6986 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6987 			report_prefix_pop();
6988 		}
6989 
6990 		/* Unset a bit when the corresponding bit in fixed0 is 1 */
6991 		if (fixed0 & (1ull << i)) {
6992 			vmcs_write(cr, cr_saved & ~(1ull << i));
6993 			report_prefix_pushf("%s %llx", cr_name,
6994 						cr_saved & ~(1ull << i));
6995 			test_vmx_vmlaunch(
6996 				VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
6997 			report_prefix_pop();
6998 		}
6999 	}
7000 
7001 	vmcs_write(cr, cr_saved);
7002 }
7003 
7004 /*
7005  * 1. The CR0 field must not set any bit to a value not supported in VMX
7006  *    operation.
7007  * 2. The CR4 field must not set any bit to a value not supported in VMX
7008  *    operation.
7009  * 3. On processors that support Intel 64 architecture, the CR3 field must
7010  *    be such that bits 63:52 and bits in the range 51:32 beyond the
7011  *    processor's physical-address width must be 0.
7012  *
7013  *  [Intel SDM]
7014  */
7015 static void test_host_ctl_regs(void)
7016 {
7017 	u64 fixed0, fixed1, cr3, cr3_saved;
7018 	int i;
7019 
7020 	/* Test CR0 */
7021 	fixed0 = rdmsr(MSR_IA32_VMX_CR0_FIXED0);
7022 	fixed1 = rdmsr(MSR_IA32_VMX_CR0_FIXED1);
7023 	test_ctl_reg("HOST_CR0", HOST_CR0, fixed0, fixed1);
7024 
7025 	/* Test CR4 */
7026 	fixed0 = rdmsr(MSR_IA32_VMX_CR4_FIXED0);
7027 	fixed1 = rdmsr(MSR_IA32_VMX_CR4_FIXED1) &
7028 		 ~(X86_CR4_SMEP | X86_CR4_SMAP);
7029 	test_ctl_reg("HOST_CR4", HOST_CR4, fixed0, fixed1);
7030 
7031 	/* Test CR3 */
7032 	cr3_saved = vmcs_read(HOST_CR3);
7033 	for (i = cpuid_maxphyaddr(); i < 64; i++) {
7034 		cr3 = cr3_saved | (1ul << i);
7035 		vmcs_write(HOST_CR3, cr3);
7036 		report_prefix_pushf("HOST_CR3 %lx", cr3);
7037 		if (this_cpu_has(X86_FEATURE_LAM) &&
7038 		    ((i == X86_CR3_LAM_U57_BIT) || (i == X86_CR3_LAM_U48_BIT)))
7039 			test_vmx_vmlaunch(0);
7040 		else
7041 			test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7042 		report_prefix_pop();
7043 	}
7044 
7045 	vmcs_write(HOST_CR3, cr3_saved);
7046 }
7047 
7048 static void test_efer_vmlaunch(u32 fld, bool ok)
7049 {
7050 	if (fld == HOST_EFER) {
7051 		if (ok)
7052 			test_vmx_vmlaunch(0);
7053 		else
7054 			test_vmx_vmlaunch2(VMXERR_ENTRY_INVALID_CONTROL_FIELD,
7055 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7056 	} else {
7057 		test_guest_state("EFER test", !ok, GUEST_EFER, "GUEST_EFER");
7058 	}
7059 }
7060 
7061 static void test_efer_one(u32 fld, const char * fld_name, u64 efer,
7062 			  u32 ctrl_fld, u64 ctrl,
7063 			  int i, const char *efer_bit_name)
7064 {
7065 	bool ok;
7066 
7067 	ok = true;
7068 	if (ctrl_fld == EXI_CONTROLS && (ctrl & EXI_LOAD_EFER)) {
7069 		if (!!(efer & EFER_LMA) != !!(ctrl & EXI_HOST_64))
7070 			ok = false;
7071 		if (!!(efer & EFER_LME) != !!(ctrl & EXI_HOST_64))
7072 			ok = false;
7073 	}
7074 	if (ctrl_fld == ENT_CONTROLS && (ctrl & ENT_LOAD_EFER)) {
7075 		/* Check LMA too since CR0.PG is set.  */
7076 		if (!!(efer & EFER_LMA) != !!(ctrl & ENT_GUEST_64))
7077 			ok = false;
7078 		if (!!(efer & EFER_LME) != !!(ctrl & ENT_GUEST_64))
7079 			ok = false;
7080 	}
7081 
7082 	/*
7083 	 * Skip the test if it would enter the guest in 32-bit mode.
7084 	 * Perhaps write the test in assembly and make sure it
7085 	 * can be run in either mode?
7086 	 */
7087 	if (fld == GUEST_EFER && ok && !(ctrl & ENT_GUEST_64))
7088 		return;
7089 
7090 	vmcs_write(ctrl_fld, ctrl);
7091 	vmcs_write(fld, efer);
7092 	report_prefix_pushf("%s %s bit turned %s, controls %s",
7093 			    fld_name, efer_bit_name,
7094 			    (i & 1) ? "on" : "off",
7095 			    (i & 2) ? "on" : "off");
7096 
7097 	test_efer_vmlaunch(fld, ok);
7098 	report_prefix_pop();
7099 }
7100 
7101 static void test_efer_bit(u32 fld, const char * fld_name,
7102 			  u32 ctrl_fld, u64 ctrl_bit, u64 efer_bit,
7103 			  const char *efer_bit_name)
7104 {
7105 	u64 efer_saved = vmcs_read(fld);
7106 	u32 ctrl_saved = vmcs_read(ctrl_fld);
7107 	int i;
7108 
7109 	for (i = 0; i < 4; i++) {
7110 		u64 efer = efer_saved & ~efer_bit;
7111 		u64 ctrl = ctrl_saved & ~ctrl_bit;
7112 
7113 		if (i & 1)
7114 			efer |= efer_bit;
7115 		if (i & 2)
7116 			ctrl |= ctrl_bit;
7117 
7118 		test_efer_one(fld, fld_name, efer, ctrl_fld, ctrl,
7119 			      i, efer_bit_name);
7120 	}
7121 
7122 	vmcs_write(ctrl_fld, ctrl_saved);
7123 	vmcs_write(fld, efer_saved);
7124 }
7125 
7126 static void test_efer(u32 fld, const char * fld_name, u32 ctrl_fld,
7127 		      u64 ctrl_bit1, u64 ctrl_bit2)
7128 {
7129 	u64 efer_saved = vmcs_read(fld);
7130 	u32 ctrl_saved = vmcs_read(ctrl_fld);
7131 	u64 efer_reserved_bits =  ~((u64)(EFER_SCE | EFER_LME | EFER_LMA));
7132 	u64 i;
7133 	u64 efer;
7134 
7135 	if (this_cpu_has(X86_FEATURE_NX))
7136 		efer_reserved_bits &= ~EFER_NX;
7137 
7138 	if (!ctrl_bit1) {
7139 		report_skip("%s : \"Load-IA32-EFER\" exit control not supported", __func__);
7140 		goto test_entry_exit_mode;
7141 	}
7142 
7143 	report_prefix_pushf("%s %lx", fld_name, efer_saved);
7144 	test_efer_vmlaunch(fld, true);
7145 	report_prefix_pop();
7146 
7147 	/*
7148 	 * Check reserved bits
7149 	 */
7150 	vmcs_write(ctrl_fld, ctrl_saved & ~ctrl_bit1);
7151 	for (i = 0; i < 64; i++) {
7152 		if ((1ull << i) & efer_reserved_bits) {
7153 			efer = efer_saved | (1ull << i);
7154 			vmcs_write(fld, efer);
7155 			report_prefix_pushf("%s %lx", fld_name, efer);
7156 			test_efer_vmlaunch(fld, true);
7157 			report_prefix_pop();
7158 		}
7159 	}
7160 
7161 	vmcs_write(ctrl_fld, ctrl_saved | ctrl_bit1);
7162 	for (i = 0; i < 64; i++) {
7163 		if ((1ull << i) & efer_reserved_bits) {
7164 			efer = efer_saved | (1ull << i);
7165 			vmcs_write(fld, efer);
7166 			report_prefix_pushf("%s %lx", fld_name, efer);
7167 			test_efer_vmlaunch(fld, false);
7168 			report_prefix_pop();
7169 		}
7170 	}
7171 
7172 	vmcs_write(ctrl_fld, ctrl_saved);
7173 	vmcs_write(fld, efer_saved);
7174 
7175 	/*
7176 	 * Check LMA and LME bits
7177 	 */
7178 	test_efer_bit(fld, fld_name,
7179 		      ctrl_fld, ctrl_bit1,
7180 		      EFER_LMA,
7181 		      "EFER_LMA");
7182 	test_efer_bit(fld, fld_name,
7183 		      ctrl_fld, ctrl_bit1,
7184 		      EFER_LME,
7185 		      "EFER_LME");
7186 
7187 test_entry_exit_mode:
7188 	test_efer_bit(fld, fld_name,
7189 		      ctrl_fld, ctrl_bit2,
7190 		      EFER_LMA,
7191 		      "EFER_LMA");
7192 	test_efer_bit(fld, fld_name,
7193 		      ctrl_fld, ctrl_bit2,
7194 		      EFER_LME,
7195 		      "EFER_LME");
7196 }
7197 
7198 /*
7199  * If the 'load IA32_EFER' VM-exit control is 1, bits reserved in the
7200  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7201  * the values of the LMA and LME bits in the field must each be that of
7202  * the 'host address-space size' VM-exit control.
7203  *
7204  *  [Intel SDM]
7205  */
7206 static void test_host_efer(void)
7207 {
7208 	test_efer(HOST_EFER, "HOST_EFER", EXI_CONTROLS,
7209 		  ctrl_exit_rev.clr & EXI_LOAD_EFER,
7210 		  EXI_HOST_64);
7211 }
7212 
7213 /*
7214  * If the 'load IA32_EFER' VM-enter control is 1, bits reserved in the
7215  * IA32_EFER MSR must be 0 in the field for that register. In addition,
7216  * the values of the LMA and LME bits in the field must each be that of
7217  * the 'IA32e-mode guest' VM-exit control.
7218  */
7219 static void test_guest_efer(void)
7220 {
7221 	if (!(ctrl_enter_rev.clr & ENT_LOAD_EFER)) {
7222 		report_skip("%s : \"Load-IA32-EFER\" entry control not supported", __func__);
7223 		return;
7224 	}
7225 
7226 	vmcs_write(GUEST_EFER, rdmsr(MSR_EFER));
7227 	test_efer(GUEST_EFER, "GUEST_EFER", ENT_CONTROLS,
7228 		  ctrl_enter_rev.clr & ENT_LOAD_EFER,
7229 		  ENT_GUEST_64);
7230 }
7231 
7232 /*
7233  * PAT values higher than 8 are uninteresting since they're likely lumped
7234  * in with "8". We only test values above 8 one bit at a time,
7235  * in order to reduce the number of VM-Entries and keep the runtime reasonable.
7236  */
7237 #define	PAT_VAL_LIMIT	8
7238 
7239 static void test_pat(u32 field, const char * field_name, u32 ctrl_field,
7240 		     u64 ctrl_bit)
7241 {
7242 	u64 pat_msr_saved = rdmsr(MSR_IA32_CR_PAT);
7243 	u32 ctrl_saved = vmcs_read(ctrl_field);
7244 	u64 pat_saved = vmcs_read(field);
7245 	u64 i, val;
7246 	u32 j;
7247 	int error;
7248 
7249 	vmcs_clear_bits(ctrl_field, ctrl_bit);
7250 
7251 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7252 		/* Test PAT0..PAT7 fields */
7253 		for (j = 0; j < (i ? 8 : 1); j++) {
7254 			val = i << j * 8;
7255 			vmcs_write(field, val);
7256 			if (field == HOST_PAT) {
7257 				report_prefix_pushf("%s %lx", field_name, val);
7258 				test_vmx_vmlaunch(0);
7259 				report_prefix_pop();
7260 
7261 			} else {	// GUEST_PAT
7262 				test_guest_state("ENT_LOAD_PAT disabled", false,
7263 						 val, "GUEST_PAT");
7264 			}
7265 		}
7266 	}
7267 
7268 	vmcs_set_bits(ctrl_field, ctrl_bit);
7269 	for (i = 0; i < 256; i = (i < PAT_VAL_LIMIT) ? i + 1 : i * 2) {
7270 		/* Test PAT0..PAT7 fields */
7271 		for (j = 0; j < (i ? 8 : 1); j++) {
7272 			val = i << j * 8;
7273 			vmcs_write(field, val);
7274 
7275 			if (field == HOST_PAT) {
7276 				report_prefix_pushf("%s %lx", field_name, val);
7277 				if (i == 0x2 || i == 0x3 || i >= 0x8)
7278 					error =
7279 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD;
7280 				else
7281 					error = 0;
7282 
7283 				test_vmx_vmlaunch(error);
7284 
7285 				if (!error)
7286 					report(rdmsr(MSR_IA32_CR_PAT) == val,
7287 					       "Expected PAT = 0x%lx, got 0x%lx",
7288 						val, rdmsr(MSR_IA32_CR_PAT));
7289 				wrmsr(MSR_IA32_CR_PAT, pat_msr_saved);
7290 
7291 				report_prefix_pop();
7292 
7293 			} else {	// GUEST_PAT
7294 				error = (i == 0x2 || i == 0x3 || i >= 0x8);
7295 				test_guest_state("ENT_LOAD_PAT enabled", !!error,
7296 						 val, "GUEST_PAT");
7297 
7298 				if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT))
7299 					wrmsr(MSR_IA32_CR_PAT, pat_msr_saved);
7300 			}
7301 
7302 		}
7303 	}
7304 
7305 	vmcs_write(ctrl_field, ctrl_saved);
7306 	vmcs_write(field, pat_saved);
7307 }
7308 
7309 /*
7310  *  If the "load IA32_PAT" VM-exit control is 1, the value of the field
7311  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7312  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7313  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7314  *  6 (WB), or 7 (UC-).
7315  *
7316  *  [Intel SDM]
7317  */
7318 static void test_load_host_pat(void)
7319 {
7320 	/*
7321 	 * "load IA32_PAT" VM-exit control
7322 	 */
7323 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PAT)) {
7324 		report_skip("%s : \"Load-IA32-PAT\" exit control not supported", __func__);
7325 		return;
7326 	}
7327 
7328 	test_pat(HOST_PAT, "HOST_PAT", EXI_CONTROLS, EXI_LOAD_PAT);
7329 }
7330 
7331 union cpuidA_eax {
7332 	struct {
7333 		unsigned int version_id:8;
7334 		unsigned int num_counters_gp:8;
7335 		unsigned int bit_width:8;
7336 		unsigned int mask_length:8;
7337 	} split;
7338 	unsigned int full;
7339 };
7340 
7341 union cpuidA_ecx {
7342 	unsigned int fixed_counters_mask;
7343 	unsigned int full;
7344 };
7345 
7346 union cpuidA_edx {
7347 	struct {
7348 		unsigned int num_contiguous_fixed_counters:5;
7349 		unsigned int bit_width_fixed:8;
7350 		unsigned int reserved1:2;
7351 		unsigned int anythread_deprecated:1;
7352 		unsigned int reserved2:16;
7353 	} split;
7354 	unsigned int full;
7355 };
7356 
7357 static bool valid_pgc(u64 val)
7358 {
7359 	struct cpuid id;
7360 	union cpuidA_eax eax;
7361 	union cpuidA_ecx ecx;
7362 	union cpuidA_edx edx;
7363 	u64 mask;
7364 
7365 	id = cpuid(0xA);
7366 	eax.full = id.a;
7367 	ecx.full = id.c;
7368 	edx.full = id.d;
7369 
7370 	/* FxCtr[i]_is_supported := ECX[i] || (EDX[4:0] > i); */
7371 	mask = ~(((1ull << eax.split.num_counters_gp) - 1) |
7372 		 (((1ull << edx.split.num_contiguous_fixed_counters) - 1) << 32) |
7373 		 ((u64)ecx.fixed_counters_mask << 32));
7374 
7375 	return !(val & mask);
7376 }
7377 
7378 static void test_pgc_vmlaunch(u32 xerror, u32 xreason, bool xfail, bool host)
7379 {
7380 	u32 inst_err;
7381 	u64 obs;
7382 	bool success;
7383 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7384 
7385 	if (host) {
7386 		success = vmlaunch();
7387 		obs = rdmsr(data->msr);
7388 		if (!success) {
7389 			inst_err = vmcs_read(VMX_INST_ERROR);
7390 			report(xerror == inst_err, "vmlaunch failed, "
7391 			       "VMX Inst Error is %d (expected %d)",
7392 			       inst_err, xerror);
7393 		} else {
7394 			report(!data->enabled || data->exp == obs,
7395 			       "Host state is 0x%lx (expected 0x%lx)",
7396 			       obs, data->exp);
7397 			report(success != xfail, "vmlaunch succeeded");
7398 		}
7399 	} else {
7400 		test_guest_state("load GUEST_PERF_GLOBAL_CTRL", xfail,
7401 				 GUEST_PERF_GLOBAL_CTRL,
7402 				 "GUEST_PERF_GLOBAL_CTRL");
7403 	}
7404 }
7405 
7406 /*
7407  * test_load_perf_global_ctrl is a generic function for testing the
7408  * "load IA32_PERF_GLOBAL_CTRL" VM-{Entry,Exit} controls. This test function
7409  * tests the provided ctrl_val when disabled and enabled.
7410  *
7411  * @nr: VMCS field number corresponding to the host/guest state field
7412  * @name: Name of the above VMCS field for printing in test report
7413  * @ctrl_nr: VMCS field number corresponding to the VM-{Entry,Exit} control
7414  * @ctrl_val: Bit to set on the ctrl_field
7415  */
7416 static void test_perf_global_ctrl(u32 nr, const char *name, u32 ctrl_nr,
7417 				  const char *ctrl_name, u64 ctrl_val)
7418 {
7419 	u64 ctrl_saved = vmcs_read(ctrl_nr);
7420 	u64 pgc_saved = vmcs_read(nr);
7421 	u64 i, val;
7422 	bool host = nr == HOST_PERF_GLOBAL_CTRL;
7423 	struct vmx_state_area_test_data *data = &vmx_state_area_test_data;
7424 
7425 	data->msr = MSR_CORE_PERF_GLOBAL_CTRL;
7426 	msr_bmp_init();
7427 	vmcs_write(ctrl_nr, ctrl_saved & ~ctrl_val);
7428 	data->enabled = false;
7429 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=0 on %s",
7430 			    ctrl_name);
7431 
7432 	for (i = 0; i < 64; i++) {
7433 		val = 1ull << i;
7434 		vmcs_write(nr, val);
7435 		report_prefix_pushf("%s = 0x%lx", name, val);
7436 		test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7437 		report_prefix_pop();
7438 	}
7439 	report_prefix_pop();
7440 
7441 	vmcs_write(ctrl_nr, ctrl_saved | ctrl_val);
7442 	data->enabled = true;
7443 	report_prefix_pushf("\"load IA32_PERF_GLOBAL_CTRL\"=1 on %s",
7444 			    ctrl_name);
7445 	for (i = 0; i < 64; i++) {
7446 		val = 1ull << i;
7447 		data->exp = val;
7448 		vmcs_write(nr, val);
7449 		report_prefix_pushf("%s = 0x%lx", name, val);
7450 		if (valid_pgc(val)) {
7451 			test_pgc_vmlaunch(0, VMX_VMCALL, false, host);
7452 		} else {
7453 			if (host)
7454 				test_pgc_vmlaunch(
7455 					VMXERR_ENTRY_INVALID_HOST_STATE_FIELD,
7456 					0,
7457 					true,
7458 					host);
7459 			else
7460 				test_pgc_vmlaunch(
7461 					0,
7462 					VMX_ENTRY_FAILURE | VMX_FAIL_STATE,
7463 					true,
7464 					host);
7465 		}
7466 		report_prefix_pop();
7467 	}
7468 
7469 	data->enabled = false;
7470 	report_prefix_pop();
7471 	vmcs_write(ctrl_nr, ctrl_saved);
7472 	vmcs_write(nr, pgc_saved);
7473 }
7474 
7475 static void test_load_host_perf_global_ctrl(void)
7476 {
7477 	if (!this_cpu_has_perf_global_ctrl()) {
7478 		report_skip("%s : \"IA32_PERF_GLOBAL_CTRL\" MSR not supported", __func__);
7479 		return;
7480 	}
7481 
7482 	if (!(ctrl_exit_rev.clr & EXI_LOAD_PERF)) {
7483 		report_skip("%s : \"Load IA32_PERF_GLOBAL_CTRL\" exit control not supported", __func__);
7484 		return;
7485 	}
7486 
7487 	test_perf_global_ctrl(HOST_PERF_GLOBAL_CTRL, "HOST_PERF_GLOBAL_CTRL",
7488 				   EXI_CONTROLS, "EXI_CONTROLS", EXI_LOAD_PERF);
7489 }
7490 
7491 
7492 static void test_load_guest_perf_global_ctrl(void)
7493 {
7494 	if (!this_cpu_has_perf_global_ctrl()) {
7495 		report_skip("%s : \"IA32_PERF_GLOBAL_CTRL\" MSR not supported", __func__);
7496 		return;
7497 	}
7498 
7499 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PERF)) {
7500 		report_skip("%s : \"Load IA32_PERF_GLOBAL_CTRL\" entry control not supported", __func__);
7501 		return;
7502 	}
7503 
7504 	test_perf_global_ctrl(GUEST_PERF_GLOBAL_CTRL, "GUEST_PERF_GLOBAL_CTRL",
7505 				   ENT_CONTROLS, "ENT_CONTROLS", ENT_LOAD_PERF);
7506 }
7507 
7508 
7509 /*
7510  * test_vmcs_field - test a value for the given VMCS field
7511  * @field: VMCS field
7512  * @field_name: string name of VMCS field
7513  * @bit_start: starting bit
7514  * @bit_end: ending bit
7515  * @val: value that the bit range must or must not contain
7516  * @valid_val: whether value given in 'val' must be valid or not
7517  * @error: expected VMCS error when vmentry fails for an invalid value
7518  */
7519 static void test_vmcs_field(u64 field, const char *field_name, u32 bit_start,
7520 			    u32 bit_end, u64 val, bool valid_val, u32 error)
7521 {
7522 	u64 field_saved = vmcs_read(field);
7523 	u32 i;
7524 	u64 tmp;
7525 	u32 bit_on;
7526 	u64 mask = ~0ull;
7527 
7528 	mask = (mask >> bit_end) << bit_end;
7529 	mask = mask | ((1 << bit_start) - 1);
7530 	tmp = (field_saved & mask) | (val << bit_start);
7531 
7532 	vmcs_write(field, tmp);
7533 	report_prefix_pushf("%s %lx", field_name, tmp);
7534 	if (valid_val)
7535 		test_vmx_vmlaunch(0);
7536 	else
7537 		test_vmx_vmlaunch(error);
7538 	report_prefix_pop();
7539 
7540 	for (i = bit_start; i <= bit_end; i = i + 2) {
7541 		bit_on = ((1ull < i) & (val << bit_start)) ? 0 : 1;
7542 		if (bit_on)
7543 			tmp = field_saved | (1ull << i);
7544 		else
7545 			tmp = field_saved & ~(1ull << i);
7546 		vmcs_write(field, tmp);
7547 		report_prefix_pushf("%s %lx", field_name, tmp);
7548 		if (valid_val)
7549 			test_vmx_vmlaunch(error);
7550 		else
7551 			test_vmx_vmlaunch(0);
7552 		report_prefix_pop();
7553 	}
7554 
7555 	vmcs_write(field, field_saved);
7556 }
7557 
7558 static void test_canonical(u64 field, const char * field_name, bool host)
7559 {
7560 	u64 addr_saved = vmcs_read(field);
7561 
7562 	/*
7563 	 * Use the existing value if possible.  Writing a random canonical
7564 	 * value is not an option as doing so would corrupt the field being
7565 	 * tested and likely hose the test.
7566 	 */
7567 	if (is_canonical(addr_saved)) {
7568 		if (host) {
7569 			report_prefix_pushf("%s %lx", field_name, addr_saved);
7570 			test_vmx_vmlaunch(0);
7571 			report_prefix_pop();
7572 		} else {
7573 			test_guest_state("Test canonical address", false,
7574 					 addr_saved, field_name);
7575 		}
7576 	}
7577 
7578 	vmcs_write(field, NONCANONICAL);
7579 
7580 	if (host) {
7581 		report_prefix_pushf("%s %llx", field_name, NONCANONICAL);
7582 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7583 		report_prefix_pop();
7584 	} else {
7585 		test_guest_state("Test non-canonical address", true,
7586 				 NONCANONICAL, field_name);
7587 	}
7588 
7589 	vmcs_write(field, addr_saved);
7590 }
7591 
7592 #define TEST_RPL_TI_FLAGS(reg, name)				\
7593 	test_vmcs_field(reg, name, 0, 2, 0x0, true,		\
7594 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7595 
7596 #define TEST_CS_TR_FLAGS(reg, name)				\
7597 	test_vmcs_field(reg, name, 3, 15, 0x0000, false,	\
7598 			VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7599 
7600 /*
7601  * 1. In the selector field for each of CS, SS, DS, ES, FS, GS and TR, the
7602  *    RPL (bits 1:0) and the TI flag (bit 2) must be 0.
7603  * 2. The selector fields for CS and TR cannot be 0000H.
7604  * 3. The selector field for SS cannot be 0000H if the "host address-space
7605  *    size" VM-exit control is 0.
7606  * 4. On processors that support Intel 64 architecture, the base-address
7607  *    fields for FS, GS and TR must contain canonical addresses.
7608  */
7609 static void test_host_segment_regs(void)
7610 {
7611 	u16 selector_saved;
7612 
7613 	/*
7614 	 * Test RPL and TI flags
7615 	 */
7616 	TEST_RPL_TI_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7617 	TEST_RPL_TI_FLAGS(HOST_SEL_SS, "HOST_SEL_SS");
7618 	TEST_RPL_TI_FLAGS(HOST_SEL_DS, "HOST_SEL_DS");
7619 	TEST_RPL_TI_FLAGS(HOST_SEL_ES, "HOST_SEL_ES");
7620 	TEST_RPL_TI_FLAGS(HOST_SEL_FS, "HOST_SEL_FS");
7621 	TEST_RPL_TI_FLAGS(HOST_SEL_GS, "HOST_SEL_GS");
7622 	TEST_RPL_TI_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7623 
7624 	/*
7625 	 * Test that CS and TR fields can not be 0x0000
7626 	 */
7627 	TEST_CS_TR_FLAGS(HOST_SEL_CS, "HOST_SEL_CS");
7628 	TEST_CS_TR_FLAGS(HOST_SEL_TR, "HOST_SEL_TR");
7629 
7630 	/*
7631 	 * SS field can not be 0x0000 if "host address-space size" VM-exit
7632 	 * control is 0
7633 	 */
7634 	selector_saved = vmcs_read(HOST_SEL_SS);
7635 	vmcs_write(HOST_SEL_SS, 0);
7636 	report_prefix_pushf("HOST_SEL_SS 0");
7637 	if (vmcs_read(EXI_CONTROLS) & EXI_HOST_64) {
7638 		test_vmx_vmlaunch(0);
7639 	} else {
7640 		test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7641 	}
7642 	report_prefix_pop();
7643 
7644 	vmcs_write(HOST_SEL_SS, selector_saved);
7645 
7646 	/*
7647 	 * Base address for FS, GS and TR must be canonical
7648 	 */
7649 	test_canonical(HOST_BASE_FS, "HOST_BASE_FS", true);
7650 	test_canonical(HOST_BASE_GS, "HOST_BASE_GS", true);
7651 	test_canonical(HOST_BASE_TR, "HOST_BASE_TR", true);
7652 }
7653 
7654 /*
7655  *  On processors that support Intel 64 architecture, the base-address
7656  *  fields for GDTR and IDTR must contain canonical addresses.
7657  */
7658 static void test_host_desc_tables(void)
7659 {
7660 	test_canonical(HOST_BASE_GDTR, "HOST_BASE_GDTR", true);
7661 	test_canonical(HOST_BASE_IDTR, "HOST_BASE_IDTR", true);
7662 }
7663 
7664 /*
7665  * If the "host address-space size" VM-exit control is 0, the following must
7666  * hold:
7667  *    - The "IA-32e mode guest" VM-entry control is 0.
7668  *    - Bit 17 of the CR4 field (corresponding to CR4.PCIDE) is 0.
7669  *    - Bits 63:32 in the RIP field are 0.
7670  *
7671  * If the "host address-space size" VM-exit control is 1, the following must
7672  * hold:
7673  *    - Bit 5 of the CR4 field (corresponding to CR4.PAE) is 1.
7674  *    - The RIP field contains a canonical address.
7675  *
7676  */
7677 static void test_host_addr_size(void)
7678 {
7679 	u64 cr4_saved = vmcs_read(HOST_CR4);
7680 	u64 rip_saved = vmcs_read(HOST_RIP);
7681 	u64 entry_ctrl_saved = vmcs_read(ENT_CONTROLS);
7682 
7683 	assert(vmcs_read(EXI_CONTROLS) & EXI_HOST_64);
7684 	assert(cr4_saved & X86_CR4_PAE);
7685 
7686 	vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7687 	report_prefix_pushf("\"IA-32e mode guest\" enabled");
7688 	test_vmx_vmlaunch(0);
7689 	report_prefix_pop();
7690 
7691 	if (this_cpu_has(X86_FEATURE_PCID)) {
7692 		vmcs_write(HOST_CR4, cr4_saved | X86_CR4_PCIDE);
7693 		report_prefix_pushf("\"CR4.PCIDE\" set");
7694 		test_vmx_vmlaunch(0);
7695 		report_prefix_pop();
7696 	}
7697 
7698 	vmcs_write(HOST_CR4, cr4_saved  & ~X86_CR4_PAE);
7699 	report_prefix_pushf("\"CR4.PAE\" unset");
7700 	test_vmx_vmlaunch(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7701 	vmcs_write(HOST_CR4, cr4_saved);
7702 	report_prefix_pop();
7703 
7704 	vmcs_write(HOST_RIP, NONCANONICAL);
7705 	report_prefix_pushf("HOST_RIP %llx", NONCANONICAL);
7706 	test_vmx_vmlaunch_must_fail(VMXERR_ENTRY_INVALID_HOST_STATE_FIELD);
7707 	report_prefix_pop();
7708 
7709 	vmcs_write(ENT_CONTROLS, entry_ctrl_saved | ENT_GUEST_64);
7710 	vmcs_write(HOST_RIP, rip_saved);
7711 	vmcs_write(HOST_CR4, cr4_saved);
7712 
7713 	/*
7714 	 * Restore host's active CR4 and RIP values by triggering a VM-Exit.
7715 	 * The original CR4 and RIP values in the VMCS are restored between
7716 	 * testcases as needed, but don't guarantee a VM-Exit and so the active
7717 	 * CR4 and RIP may still hold a test value.  Running with the test CR4
7718 	 * and RIP values at some point is unavoidable, and the active values
7719 	 * are unlikely to affect VM-Enter, so the above doesn't force a VM-exit
7720 	 * between testcases.  Note, if VM-Enter is surrounded by CALL+RET then
7721 	 * the active RIP will already be restored, but that's also not
7722 	 * guaranteed, and CR4 needs to be restored regardless.
7723 	 */
7724 	report_prefix_pushf("restore host state");
7725 	test_vmx_vmlaunch(0);
7726 	report_prefix_pop();
7727 }
7728 
7729 /*
7730  * Check that the virtual CPU checks the VMX Host State Area as
7731  * documented in the Intel SDM.
7732  */
7733 static void vmx_host_state_area_test(void)
7734 {
7735 	/*
7736 	 * Bit 1 of the guest's RFLAGS must be 1, or VM-entry will
7737 	 * fail due to invalid guest state, should we make it that
7738 	 * far.
7739 	 */
7740 	vmcs_write(GUEST_RFLAGS, 0);
7741 
7742 	test_host_ctl_regs();
7743 
7744 	test_canonical(HOST_SYSENTER_ESP, "HOST_SYSENTER_ESP", true);
7745 	test_canonical(HOST_SYSENTER_EIP, "HOST_SYSENTER_EIP", true);
7746 
7747 	test_host_efer();
7748 	test_load_host_pat();
7749 	test_host_segment_regs();
7750 	test_host_desc_tables();
7751 	test_host_addr_size();
7752 	test_load_host_perf_global_ctrl();
7753 }
7754 
7755 /*
7756  * If the "load debug controls" VM-entry control is 1, bits 63:32 in
7757  * the DR7 field must be 0.
7758  *
7759  * [Intel SDM]
7760  */
7761 static void test_guest_dr7(void)
7762 {
7763 	u32 ent_saved = vmcs_read(ENT_CONTROLS);
7764 	u64 dr7_saved = vmcs_read(GUEST_DR7);
7765 	u64 val;
7766 	int i;
7767 
7768 	if (ctrl_enter_rev.set & ENT_LOAD_DBGCTLS) {
7769 		vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7770 		for (i = 0; i < 64; i++) {
7771 			val = 1ull << i;
7772 			vmcs_write(GUEST_DR7, val);
7773 			test_guest_state("ENT_LOAD_DBGCTLS disabled", false,
7774 					 val, "GUEST_DR7");
7775 		}
7776 	}
7777 	if (ctrl_enter_rev.clr & ENT_LOAD_DBGCTLS) {
7778 		vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_DBGCTLS);
7779 		for (i = 0; i < 64; i++) {
7780 			val = 1ull << i;
7781 			vmcs_write(GUEST_DR7, val);
7782 			test_guest_state("ENT_LOAD_DBGCTLS enabled", i >= 32,
7783 					 val, "GUEST_DR7");
7784 		}
7785 	}
7786 	vmcs_write(GUEST_DR7, dr7_saved);
7787 	vmcs_write(ENT_CONTROLS, ent_saved);
7788 }
7789 
7790 /*
7791  *  If the "load IA32_PAT" VM-entry control is 1, the value of the field
7792  *  for the IA32_PAT MSR must be one that could be written by WRMSR
7793  *  without fault at CPL 0. Specifically, each of the 8 bytes in the
7794  *  field must have one of the values 0 (UC), 1 (WC), 4 (WT), 5 (WP),
7795  *  6 (WB), or 7 (UC-).
7796  *
7797  *  [Intel SDM]
7798  */
7799 static void test_load_guest_pat(void)
7800 {
7801 	/*
7802 	 * "load IA32_PAT" VM-entry control
7803 	 */
7804 	if (!(ctrl_enter_rev.clr & ENT_LOAD_PAT)) {
7805 		report_skip("%s : \"Load-IA32-PAT\" entry control not supported", __func__);
7806 		return;
7807 	}
7808 
7809 	test_pat(GUEST_PAT, "GUEST_PAT", ENT_CONTROLS, ENT_LOAD_PAT);
7810 }
7811 
7812 #define MSR_IA32_BNDCFGS_RSVD_MASK	0x00000ffc
7813 
7814 /*
7815  * If the "load IA32_BNDCFGS" VM-entry control is 1, the following
7816  * checks are performed on the field for the IA32_BNDCFGS MSR:
7817  *
7818  *   - Bits reserved in the IA32_BNDCFGS MSR must be 0.
7819  *   - The linear address in bits 63:12 must be canonical.
7820  *
7821  *  [Intel SDM]
7822  */
7823 static void test_load_guest_bndcfgs(void)
7824 {
7825 	u64 bndcfgs_saved = vmcs_read(GUEST_BNDCFGS);
7826 	u64 bndcfgs;
7827 
7828 	if (!(ctrl_enter_rev.clr & ENT_LOAD_BNDCFGS)) {
7829 		report_skip("%s : \"Load-IA32-BNDCFGS\" entry control not supported", __func__);
7830 		return;
7831 	}
7832 
7833 	vmcs_clear_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7834 
7835 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7836 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7837 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7838 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7839 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7840 	test_guest_state("ENT_LOAD_BNDCFGS disabled", false,
7841 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7842 
7843 	vmcs_set_bits(ENT_CONTROLS, ENT_LOAD_BNDCFGS);
7844 
7845 	vmcs_write(GUEST_BNDCFGS, NONCANONICAL);
7846 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7847 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7848 	bndcfgs = bndcfgs_saved | MSR_IA32_BNDCFGS_RSVD_MASK;
7849 	vmcs_write(GUEST_BNDCFGS, bndcfgs);
7850 	test_guest_state("ENT_LOAD_BNDCFGS enabled", true,
7851 			 GUEST_BNDCFGS, "GUEST_BNDCFGS");
7852 
7853 	vmcs_write(GUEST_BNDCFGS, bndcfgs_saved);
7854 }
7855 
7856 #define	GUEST_SEG_UNUSABLE_MASK	(1u << 16)
7857 #define	GUEST_SEG_SEL_TI_MASK	(1u << 2)
7858 
7859 
7860 #define	TEST_SEGMENT_SEL(test, xfail, sel, val)				\
7861 do {									\
7862 	vmcs_write(sel, val);						\
7863 	test_guest_state(test " segment", xfail, val, xstr(sel));	\
7864 } while (0)
7865 
7866 #define	TEST_INVALID_SEG_SEL(sel, val) \
7867 	TEST_SEGMENT_SEL("Invalid: " xstr(val), true, sel, val);
7868 
7869 #define	TEST_VALID_SEG_SEL(sel, val) \
7870 	TEST_SEGMENT_SEL("Valid: " xstr(val), false, sel, val);
7871 
7872 /*
7873  * The following checks are done on the Selector field of the Guest Segment
7874  * Registers:
7875  *    - TR. The TI flag (bit 2) must be 0.
7876  *    - LDTR. If LDTR is usable, the TI flag (bit 2) must be 0.
7877  *    - SS. If the guest will not be virtual-8086 and the "unrestricted
7878  *	guest" VM-execution control is 0, the RPL (bits 1:0) must equal
7879  *	the RPL of the selector field for CS.
7880  *
7881  *  [Intel SDM]
7882  */
7883 static void test_guest_segment_sel_fields(void)
7884 {
7885 	u16 sel_saved;
7886 	u32 ar_saved;
7887 	u32 cpu_ctrl0_saved;
7888 	u32 cpu_ctrl1_saved;
7889 	u16 cs_rpl_bits;
7890 
7891 	/*
7892 	 * Test for GUEST_SEL_TR
7893 	 */
7894 	sel_saved = vmcs_read(GUEST_SEL_TR);
7895 	TEST_INVALID_SEG_SEL(GUEST_SEL_TR, sel_saved | GUEST_SEG_SEL_TI_MASK);
7896 	vmcs_write(GUEST_SEL_TR, sel_saved);
7897 
7898 	/*
7899 	 * Test for GUEST_SEL_LDTR
7900 	 */
7901 	sel_saved = vmcs_read(GUEST_SEL_LDTR);
7902 	ar_saved = vmcs_read(GUEST_AR_LDTR);
7903 	/* LDTR is set unusable */
7904 	vmcs_write(GUEST_AR_LDTR, ar_saved | GUEST_SEG_UNUSABLE_MASK);
7905 	TEST_VALID_SEG_SEL(GUEST_SEL_LDTR, sel_saved | GUEST_SEG_SEL_TI_MASK);
7906 	TEST_VALID_SEG_SEL(GUEST_SEL_LDTR, sel_saved & ~GUEST_SEG_SEL_TI_MASK);
7907 	/* LDTR is set usable */
7908 	vmcs_write(GUEST_AR_LDTR, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
7909 	TEST_INVALID_SEG_SEL(GUEST_SEL_LDTR, sel_saved | GUEST_SEG_SEL_TI_MASK);
7910 
7911 	TEST_VALID_SEG_SEL(GUEST_SEL_LDTR, sel_saved & ~GUEST_SEG_SEL_TI_MASK);
7912 
7913 	vmcs_write(GUEST_AR_LDTR, ar_saved);
7914 	vmcs_write(GUEST_SEL_LDTR, sel_saved);
7915 
7916 	/*
7917 	 * Test for GUEST_SEL_SS
7918 	 */
7919 	cpu_ctrl0_saved = vmcs_read(CPU_EXEC_CTRL0);
7920 	cpu_ctrl1_saved = vmcs_read(CPU_EXEC_CTRL1);
7921 	ar_saved = vmcs_read(GUEST_AR_SS);
7922 	/* Turn off "unrestricted guest" vm-execution control */
7923 	vmcs_write(CPU_EXEC_CTRL1, cpu_ctrl1_saved & ~CPU_URG);
7924 	cs_rpl_bits = vmcs_read(GUEST_SEL_CS) & 0x3;
7925 	sel_saved = vmcs_read(GUEST_SEL_SS);
7926 	TEST_INVALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (~cs_rpl_bits & 0x3)));
7927 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (cs_rpl_bits & 0x3)));
7928 	/* Make SS usable if it's unusable or vice-versa */
7929 	if (ar_saved & GUEST_SEG_UNUSABLE_MASK)
7930 		vmcs_write(GUEST_AR_SS, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
7931 	else
7932 		vmcs_write(GUEST_AR_SS, ar_saved | GUEST_SEG_UNUSABLE_MASK);
7933 	TEST_INVALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (~cs_rpl_bits & 0x3)));
7934 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (cs_rpl_bits & 0x3)));
7935 
7936 	/* Need a valid EPTP as the passing case fully enters the guest. */
7937 	if (enable_unrestricted_guest(true))
7938 		goto skip_ss_tests;
7939 
7940 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (~cs_rpl_bits & 0x3)));
7941 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (cs_rpl_bits & 0x3)));
7942 
7943 	/* Make SS usable if it's unusable or vice-versa */
7944 	if (vmcs_read(GUEST_AR_SS) & GUEST_SEG_UNUSABLE_MASK)
7945 		vmcs_write(GUEST_AR_SS, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
7946 	else
7947 		vmcs_write(GUEST_AR_SS, ar_saved | GUEST_SEG_UNUSABLE_MASK);
7948 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (~cs_rpl_bits & 0x3)));
7949 	TEST_VALID_SEG_SEL(GUEST_SEL_SS, ((sel_saved & ~0x3) | (cs_rpl_bits & 0x3)));
7950 skip_ss_tests:
7951 
7952 	vmcs_write(GUEST_AR_SS, ar_saved);
7953 	vmcs_write(GUEST_SEL_SS, sel_saved);
7954 	vmcs_write(CPU_EXEC_CTRL0, cpu_ctrl0_saved);
7955 	vmcs_write(CPU_EXEC_CTRL1, cpu_ctrl1_saved);
7956 }
7957 
7958 #define	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(xfail, seg_base)			\
7959 do {										\
7960 	addr_saved = vmcs_read(seg_base);					\
7961 	for (i = 32; i < 63; i = i + 4) {					\
7962 		addr = addr_saved | 1ull << i;					\
7963 		vmcs_write(seg_base, addr);					\
7964 		test_guest_state("seg.BASE[63:32] != 0, usable = " xstr(xfail),	\
7965 				 xfail, addr, xstr(seg_base));			\
7966 	}									\
7967 	vmcs_write(seg_base, addr_saved);					\
7968 } while (0)
7969 
7970 #define	TEST_SEGMENT_BASE_ADDR_CANONICAL(xfail, seg_base)		  \
7971 do {									  \
7972 	addr_saved = vmcs_read(seg_base);				  \
7973 	vmcs_write(seg_base, NONCANONICAL);				  \
7974 	test_guest_state("seg.BASE non-canonical, usable = " xstr(xfail), \
7975 			 xfail, NONCANONICAL, xstr(seg_base));		  \
7976 	vmcs_write(seg_base, addr_saved);				  \
7977 } while (0)
7978 
7979 /*
7980  * The following checks are done on the Base Address field of the Guest
7981  * Segment Registers on processors that support Intel 64 architecture:
7982  *    - TR, FS, GS : The address must be canonical.
7983  *    - LDTR : If LDTR is usable, the address must be canonical.
7984  *    - CS : Bits 63:32 of the address must be zero.
7985  *    - SS, DS, ES : If the register is usable, bits 63:32 of the address
7986  *	must be zero.
7987  *
7988  *  [Intel SDM]
7989  */
7990 static void test_guest_segment_base_addr_fields(void)
7991 {
7992 	u64 addr_saved;
7993 	u64 addr;
7994 	u32 ar_saved;
7995 	int i;
7996 
7997 	/*
7998 	 * The address of TR, FS, GS and LDTR must be canonical.
7999 	 */
8000 	TEST_SEGMENT_BASE_ADDR_CANONICAL(true, GUEST_BASE_TR);
8001 	TEST_SEGMENT_BASE_ADDR_CANONICAL(true, GUEST_BASE_FS);
8002 	TEST_SEGMENT_BASE_ADDR_CANONICAL(true, GUEST_BASE_GS);
8003 	ar_saved = vmcs_read(GUEST_AR_LDTR);
8004 	/* Make LDTR unusable */
8005 	vmcs_write(GUEST_AR_LDTR, ar_saved | GUEST_SEG_UNUSABLE_MASK);
8006 	TEST_SEGMENT_BASE_ADDR_CANONICAL(false, GUEST_BASE_LDTR);
8007 	/* Make LDTR usable */
8008 	vmcs_write(GUEST_AR_LDTR, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
8009 	TEST_SEGMENT_BASE_ADDR_CANONICAL(true, GUEST_BASE_LDTR);
8010 
8011 	vmcs_write(GUEST_AR_LDTR, ar_saved);
8012 
8013 	/*
8014 	 * Bits 63:32 in CS, SS, DS and ES base address must be zero
8015 	 */
8016 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(true, GUEST_BASE_CS);
8017 	ar_saved = vmcs_read(GUEST_AR_SS);
8018 	/* Make SS unusable */
8019 	vmcs_write(GUEST_AR_SS, ar_saved | GUEST_SEG_UNUSABLE_MASK);
8020 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(false, GUEST_BASE_SS);
8021 	/* Make SS usable */
8022 	vmcs_write(GUEST_AR_SS, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
8023 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(true, GUEST_BASE_SS);
8024 	vmcs_write(GUEST_AR_SS, ar_saved);
8025 
8026 	ar_saved = vmcs_read(GUEST_AR_DS);
8027 	/* Make DS unusable */
8028 	vmcs_write(GUEST_AR_DS, ar_saved | GUEST_SEG_UNUSABLE_MASK);
8029 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(false, GUEST_BASE_DS);
8030 	/* Make DS usable */
8031 	vmcs_write(GUEST_AR_DS, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
8032 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(true, GUEST_BASE_DS);
8033 	vmcs_write(GUEST_AR_DS, ar_saved);
8034 
8035 	ar_saved = vmcs_read(GUEST_AR_ES);
8036 	/* Make ES unusable */
8037 	vmcs_write(GUEST_AR_ES, ar_saved | GUEST_SEG_UNUSABLE_MASK);
8038 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(false, GUEST_BASE_ES);
8039 	/* Make ES usable */
8040 	vmcs_write(GUEST_AR_ES, ar_saved & ~GUEST_SEG_UNUSABLE_MASK);
8041 	TEST_SEGMENT_BASE_ADDR_UPPER_BITS(true, GUEST_BASE_ES);
8042 	vmcs_write(GUEST_AR_ES, ar_saved);
8043 }
8044 
8045 /*
8046  * Check that the virtual CPU checks the VMX Guest State Area as
8047  * documented in the Intel SDM.
8048  */
8049 static void vmx_guest_state_area_test(void)
8050 {
8051 	vmx_set_test_stage(1);
8052 	test_set_guest(guest_state_test_main);
8053 
8054 	/*
8055 	 * The IA32_SYSENTER_ESP field and the IA32_SYSENTER_EIP field
8056 	 * must each contain a canonical address.
8057 	 */
8058 	test_canonical(GUEST_SYSENTER_ESP, "GUEST_SYSENTER_ESP", false);
8059 	test_canonical(GUEST_SYSENTER_EIP, "GUEST_SYSENTER_EIP", false);
8060 
8061 	test_guest_dr7();
8062 	test_load_guest_pat();
8063 	test_guest_efer();
8064 	test_load_guest_perf_global_ctrl();
8065 	test_load_guest_bndcfgs();
8066 
8067 	test_guest_segment_sel_fields();
8068 	test_guest_segment_base_addr_fields();
8069 
8070 	test_canonical(GUEST_BASE_GDTR, "GUEST_BASE_GDTR", false);
8071 	test_canonical(GUEST_BASE_IDTR, "GUEST_BASE_IDTR", false);
8072 
8073 	u32 guest_desc_limit_saved = vmcs_read(GUEST_LIMIT_GDTR);
8074 	int i;
8075 	for (i = 16; i <= 31; i++) {
8076 		u32 tmp = guest_desc_limit_saved | (1ull << i);
8077 		vmcs_write(GUEST_LIMIT_GDTR, tmp);
8078 		test_guest_state("GDT.limit > 0xffff", true, tmp, "GUEST_LIMIT_GDTR");
8079 	}
8080 	vmcs_write(GUEST_LIMIT_GDTR, guest_desc_limit_saved);
8081 
8082 	guest_desc_limit_saved = vmcs_read(GUEST_LIMIT_IDTR);
8083 	for (i = 16; i <= 31; i++) {
8084 		u32 tmp = guest_desc_limit_saved | (1ull << i);
8085 		vmcs_write(GUEST_LIMIT_IDTR, tmp);
8086 		test_guest_state("IDT.limit > 0xffff", true, tmp, "GUEST_LIMIT_IDTR");
8087 	}
8088 	vmcs_write(GUEST_LIMIT_IDTR, guest_desc_limit_saved);
8089 
8090 	/*
8091 	 * Let the guest finish execution
8092 	 */
8093 	vmx_set_test_stage(2);
8094 	enter_guest();
8095 }
8096 
8097 extern void unrestricted_guest_main(void);
8098 asm (".code32\n"
8099 	"unrestricted_guest_main:\n"
8100 	"vmcall\n"
8101 	"nop\n"
8102 	"mov $1, %edi\n"
8103 	"call hypercall\n"
8104 	".code64\n");
8105 
8106 static void setup_unrestricted_guest(void)
8107 {
8108 	vmcs_write(GUEST_CR0, vmcs_read(GUEST_CR0) & ~(X86_CR0_PG));
8109 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) & ~ENT_GUEST_64);
8110 	vmcs_write(GUEST_EFER, vmcs_read(GUEST_EFER) & ~EFER_LMA);
8111 	vmcs_write(GUEST_RIP, virt_to_phys(unrestricted_guest_main));
8112 }
8113 
8114 static void unsetup_unrestricted_guest(void)
8115 {
8116 	vmcs_write(GUEST_CR0, vmcs_read(GUEST_CR0) | X86_CR0_PG);
8117 	vmcs_write(ENT_CONTROLS, vmcs_read(ENT_CONTROLS) | ENT_GUEST_64);
8118 	vmcs_write(GUEST_EFER, vmcs_read(GUEST_EFER) | EFER_LMA);
8119 	vmcs_write(GUEST_RIP, (u64) phys_to_virt(vmcs_read(GUEST_RIP)));
8120 	vmcs_write(GUEST_RSP, (u64) phys_to_virt(vmcs_read(GUEST_RSP)));
8121 }
8122 
8123 /*
8124  * If "unrestricted guest" secondary VM-execution control is set, guests
8125  * can run in unpaged protected mode.
8126  */
8127 static void vmentry_unrestricted_guest_test(void)
8128 {
8129 	if (enable_unrestricted_guest(true)) {
8130 		report_skip("%s: \"Unrestricted guest\" exec control not supported", __func__);
8131 		return;
8132 	}
8133 
8134 	test_set_guest(unrestricted_guest_main);
8135 	setup_unrestricted_guest();
8136 	test_guest_state("Unrestricted guest test", false, CPU_URG, "CPU_URG");
8137 
8138 	/*
8139 	 * Let the guest finish execution as a regular guest
8140 	 */
8141 	unsetup_unrestricted_guest();
8142 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) & ~CPU_URG);
8143 	enter_guest();
8144 }
8145 
8146 static bool valid_vmcs_for_vmentry(void)
8147 {
8148 	struct vmcs *current_vmcs = NULL;
8149 
8150 	if (vmcs_save(&current_vmcs))
8151 		return false;
8152 
8153 	return current_vmcs && !current_vmcs->hdr.shadow_vmcs;
8154 }
8155 
8156 static void try_vmentry_in_movss_shadow(void)
8157 {
8158 	u32 vm_inst_err;
8159 	u32 flags;
8160 	bool early_failure = false;
8161 	u32 expected_flags = X86_EFLAGS_FIXED;
8162 	bool valid_vmcs = valid_vmcs_for_vmentry();
8163 
8164 	expected_flags |= valid_vmcs ? X86_EFLAGS_ZF : X86_EFLAGS_CF;
8165 
8166 	/*
8167 	 * Indirectly set VM_INST_ERR to 12 ("VMREAD/VMWRITE from/to
8168 	 * unsupported VMCS component").
8169 	 */
8170 	vmcs_write(~0u, 0);
8171 
8172 	__asm__ __volatile__ ("mov %[host_rsp], %%edx;"
8173 			      "vmwrite %%rsp, %%rdx;"
8174 			      "mov 0f, %%rax;"
8175 			      "mov %[host_rip], %%edx;"
8176 			      "vmwrite %%rax, %%rdx;"
8177 			      "mov $-1, %%ah;"
8178 			      "sahf;"
8179 			      "mov %%ss, %%ax;"
8180 			      "mov %%ax, %%ss;"
8181 			      "vmlaunch;"
8182 			      "mov $1, %[early_failure];"
8183 			      "0: lahf;"
8184 			      "movzbl %%ah, %[flags]"
8185 			      : [early_failure] "+r" (early_failure),
8186 				[flags] "=&a" (flags)
8187 			      : [host_rsp] "i" (HOST_RSP),
8188 				[host_rip] "i" (HOST_RIP)
8189 			      : "rdx", "cc", "memory");
8190 	vm_inst_err = vmcs_read(VMX_INST_ERROR);
8191 
8192 	report(early_failure, "Early VM-entry failure");
8193 	report(flags == expected_flags, "RFLAGS[8:0] is %x (actual %x)",
8194 	       expected_flags, flags);
8195 	if (valid_vmcs)
8196 		report(vm_inst_err == VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS,
8197 		       "VM-instruction error is %d (actual %d)",
8198 		       VMXERR_ENTRY_EVENTS_BLOCKED_BY_MOV_SS, vm_inst_err);
8199 }
8200 
8201 static void vmentry_movss_shadow_test(void)
8202 {
8203 	struct vmcs *orig_vmcs;
8204 
8205 	TEST_ASSERT(!vmcs_save(&orig_vmcs));
8206 
8207 	/*
8208 	 * Set the launched flag on the current VMCS to verify the correct
8209 	 * error priority, below.
8210 	 */
8211 	test_set_guest(v2_null_test_guest);
8212 	enter_guest();
8213 
8214 	/*
8215 	 * With bit 1 of the guest's RFLAGS clear, VM-entry should
8216 	 * fail due to invalid guest state (if we make it that far).
8217 	 */
8218 	vmcs_write(GUEST_RFLAGS, 0);
8219 
8220 	/*
8221 	 * "VM entry with events blocked by MOV SS" takes precedence over
8222 	 * "VMLAUNCH with non-clear VMCS."
8223 	 */
8224 	report_prefix_push("valid current-VMCS");
8225 	try_vmentry_in_movss_shadow();
8226 	report_prefix_pop();
8227 
8228 	/*
8229 	 * VMfailInvalid takes precedence over "VM entry with events
8230 	 * blocked by MOV SS."
8231 	 */
8232 	TEST_ASSERT(!vmcs_clear(orig_vmcs));
8233 	report_prefix_push("no current-VMCS");
8234 	try_vmentry_in_movss_shadow();
8235 	report_prefix_pop();
8236 
8237 	TEST_ASSERT(!make_vmcs_current(orig_vmcs));
8238 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8239 }
8240 
8241 static void vmx_ldtr_test_guest(void)
8242 {
8243 	u16 ldtr = sldt();
8244 
8245 	report(ldtr == NP_SEL, "Expected %x for L2 LDTR selector (got %x)",
8246 	       NP_SEL, ldtr);
8247 }
8248 
8249 /*
8250  * Ensure that the L1 LDTR is set to 0 on VM-exit.
8251  */
8252 static void vmx_ldtr_test(void)
8253 {
8254 	const u8 ldt_ar = 0x82; /* Present LDT */
8255 	u16 sel = FIRST_SPARE_SEL;
8256 
8257 	/* Set up a non-zero L1 LDTR prior to VM-entry. */
8258 	set_gdt_entry(sel, 0, 0, ldt_ar, 0);
8259 	lldt(sel);
8260 
8261 	test_set_guest(vmx_ldtr_test_guest);
8262 	/*
8263 	 * Set up a different LDTR for L2. The actual GDT contents are
8264 	 * irrelevant, since we stuff the hidden descriptor state
8265 	 * straight into the VMCS rather than reading it from the GDT.
8266 	 */
8267 	vmcs_write(GUEST_SEL_LDTR, NP_SEL);
8268 	vmcs_write(GUEST_AR_LDTR, ldt_ar);
8269 	enter_guest();
8270 
8271 	/*
8272 	 * VM-exit should clear LDTR (and make it unusable, but we
8273 	 * won't verify that here).
8274 	 */
8275 	sel = sldt();
8276 	report(!sel, "Expected 0 for L1 LDTR selector (got %x)", sel);
8277 }
8278 
8279 static void vmx_single_vmcall_guest(void)
8280 {
8281 	vmcall();
8282 }
8283 
8284 static void vmx_cr_load_test(void)
8285 {
8286 	unsigned long cr3, cr4, orig_cr3, orig_cr4;
8287 	u32 ctrls[2] = {0};
8288 	pgd_t *pml5;
8289 
8290 	orig_cr4 = read_cr4();
8291 	orig_cr3 = read_cr3();
8292 
8293 	if (!this_cpu_has(X86_FEATURE_PCID)) {
8294 		report_skip("%s : PCID not detected", __func__);
8295 		return;
8296 	}
8297 	if (!this_cpu_has(X86_FEATURE_MCE)) {
8298 		report_skip("%s : MCE not detected", __func__);
8299 		return;
8300 	}
8301 
8302 	TEST_ASSERT(!(orig_cr3 & X86_CR3_PCID_MASK));
8303 
8304 	/* Enable PCID for L1. */
8305 	cr4 = orig_cr4 | X86_CR4_PCIDE;
8306 	cr3 = orig_cr3 | 0x1;
8307 	TEST_ASSERT(!write_cr4_safe(cr4));
8308 	write_cr3(cr3);
8309 
8310 	test_set_guest(vmx_single_vmcall_guest);
8311 	vmcs_write(HOST_CR4, cr4);
8312 	vmcs_write(HOST_CR3, cr3);
8313 	enter_guest();
8314 
8315 	/*
8316 	 * No exception is expected.
8317 	 *
8318 	 * NB. KVM loads the last guest write to CR4 into CR4 read
8319 	 *     shadow. In order to trigger an exit to KVM, we can toggle a
8320 	 *     bit that is owned by KVM. We use CR4.MCE, which shall
8321 	 *     have no side effect because normally no guest MCE (e.g., as the
8322 	 *     result of bad memory) would happen during this test.
8323 	 */
8324 	TEST_ASSERT(!write_cr4_safe(cr4 ^ X86_CR4_MCE));
8325 
8326 	/* Cleanup L1 state. */
8327 	write_cr3(orig_cr3);
8328 	TEST_ASSERT(!write_cr4_safe(orig_cr4));
8329 
8330 	if (!this_cpu_has(X86_FEATURE_LA57))
8331 		goto done;
8332 
8333 	/*
8334 	 * Allocate a full page for PML5 to guarantee alignment, though only
8335 	 * the first entry needs to be filled (the test's virtual addresses
8336 	 * most definitely do not have any of bits 56:48 set).
8337 	 */
8338 	pml5 = alloc_page();
8339 	*pml5 = orig_cr3 | PT_PRESENT_MASK | PT_WRITABLE_MASK;
8340 
8341 	/*
8342 	 * Transition to/from 5-level paging in the host via VM-Exit.  CR4.LA57
8343 	 * can't be toggled while long is active via MOV CR4, but there are no
8344 	 * such restrictions on VM-Exit.
8345 	 */
8346 lol_5level:
8347 	vmcs_write(HOST_CR4, orig_cr4 | X86_CR4_LA57);
8348 	vmcs_write(HOST_CR3, virt_to_phys(pml5));
8349 	enter_guest();
8350 
8351 	/*
8352 	 * VMREAD with a memory operand to verify KVM detects the LA57 change,
8353 	 * e.g. uses the correct guest root level in gva_to_gpa().
8354 	 */
8355 	TEST_ASSERT(vmcs_readm(HOST_CR3) == virt_to_phys(pml5));
8356 	TEST_ASSERT(vmcs_readm(HOST_CR4) == (orig_cr4 | X86_CR4_LA57));
8357 
8358 	vmcs_write(HOST_CR4, orig_cr4);
8359 	vmcs_write(HOST_CR3, orig_cr3);
8360 	enter_guest();
8361 
8362 	TEST_ASSERT(vmcs_readm(HOST_CR3) == orig_cr3);
8363 	TEST_ASSERT(vmcs_readm(HOST_CR4) == orig_cr4);
8364 
8365 	/*
8366 	 * And now do the same LA57 shenanigans with EPT enabled.  KVM uses
8367 	 * two separate MMUs when L1 uses TDP, whereas the above shadow paging
8368 	 * version shares an MMU between L1 and L2.
8369 	 *
8370 	 * If the saved execution controls are non-zero then the EPT version
8371 	 * has already run.  In that case, restore the old controls.  If EPT
8372 	 * setup fails, e.g. EPT isn't supported, fall through and finish up.
8373 	 */
8374 	if (ctrls[0]) {
8375 		vmcs_write(CPU_EXEC_CTRL0, ctrls[0]);
8376 		vmcs_write(CPU_EXEC_CTRL1, ctrls[1]);
8377 	} else if (!setup_ept(false)) {
8378 		ctrls[0] = vmcs_read(CPU_EXEC_CTRL0);
8379 		ctrls[1]  = vmcs_read(CPU_EXEC_CTRL1);
8380 		goto lol_5level;
8381 	}
8382 
8383 	free_page(pml5);
8384 
8385 done:
8386 	skip_exit_vmcall();
8387 	enter_guest();
8388 }
8389 
8390 static void vmx_cr4_osxsave_test_guest(void)
8391 {
8392 	write_cr4(read_cr4() & ~X86_CR4_OSXSAVE);
8393 }
8394 
8395 /*
8396  * Ensure that kvm recalculates the L1 guest's CPUID.01H:ECX.OSXSAVE
8397  * after VM-exit from an L2 guest that sets CR4.OSXSAVE to a different
8398  * value than in L1.
8399  */
8400 static void vmx_cr4_osxsave_test(void)
8401 {
8402 	if (!this_cpu_has(X86_FEATURE_XSAVE)) {
8403 		report_skip("%s : XSAVE not detected", __func__);
8404 		return;
8405 	}
8406 
8407 	if (!(read_cr4() & X86_CR4_OSXSAVE)) {
8408 		unsigned long cr4 = read_cr4() | X86_CR4_OSXSAVE;
8409 
8410 		write_cr4(cr4);
8411 		vmcs_write(GUEST_CR4, cr4);
8412 		vmcs_write(HOST_CR4, cr4);
8413 	}
8414 
8415 	TEST_ASSERT(this_cpu_has(X86_FEATURE_OSXSAVE));
8416 
8417 	test_set_guest(vmx_cr4_osxsave_test_guest);
8418 	enter_guest();
8419 
8420 	TEST_ASSERT(this_cpu_has(X86_FEATURE_OSXSAVE));
8421 }
8422 
8423 /*
8424  * FNOP with both CR0.TS and CR0.EM clear should not generate #NM, and the L2
8425  * guest should exit normally.
8426  */
8427 static void vmx_no_nm_test(void)
8428 {
8429 	test_set_guest(fnop);
8430 	vmcs_write(GUEST_CR0, read_cr0() & ~(X86_CR0_TS | X86_CR0_EM));
8431 	enter_guest();
8432 }
8433 
8434 bool vmx_pending_event_ipi_fired;
8435 static void vmx_pending_event_ipi_isr(isr_regs_t *regs)
8436 {
8437 	vmx_pending_event_ipi_fired = true;
8438 	eoi();
8439 }
8440 
8441 bool vmx_pending_event_guest_run;
8442 static void vmx_pending_event_guest(void)
8443 {
8444 	vmcall();
8445 	vmx_pending_event_guest_run = true;
8446 }
8447 
8448 static void vmx_pending_event_test_core(bool guest_hlt)
8449 {
8450 	int ipi_vector = 0xf1;
8451 
8452 	vmx_pending_event_ipi_fired = false;
8453 	handle_irq(ipi_vector, vmx_pending_event_ipi_isr);
8454 
8455 	vmx_pending_event_guest_run = false;
8456 	test_set_guest(vmx_pending_event_guest);
8457 
8458 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
8459 
8460 	enter_guest();
8461 	skip_exit_vmcall();
8462 
8463 	if (guest_hlt)
8464 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8465 
8466 	cli();
8467 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
8468 				   APIC_DM_FIXED | ipi_vector,
8469 				   0);
8470 
8471 	enter_guest();
8472 
8473 	assert_exit_reason(VMX_EXTINT);
8474 	report(!vmx_pending_event_guest_run,
8475 	       "Guest did not run before host received IPI");
8476 
8477 	sti_nop_cli();
8478 	report(vmx_pending_event_ipi_fired,
8479 	       "Got pending interrupt after IRQ enabled");
8480 
8481 	if (guest_hlt)
8482 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8483 
8484 	enter_guest();
8485 	report(vmx_pending_event_guest_run,
8486 	       "Guest finished running when no interrupt");
8487 }
8488 
8489 static void vmx_pending_event_test(void)
8490 {
8491 	vmx_pending_event_test_core(false);
8492 }
8493 
8494 static void vmx_pending_event_hlt_test(void)
8495 {
8496 	vmx_pending_event_test_core(true);
8497 }
8498 
8499 static int vmx_window_test_db_count;
8500 
8501 static void vmx_window_test_db_handler(struct ex_regs *regs)
8502 {
8503 	vmx_window_test_db_count++;
8504 }
8505 
8506 static void vmx_nmi_window_test_guest(void)
8507 {
8508 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
8509 
8510 	asm volatile("vmcall\n\t"
8511 		     "nop\n\t");
8512 
8513 	handle_exception(DB_VECTOR, NULL);
8514 }
8515 
8516 static void verify_nmi_window_exit(u64 rip)
8517 {
8518 	u32 exit_reason = vmcs_read(EXI_REASON);
8519 
8520 	report(exit_reason == VMX_NMI_WINDOW,
8521 	       "Exit reason (%d) is 'NMI window'", exit_reason);
8522 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8523 	       vmcs_read(GUEST_RIP), rip);
8524 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8525 }
8526 
8527 static void vmx_nmi_window_test(void)
8528 {
8529 	u64 nop_addr;
8530 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8531 
8532 	if (!(ctrl_pin_rev.clr & PIN_VIRT_NMI)) {
8533 		report_skip("%s : \"Virtual NMIs\" exec control not supported", __func__);
8534 		return;
8535 	}
8536 
8537 	if (!(ctrl_cpu_rev[0].clr & CPU_NMI_WINDOW)) {
8538 		report_skip("%s : \"NMI-window exiting\" exec control not supported", __func__);
8539 		return;
8540 	}
8541 
8542 	vmx_window_test_db_count = 0;
8543 
8544 	report_prefix_push("NMI-window");
8545 	test_set_guest(vmx_nmi_window_test_guest);
8546 	vmcs_set_bits(PIN_CONTROLS, PIN_VIRT_NMI);
8547 	enter_guest();
8548 	skip_exit_vmcall();
8549 	nop_addr = vmcs_read(GUEST_RIP);
8550 
8551 	/*
8552 	 * Ask for "NMI-window exiting," and expect an immediate VM-exit.
8553 	 * RIP will not advance.
8554 	 */
8555 	report_prefix_push("active, no blocking");
8556 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8557 	enter_guest();
8558 	verify_nmi_window_exit(nop_addr);
8559 	report_prefix_pop();
8560 
8561 	/*
8562 	 * Ask for "NMI-window exiting" in a MOV-SS shadow, and expect
8563 	 * a VM-exit on the next instruction after the nop. (The nop
8564 	 * is one byte.)
8565 	 */
8566 	report_prefix_push("active, blocking by MOV-SS");
8567 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8568 	enter_guest();
8569 	verify_nmi_window_exit(nop_addr + 1);
8570 	report_prefix_pop();
8571 
8572 	/*
8573 	 * Ask for "NMI-window exiting" (with event injection), and
8574 	 * expect a VM-exit after the event is injected. (RIP should
8575 	 * be at the address specified in the IDT entry for #DB.)
8576 	 */
8577 	report_prefix_push("active, no blocking, injecting #DB");
8578 	vmcs_write(ENT_INTR_INFO,
8579 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8580 	enter_guest();
8581 	verify_nmi_window_exit((u64)db_fault_addr);
8582 	report_prefix_pop();
8583 
8584 	/*
8585 	 * Ask for "NMI-window exiting" with NMI blocking, and expect
8586 	 * a VM-exit after the next IRET (i.e. after the #DB handler
8587 	 * returns). So, RIP should be back at one byte past the nop.
8588 	 */
8589 	report_prefix_push("active, blocking by NMI");
8590 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_NMI);
8591 	enter_guest();
8592 	verify_nmi_window_exit(nop_addr + 1);
8593 	report(vmx_window_test_db_count == 1,
8594 	       "#DB handler executed once (actual %d times)",
8595 	       vmx_window_test_db_count);
8596 	report_prefix_pop();
8597 
8598 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8599 		report_skip("CPU does not support activity state HLT.");
8600 	} else {
8601 		/*
8602 		 * Ask for "NMI-window exiting" when entering activity
8603 		 * state HLT, and expect an immediate VM-exit. RIP is
8604 		 * still one byte past the nop.
8605 		 */
8606 		report_prefix_push("halted, no blocking");
8607 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8608 		enter_guest();
8609 		verify_nmi_window_exit(nop_addr + 1);
8610 		report_prefix_pop();
8611 
8612 		/*
8613 		 * Ask for "NMI-window exiting" when entering activity
8614 		 * state HLT (with event injection), and expect a
8615 		 * VM-exit after the event is injected. (RIP should be
8616 		 * at the address specified in the IDT entry for #DB.)
8617 		 */
8618 		report_prefix_push("halted, no blocking, injecting #DB");
8619 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8620 		vmcs_write(ENT_INTR_INFO,
8621 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8622 			   DB_VECTOR);
8623 		enter_guest();
8624 		verify_nmi_window_exit((u64)db_fault_addr);
8625 		report_prefix_pop();
8626 	}
8627 
8628 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_NMI_WINDOW);
8629 	enter_guest();
8630 	report_prefix_pop();
8631 }
8632 
8633 static void vmx_intr_window_test_guest(void)
8634 {
8635 	handle_exception(DB_VECTOR, vmx_window_test_db_handler);
8636 
8637 	/*
8638 	 * The two consecutive STIs are to ensure that only the first
8639 	 * one has a shadow. Note that NOP and STI are one byte
8640 	 * instructions.
8641 	 */
8642 	asm volatile("vmcall\n\t"
8643 		     "nop\n\t"
8644 		     "sti\n\t"
8645 		     "sti\n\t");
8646 
8647 	handle_exception(DB_VECTOR, NULL);
8648 }
8649 
8650 static void verify_intr_window_exit(u64 rip)
8651 {
8652 	u32 exit_reason = vmcs_read(EXI_REASON);
8653 
8654 	report(exit_reason == VMX_INTR_WINDOW,
8655 	       "Exit reason (%d) is 'interrupt window'", exit_reason);
8656 	report(vmcs_read(GUEST_RIP) == rip, "RIP (%#lx) is %#lx",
8657 	       vmcs_read(GUEST_RIP), rip);
8658 	vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
8659 }
8660 
8661 static void vmx_intr_window_test(void)
8662 {
8663 	u64 vmcall_addr;
8664 	u64 nop_addr;
8665 	unsigned int orig_db_gate_type;
8666 	void *db_fault_addr = get_idt_addr(&boot_idt[DB_VECTOR]);
8667 
8668 	if (!(ctrl_cpu_rev[0].clr & CPU_INTR_WINDOW)) {
8669 		report_skip("%s : \"Interrupt-window exiting\" exec control not supported", __func__);
8670 		return;
8671 	}
8672 
8673 	/*
8674 	 * Change the IDT entry for #DB from interrupt gate to trap gate,
8675 	 * so that it won't clear RFLAGS.IF. We don't want interrupts to
8676 	 * be disabled after vectoring a #DB.
8677 	 */
8678 	orig_db_gate_type = boot_idt[DB_VECTOR].type;
8679 	boot_idt[DB_VECTOR].type = 15;
8680 
8681 	report_prefix_push("interrupt-window");
8682 	test_set_guest(vmx_intr_window_test_guest);
8683 	enter_guest();
8684 	assert_exit_reason(VMX_VMCALL);
8685 	vmcall_addr = vmcs_read(GUEST_RIP);
8686 
8687 	/*
8688 	 * Ask for "interrupt-window exiting" with RFLAGS.IF set and
8689 	 * no blocking; expect an immediate VM-exit. Note that we have
8690 	 * not advanced past the vmcall instruction yet, so RIP should
8691 	 * point to the vmcall instruction.
8692 	 */
8693 	report_prefix_push("active, no blocking, RFLAGS.IF=1");
8694 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8695 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_IF);
8696 	enter_guest();
8697 	verify_intr_window_exit(vmcall_addr);
8698 	report_prefix_pop();
8699 
8700 	/*
8701 	 * Ask for "interrupt-window exiting" (with event injection)
8702 	 * with RFLAGS.IF set and no blocking; expect a VM-exit after
8703 	 * the event is injected. That is, RIP should should be at the
8704 	 * address specified in the IDT entry for #DB.
8705 	 */
8706 	report_prefix_push("active, no blocking, RFLAGS.IF=1, injecting #DB");
8707 	vmcs_write(ENT_INTR_INFO,
8708 		   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8709 	vmcall_addr = vmcs_read(GUEST_RIP);
8710 	enter_guest();
8711 	verify_intr_window_exit((u64)db_fault_addr);
8712 	report_prefix_pop();
8713 
8714 	/*
8715 	 * Let the L2 guest run through the IRET, back to the VMCALL.
8716 	 * We have to clear the "interrupt-window exiting"
8717 	 * VM-execution control, or it would just keep causing
8718 	 * VM-exits. Then, advance past the VMCALL and set the
8719 	 * "interrupt-window exiting" VM-execution control again.
8720 	 */
8721 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8722 	enter_guest();
8723 	skip_exit_vmcall();
8724 	nop_addr = vmcs_read(GUEST_RIP);
8725 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8726 
8727 	/*
8728 	 * Ask for "interrupt-window exiting" in a MOV-SS shadow with
8729 	 * RFLAGS.IF set, and expect a VM-exit on the next
8730 	 * instruction. (NOP is one byte.)
8731 	 */
8732 	report_prefix_push("active, blocking by MOV-SS, RFLAGS.IF=1");
8733 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
8734 	enter_guest();
8735 	verify_intr_window_exit(nop_addr + 1);
8736 	report_prefix_pop();
8737 
8738 	/*
8739 	 * Back up to the NOP and ask for "interrupt-window exiting"
8740 	 * in an STI shadow with RFLAGS.IF set, and expect a VM-exit
8741 	 * on the next instruction. (NOP is one byte.)
8742 	 */
8743 	report_prefix_push("active, blocking by STI, RFLAGS.IF=1");
8744 	vmcs_write(GUEST_RIP, nop_addr);
8745 	vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_STI);
8746 	enter_guest();
8747 	verify_intr_window_exit(nop_addr + 1);
8748 	report_prefix_pop();
8749 
8750 	/*
8751 	 * Ask for "interrupt-window exiting" with RFLAGS.IF clear,
8752 	 * and expect a VM-exit on the instruction following the STI
8753 	 * shadow. Only the first STI (which is one byte past the NOP)
8754 	 * should have a shadow. The second STI (which is two bytes
8755 	 * past the NOP) has no shadow. Therefore, the interrupt
8756 	 * window opens at three bytes past the NOP.
8757 	 */
8758 	report_prefix_push("active, RFLAGS.IF = 0");
8759 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
8760 	enter_guest();
8761 	verify_intr_window_exit(nop_addr + 3);
8762 	report_prefix_pop();
8763 
8764 	if (!(rdmsr(MSR_IA32_VMX_MISC) & (1 << 6))) {
8765 		report_skip("CPU does not support activity state HLT.");
8766 	} else {
8767 		/*
8768 		 * Ask for "interrupt-window exiting" when entering
8769 		 * activity state HLT, and expect an immediate
8770 		 * VM-exit. RIP is still three bytes past the nop.
8771 		 */
8772 		report_prefix_push("halted, no blocking");
8773 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8774 		enter_guest();
8775 		verify_intr_window_exit(nop_addr + 3);
8776 		report_prefix_pop();
8777 
8778 		/*
8779 		 * Ask for "interrupt-window exiting" when entering
8780 		 * activity state HLT (with event injection), and
8781 		 * expect a VM-exit after the event is injected. That
8782 		 * is, RIP should should be at the address specified
8783 		 * in the IDT entry for #DB.
8784 		 */
8785 		report_prefix_push("halted, no blocking, injecting #DB");
8786 		vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
8787 		vmcs_write(ENT_INTR_INFO,
8788 			   INTR_INFO_VALID_MASK | INTR_TYPE_HARD_EXCEPTION |
8789 			   DB_VECTOR);
8790 		enter_guest();
8791 		verify_intr_window_exit((u64)db_fault_addr);
8792 		report_prefix_pop();
8793 	}
8794 
8795 	boot_idt[DB_VECTOR].type = orig_db_gate_type;
8796 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INTR_WINDOW);
8797 	enter_guest();
8798 	report_prefix_pop();
8799 }
8800 
8801 #define GUEST_TSC_OFFSET (1u << 30)
8802 
8803 static u64 guest_tsc;
8804 
8805 static void vmx_store_tsc_test_guest(void)
8806 {
8807 	guest_tsc = rdtsc();
8808 }
8809 
8810 /*
8811  * This test ensures that when IA32_TSC is in the VM-exit MSR-store
8812  * list, the value saved is not subject to the TSC offset that is
8813  * applied to RDTSC/RDTSCP/RDMSR(IA32_TSC) in guest execution.
8814  */
8815 static void vmx_store_tsc_test(void)
8816 {
8817 	struct vmx_msr_entry msr_entry = { .index = MSR_IA32_TSC };
8818 	u64 low, high;
8819 
8820 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET)) {
8821 		report_skip("%s : \"Use TSC offsetting\" exec control not supported", __func__);
8822 		return;
8823 	}
8824 
8825 	test_set_guest(vmx_store_tsc_test_guest);
8826 
8827 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
8828 	vmcs_write(EXI_MSR_ST_CNT, 1);
8829 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(&msr_entry));
8830 	vmcs_write(TSC_OFFSET, GUEST_TSC_OFFSET);
8831 
8832 	low = rdtsc();
8833 	enter_guest();
8834 	high = rdtsc();
8835 
8836 	report(low + GUEST_TSC_OFFSET <= guest_tsc &&
8837 	       guest_tsc <= high + GUEST_TSC_OFFSET,
8838 	       "RDTSC value in the guest (%lu) is in range [%lu, %lu]",
8839 	       guest_tsc, low + GUEST_TSC_OFFSET, high + GUEST_TSC_OFFSET);
8840 	report(low <= msr_entry.value && msr_entry.value <= high,
8841 	       "IA32_TSC value saved in the VM-exit MSR-store list (%lu) is in range [%lu, %lu]",
8842 	       msr_entry.value, low, high);
8843 }
8844 
8845 static void vmx_preemption_timer_zero_test_db_handler(struct ex_regs *regs)
8846 {
8847 }
8848 
8849 static void vmx_preemption_timer_zero_test_guest(void)
8850 {
8851 	while (vmx_get_test_stage() < 3)
8852 		vmcall();
8853 }
8854 
8855 static void vmx_preemption_timer_zero_activate_preemption_timer(void)
8856 {
8857 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
8858 	vmcs_write(PREEMPT_TIMER_VALUE, 0);
8859 }
8860 
8861 static void vmx_preemption_timer_zero_advance_past_vmcall(void)
8862 {
8863 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8864 	enter_guest();
8865 	skip_exit_vmcall();
8866 }
8867 
8868 static void vmx_preemption_timer_zero_inject_db(bool intercept_db)
8869 {
8870 	vmx_preemption_timer_zero_activate_preemption_timer();
8871 	vmcs_write(ENT_INTR_INFO, INTR_INFO_VALID_MASK |
8872 		   INTR_TYPE_HARD_EXCEPTION | DB_VECTOR);
8873 	vmcs_write(EXC_BITMAP, intercept_db ? 1 << DB_VECTOR : 0);
8874 	enter_guest();
8875 }
8876 
8877 static void vmx_preemption_timer_zero_set_pending_dbg(u32 exception_bitmap)
8878 {
8879 	vmx_preemption_timer_zero_activate_preemption_timer();
8880 	vmcs_write(GUEST_PENDING_DEBUG, PENDING_DBG_TRAP | DR6_TRAP1);
8881 	vmcs_write(EXC_BITMAP, exception_bitmap);
8882 	enter_guest();
8883 }
8884 
8885 static void vmx_preemption_timer_zero_expect_preempt_at_rip(u64 expected_rip)
8886 {
8887 	u32 reason = (u32)vmcs_read(EXI_REASON);
8888 	u64 guest_rip = vmcs_read(GUEST_RIP);
8889 
8890 	report(reason == VMX_PREEMPT && guest_rip == expected_rip,
8891 	       "Exit reason is 0x%x (expected 0x%x) and guest RIP is %lx (0x%lx expected).",
8892 	       reason, VMX_PREEMPT, guest_rip, expected_rip);
8893 }
8894 
8895 /*
8896  * This test ensures that when the VMX preemption timer is zero at
8897  * VM-entry, a VM-exit occurs after any event injection and after any
8898  * pending debug exceptions are raised, but before execution of any
8899  * guest instructions.
8900  */
8901 static void vmx_preemption_timer_zero_test(void)
8902 {
8903 	u64 db_fault_address = (u64)get_idt_addr(&boot_idt[DB_VECTOR]);
8904 	handler old_db;
8905 	u32 reason;
8906 
8907 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
8908 		report_skip("%s : \"Activate VMX-preemption timer\" pin control not supported", __func__);
8909 		return;
8910 	}
8911 
8912 	/*
8913 	 * Install a custom #DB handler that doesn't abort.
8914 	 */
8915 	old_db = handle_exception(DB_VECTOR,
8916 				  vmx_preemption_timer_zero_test_db_handler);
8917 
8918 	test_set_guest(vmx_preemption_timer_zero_test_guest);
8919 
8920 	/*
8921 	 * VMX-preemption timer should fire after event injection.
8922 	 */
8923 	vmx_set_test_stage(0);
8924 	vmx_preemption_timer_zero_inject_db(0);
8925 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8926 	vmx_preemption_timer_zero_advance_past_vmcall();
8927 
8928 	/*
8929 	 * VMX-preemption timer should fire after event injection.
8930 	 * Exception bitmap is irrelevant, since you can't intercept
8931 	 * an event that you injected.
8932 	 */
8933 	vmx_set_test_stage(1);
8934 	vmx_preemption_timer_zero_inject_db(true);
8935 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8936 	vmx_preemption_timer_zero_advance_past_vmcall();
8937 
8938 	/*
8939 	 * VMX-preemption timer should fire after pending debug exceptions
8940 	 * have delivered a #DB trap.
8941 	 */
8942 	vmx_set_test_stage(2);
8943 	vmx_preemption_timer_zero_set_pending_dbg(0);
8944 	vmx_preemption_timer_zero_expect_preempt_at_rip(db_fault_address);
8945 	vmx_preemption_timer_zero_advance_past_vmcall();
8946 
8947 	/*
8948 	 * VMX-preemption timer would fire after pending debug exceptions
8949 	 * have delivered a #DB trap, but in this case, the #DB trap is
8950 	 * intercepted.
8951 	 */
8952 	vmx_set_test_stage(3);
8953 	vmx_preemption_timer_zero_set_pending_dbg(1 << DB_VECTOR);
8954 	reason = (u32)vmcs_read(EXI_REASON);
8955 	report(reason == VMX_EXC_NMI, "Exit reason is 0x%x (expected 0x%x)",
8956 	       reason, VMX_EXC_NMI);
8957 
8958 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
8959 	enter_guest();
8960 
8961 	handle_exception(DB_VECTOR, old_db);
8962 }
8963 
8964 static u64 vmx_preemption_timer_tf_test_prev_rip;
8965 
8966 static void vmx_preemption_timer_tf_test_db_handler(struct ex_regs *regs)
8967 {
8968 	extern char vmx_preemption_timer_tf_test_endloop;
8969 
8970 	if (vmx_get_test_stage() == 2) {
8971 		/*
8972 		 * Stage 2 means that we're done, one way or another.
8973 		 * Arrange for the iret to drop us out of the wbinvd
8974 		 * loop and stop single-stepping.
8975 		 */
8976 		regs->rip = (u64)&vmx_preemption_timer_tf_test_endloop;
8977 		regs->rflags &= ~X86_EFLAGS_TF;
8978 	} else if (regs->rip == vmx_preemption_timer_tf_test_prev_rip) {
8979 		/*
8980 		 * The RIP should alternate between the wbinvd and the
8981 		 * jmp instruction in the code below. If we ever see
8982 		 * the same instruction twice in a row, that means a
8983 		 * single-step trap has been dropped. Let the
8984 		 * hypervisor know about the failure by executing a
8985 		 * VMCALL.
8986 		 */
8987 		vmcall();
8988 	}
8989 	vmx_preemption_timer_tf_test_prev_rip = regs->rip;
8990 }
8991 
8992 static void vmx_preemption_timer_tf_test_guest(void)
8993 {
8994 	/*
8995 	 * The hypervisor doesn't intercept WBINVD, so the loop below
8996 	 * shouldn't be a problem--it's just two instructions
8997 	 * executing in VMX non-root mode. However, when the
8998 	 * hypervisor is running in a virtual environment, the parent
8999 	 * hypervisor might intercept WBINVD and emulate it. If the
9000 	 * parent hypervisor is broken, the single-step trap after the
9001 	 * WBINVD might be lost.
9002 	 */
9003 	asm volatile("vmcall\n\t"
9004 		     "0: wbinvd\n\t"
9005 		     "1: jmp 0b\n\t"
9006 		     "vmx_preemption_timer_tf_test_endloop:");
9007 }
9008 
9009 /*
9010  * Ensure that the delivery of a "VMX-preemption timer expired"
9011  * VM-exit doesn't disrupt single-stepping in the guest. Note that
9012  * passing this test doesn't ensure correctness, because the test will
9013  * only fail if the VMX-preemtion timer fires at the right time (or
9014  * the wrong time, as it were).
9015  */
9016 static void vmx_preemption_timer_tf_test(void)
9017 {
9018 	handler old_db;
9019 	u32 reason;
9020 	int i;
9021 
9022 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
9023 		report_skip("%s : \"Activate VMX-preemption timer\" pin control not supported", __func__);
9024 		return;
9025 	}
9026 
9027 	old_db = handle_exception(DB_VECTOR,
9028 				  vmx_preemption_timer_tf_test_db_handler);
9029 
9030 	test_set_guest(vmx_preemption_timer_tf_test_guest);
9031 
9032 	enter_guest();
9033 	skip_exit_vmcall();
9034 
9035 	vmx_set_test_stage(1);
9036 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
9037 	vmcs_write(PREEMPT_TIMER_VALUE, 50000);
9038 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
9039 
9040 	/*
9041 	 * The only exit we should see is "VMX-preemption timer
9042 	 * expired."  If we get a VMCALL exit, that means the #DB
9043 	 * handler has detected a missing single-step trap. It doesn't
9044 	 * matter where the guest RIP is when the VMX-preemption timer
9045 	 * expires (whether it's in the WBINVD loop or in the #DB
9046 	 * handler)--a single-step trap should never be discarded.
9047 	 */
9048 	for (i = 0; i < 10000; i++) {
9049 		enter_guest();
9050 		reason = (u32)vmcs_read(EXI_REASON);
9051 		if (reason == VMX_PREEMPT)
9052 			continue;
9053 		TEST_ASSERT(reason == VMX_VMCALL);
9054 		skip_exit_insn();
9055 		break;
9056 	}
9057 
9058 	report(reason == VMX_PREEMPT, "No single-step traps skipped");
9059 
9060 	vmx_set_test_stage(2);
9061 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
9062 	enter_guest();
9063 
9064 	handle_exception(DB_VECTOR, old_db);
9065 }
9066 
9067 #define VMX_PREEMPTION_TIMER_EXPIRY_CYCLES 1000000
9068 
9069 static u64 vmx_preemption_timer_expiry_start;
9070 static u64 vmx_preemption_timer_expiry_finish;
9071 
9072 static void vmx_preemption_timer_expiry_test_guest(void)
9073 {
9074 	vmcall();
9075 	vmx_preemption_timer_expiry_start = fenced_rdtsc();
9076 
9077 	while (vmx_get_test_stage() == 0)
9078 		vmx_preemption_timer_expiry_finish = fenced_rdtsc();
9079 }
9080 
9081 /*
9082  * Test that the VMX-preemption timer is not excessively delayed.
9083  *
9084  * Per the SDM, volume 3, VM-entry starts the VMX-preemption timer
9085  * with the unsigned value in the VMX-preemption timer-value field,
9086  * and the VMX-preemption timer counts down by 1 every time bit X in
9087  * the TSC changes due to a TSC increment (where X is
9088  * IA32_VMX_MISC[4:0]). If the timer counts down to zero in any state
9089  * other than the wait-for-SIPI state, the logical processor
9090  * transitions to the C0 C-state and causes a VM-exit.
9091  *
9092  * The guest code above reads the starting TSC after VM-entry. At this
9093  * point, the VMX-preemption timer has already been activated. Next,
9094  * the guest code reads the current TSC in a loop, storing the value
9095  * read to memory.
9096  *
9097  * If the RDTSC in the loop reads a value past the VMX-preemption
9098  * timer deadline, then the VMX-preemption timer VM-exit must be
9099  * delivered before the next instruction retires. Even if a higher
9100  * priority SMI is delivered first, the VMX-preemption timer VM-exit
9101  * must be delivered before the next instruction retires. Hence, a TSC
9102  * value past the VMX-preemption timer deadline might be read, but it
9103  * cannot be stored. If a TSC value past the deadline *is* stored,
9104  * then the architectural specification has been violated.
9105  */
9106 static void vmx_preemption_timer_expiry_test(void)
9107 {
9108 	u32 preemption_timer_value;
9109 	union vmx_misc misc;
9110 	u64 tsc_deadline;
9111 	u32 reason;
9112 
9113 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
9114 		report_skip("%s : \"Activate VMX-preemption timer\" pin control not supported", __func__);
9115 		return;
9116 	}
9117 
9118 	test_set_guest(vmx_preemption_timer_expiry_test_guest);
9119 
9120 	enter_guest();
9121 	skip_exit_vmcall();
9122 
9123 	misc.val = rdmsr(MSR_IA32_VMX_MISC);
9124 	preemption_timer_value =
9125 		VMX_PREEMPTION_TIMER_EXPIRY_CYCLES >> misc.pt_bit;
9126 
9127 	vmcs_set_bits(PIN_CONTROLS, PIN_PREEMPT);
9128 	vmcs_write(PREEMPT_TIMER_VALUE, preemption_timer_value);
9129 	vmx_set_test_stage(0);
9130 
9131 	enter_guest();
9132 	reason = (u32)vmcs_read(EXI_REASON);
9133 	TEST_ASSERT(reason == VMX_PREEMPT);
9134 
9135 	tsc_deadline = ((vmx_preemption_timer_expiry_start >> misc.pt_bit) <<
9136 			misc.pt_bit) + (preemption_timer_value << misc.pt_bit);
9137 
9138 	report(vmx_preemption_timer_expiry_finish < tsc_deadline,
9139 	       "Last stored guest TSC (%lu) < TSC deadline (%lu)",
9140 	       vmx_preemption_timer_expiry_finish, tsc_deadline);
9141 
9142 	vmcs_clear_bits(PIN_CONTROLS, PIN_PREEMPT);
9143 	vmx_set_test_stage(1);
9144 	enter_guest();
9145 }
9146 
9147 static void vmx_db_test_guest(void)
9148 {
9149 	/*
9150 	 * For a hardware generated single-step #DB.
9151 	 */
9152 	asm volatile("vmcall;"
9153 		     "nop;"
9154 		     ".Lpost_nop:");
9155 	/*
9156 	 * ...in a MOVSS shadow, with pending debug exceptions.
9157 	 */
9158 	asm volatile("vmcall;"
9159 		     "nop;"
9160 		     ".Lpost_movss_nop:");
9161 	/*
9162 	 * For an L0 synthesized single-step #DB. (L0 intercepts WBINVD and
9163 	 * emulates it in software.)
9164 	 */
9165 	asm volatile("vmcall;"
9166 		     "wbinvd;"
9167 		     ".Lpost_wbinvd:");
9168 	/*
9169 	 * ...in a MOVSS shadow, with pending debug exceptions.
9170 	 */
9171 	asm volatile("vmcall;"
9172 		     "wbinvd;"
9173 		     ".Lpost_movss_wbinvd:");
9174 	/*
9175 	 * For a hardware generated single-step #DB in a transactional region.
9176 	 */
9177 	asm volatile("vmcall;"
9178 		     ".Lxbegin: xbegin .Lskip_rtm;"
9179 		     "xend;"
9180 		     ".Lskip_rtm:");
9181 }
9182 
9183 /*
9184  * Clear the pending debug exceptions and RFLAGS.TF and re-enter
9185  * L2. No #DB is delivered and L2 continues to the next point of
9186  * interest.
9187  */
9188 static void dismiss_db(void)
9189 {
9190 	vmcs_write(GUEST_PENDING_DEBUG, 0);
9191 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED);
9192 	enter_guest();
9193 }
9194 
9195 /*
9196  * Check a variety of VMCS fields relevant to an intercepted #DB exception.
9197  * Then throw away the #DB exception and resume L2.
9198  */
9199 static void check_db_exit(bool xfail_qual, bool xfail_dr6, bool xfail_pdbg,
9200 			  void *expected_rip, u64 expected_exit_qual,
9201 			  u64 expected_dr6)
9202 {
9203 	u32 reason = vmcs_read(EXI_REASON);
9204 	u32 intr_info = vmcs_read(EXI_INTR_INFO);
9205 	u64 exit_qual = vmcs_read(EXI_QUALIFICATION);
9206 	u64 guest_rip = vmcs_read(GUEST_RIP);
9207 	u64 guest_pending_dbg = vmcs_read(GUEST_PENDING_DEBUG);
9208 	u64 dr6 = read_dr6();
9209 	const u32 expected_intr_info = INTR_INFO_VALID_MASK |
9210 		INTR_TYPE_HARD_EXCEPTION | DB_VECTOR;
9211 
9212 	report(reason == VMX_EXC_NMI && intr_info == expected_intr_info,
9213 	       "Expected #DB VM-exit");
9214 	report((u64)expected_rip == guest_rip, "Expected RIP %p (actual %lx)",
9215 	       expected_rip, guest_rip);
9216 	report_xfail(xfail_pdbg, 0 == guest_pending_dbg,
9217 		     "Expected pending debug exceptions 0 (actual %lx)",
9218 		     guest_pending_dbg);
9219 	report_xfail(xfail_qual, expected_exit_qual == exit_qual,
9220 		     "Expected exit qualification %lx (actual %lx)",
9221 		     expected_exit_qual, exit_qual);
9222 	report_xfail(xfail_dr6, expected_dr6 == dr6,
9223 		     "Expected DR6 %lx (actual %lx)", expected_dr6, dr6);
9224 	dismiss_db();
9225 }
9226 
9227 /*
9228  * Assuming the guest has just exited on a VMCALL instruction, skip
9229  * over the vmcall, and set the guest's RFLAGS.TF in the VMCS. If
9230  * pending debug exceptions are non-zero, set the VMCS up as if the
9231  * previous instruction was a MOVSS that generated the indicated
9232  * pending debug exceptions. Then enter L2.
9233  */
9234 static void single_step_guest(const char *test_name, u64 starting_dr6,
9235 			      u64 pending_debug_exceptions)
9236 {
9237 	printf("\n%s\n", test_name);
9238 	skip_exit_vmcall();
9239 	write_dr6(starting_dr6);
9240 	vmcs_write(GUEST_RFLAGS, X86_EFLAGS_FIXED | X86_EFLAGS_TF);
9241 	if (pending_debug_exceptions) {
9242 		vmcs_write(GUEST_PENDING_DEBUG, pending_debug_exceptions);
9243 		vmcs_write(GUEST_INTR_STATE, GUEST_INTR_STATE_MOVSS);
9244 	}
9245 	enter_guest();
9246 }
9247 
9248 /*
9249  * When L1 intercepts #DB, verify that a single-step trap clears
9250  * pending debug exceptions, populates the exit qualification field
9251  * properly, and that DR6 is not prematurely clobbered. In a
9252  * (simulated) MOVSS shadow, make sure that the pending debug
9253  * exception bits are properly accumulated into the exit qualification
9254  * field.
9255  */
9256 static void vmx_db_test(void)
9257 {
9258 	/*
9259 	 * We are going to set a few arbitrary bits in DR6 to verify that
9260 	 * (a) DR6 is not modified by an intercepted #DB, and
9261 	 * (b) stale bits in DR6 (DR6.BD, in particular) don't leak into
9262          *     the exit qualification field for a subsequent #DB exception.
9263 	 */
9264 	const u64 starting_dr6 = DR6_ACTIVE_LOW | DR6_BS | DR6_TRAP3 | DR6_TRAP1;
9265 	extern char post_nop asm(".Lpost_nop");
9266 	extern char post_movss_nop asm(".Lpost_movss_nop");
9267 	extern char post_wbinvd asm(".Lpost_wbinvd");
9268 	extern char post_movss_wbinvd asm(".Lpost_movss_wbinvd");
9269 	extern char xbegin asm(".Lxbegin");
9270 	extern char skip_rtm asm(".Lskip_rtm");
9271 
9272 	/*
9273 	 * L1 wants to intercept #DB exceptions encountered in L2.
9274 	 */
9275 	vmcs_write(EXC_BITMAP, BIT(DB_VECTOR));
9276 
9277 	/*
9278 	 * Start L2 and run it up to the first point of interest.
9279 	 */
9280 	test_set_guest(vmx_db_test_guest);
9281 	enter_guest();
9282 
9283 	/*
9284 	 * Hardware-delivered #DB trap for single-step sets the
9285 	 * standard that L0 has to follow for emulated instructions.
9286 	 */
9287 	single_step_guest("Hardware delivered single-step", starting_dr6, 0);
9288 	check_db_exit(false, false, false, &post_nop, DR6_BS, starting_dr6);
9289 
9290 	/*
9291 	 * Hardware-delivered #DB trap for single-step in MOVSS shadow
9292 	 * also sets the standard that L0 has to follow for emulated
9293 	 * instructions. Here, we establish the VMCS pending debug
9294 	 * exceptions to indicate that the simulated MOVSS triggered a
9295 	 * data breakpoint as well as the single-step trap.
9296 	 */
9297 	single_step_guest("Hardware delivered single-step in MOVSS shadow",
9298 			  starting_dr6, DR6_BS | PENDING_DBG_TRAP | DR6_TRAP0);
9299 	check_db_exit(false, false, false, &post_movss_nop, DR6_BS | DR6_TRAP0,
9300 		      starting_dr6);
9301 
9302 	/*
9303 	 * L0 synthesized #DB trap for single-step is buggy, because
9304 	 * kvm (a) clobbers DR6 too early, and (b) tries its best to
9305 	 * reconstitute the exit qualification from the prematurely
9306 	 * modified DR6, but fails miserably.
9307 	 */
9308 	single_step_guest("Software synthesized single-step", starting_dr6, 0);
9309 	check_db_exit(false, false, false, &post_wbinvd, DR6_BS, starting_dr6);
9310 
9311 	/*
9312 	 * L0 synthesized #DB trap for single-step in MOVSS shadow is
9313 	 * even worse, because L0 also leaves the pending debug
9314 	 * exceptions in the VMCS instead of accumulating them into
9315 	 * the exit qualification field for the #DB exception.
9316 	 */
9317 	single_step_guest("Software synthesized single-step in MOVSS shadow",
9318 			  starting_dr6, DR6_BS | PENDING_DBG_TRAP | DR6_TRAP0);
9319 	check_db_exit(true, false, true, &post_movss_wbinvd, DR6_BS | DR6_TRAP0,
9320 		      starting_dr6);
9321 
9322 	/*
9323 	 * Optional RTM test for hardware that supports RTM, to
9324 	 * demonstrate that the current volume 3 of the SDM
9325 	 * (325384-067US), table 27-1 is incorrect. Bit 16 of the exit
9326 	 * qualification for debug exceptions is not reserved. It is
9327 	 * set to 1 if a debug exception (#DB) or a breakpoint
9328 	 * exception (#BP) occurs inside an RTM region while advanced
9329 	 * debugging of RTM transactional regions is enabled.
9330 	 */
9331 	if (this_cpu_has(X86_FEATURE_RTM)) {
9332 		vmcs_write(ENT_CONTROLS,
9333 			   vmcs_read(ENT_CONTROLS) | ENT_LOAD_DBGCTLS);
9334 		/*
9335 		 * Set DR7.RTM[bit 11] and IA32_DEBUGCTL.RTM[bit 15]
9336 		 * in the guest to enable advanced debugging of RTM
9337 		 * transactional regions.
9338 		 */
9339 		vmcs_write(GUEST_DR7, BIT(11));
9340 		vmcs_write(GUEST_DEBUGCTL, BIT(15));
9341 		single_step_guest("Hardware delivered single-step in "
9342 				  "transactional region", starting_dr6, 0);
9343 		check_db_exit(false, false, false, &xbegin, BIT(16),
9344 			      starting_dr6);
9345 	} else {
9346 		vmcs_write(GUEST_RIP, (u64)&skip_rtm);
9347 		enter_guest();
9348 	}
9349 }
9350 
9351 static void enable_vid(void)
9352 {
9353 	void *virtual_apic_page;
9354 
9355 	assert(cpu_has_apicv());
9356 
9357 	enable_x2apic();
9358 	disable_intercept_for_x2apic_msrs();
9359 
9360 	virtual_apic_page = alloc_page();
9361 	vmcs_write(APIC_VIRT_ADDR, (u64)virtual_apic_page);
9362 
9363 	vmcs_set_bits(PIN_CONTROLS, PIN_EXTINT);
9364 
9365 	vmcs_write(EOI_EXIT_BITMAP0, 0x0);
9366 	vmcs_write(EOI_EXIT_BITMAP1, 0x0);
9367 	vmcs_write(EOI_EXIT_BITMAP2, 0x0);
9368 	vmcs_write(EOI_EXIT_BITMAP3, 0x0);
9369 
9370 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY | CPU_TPR_SHADOW);
9371 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VINTD | CPU_VIRT_X2APIC);
9372 }
9373 
9374 #define	PI_VECTOR	255
9375 
9376 static void enable_posted_interrupts(void)
9377 {
9378 	void *pi_desc = alloc_page();
9379 
9380 	vmcs_set_bits(PIN_CONTROLS, PIN_POST_INTR);
9381 	vmcs_set_bits(EXI_CONTROLS, EXI_INTA);
9382 	vmcs_write(PINV, PI_VECTOR);
9383 	vmcs_write(POSTED_INTR_DESC_ADDR, (u64)pi_desc);
9384 }
9385 
9386 static void trigger_ioapic_scan_thread(void *data)
9387 {
9388 	/* Wait until other CPU entered L2 */
9389 	while (vmx_get_test_stage() != 1)
9390 		;
9391 
9392 	/* Trigger ioapic scan */
9393 	ioapic_set_redir(0xf, 0x79, TRIGGER_LEVEL);
9394 	vmx_set_test_stage(2);
9395 }
9396 
9397 static void irq_79_handler_guest(isr_regs_t *regs)
9398 {
9399 	eoi();
9400 
9401 	/* L1 expects vmexit on VMX_VMCALL and not VMX_EOI_INDUCED */
9402 	vmcall();
9403 }
9404 
9405 /*
9406  * Constant for num of busy-loop iterations after which
9407  * a timer interrupt should have happened in host
9408  */
9409 #define TIMER_INTERRUPT_DELAY 100000000
9410 
9411 static void vmx_eoi_bitmap_ioapic_scan_test_guest(void)
9412 {
9413 	handle_irq(0x79, irq_79_handler_guest);
9414 	sti();
9415 
9416 	/* Signal to L1 CPU to trigger ioapic scan */
9417 	vmx_set_test_stage(1);
9418 	/* Wait until L1 CPU to trigger ioapic scan */
9419 	while (vmx_get_test_stage() != 2)
9420 		;
9421 
9422 	/*
9423 	 * Wait for L0 timer interrupt to be raised while we run in L2
9424 	 * such that L0 will process the IOAPIC scan request before
9425 	 * resuming L2
9426 	 */
9427 	delay(TIMER_INTERRUPT_DELAY);
9428 
9429 	asm volatile ("int $0x79");
9430 }
9431 
9432 static void vmx_eoi_bitmap_ioapic_scan_test(void)
9433 {
9434 	if (!cpu_has_apicv() || (cpu_count() < 2)) {
9435 		report_skip("%s : Not all required APICv bits supported or CPU count < 2", __func__);
9436 		return;
9437 	}
9438 
9439 	enable_vid();
9440 
9441 	on_cpu_async(1, trigger_ioapic_scan_thread, NULL);
9442 	test_set_guest(vmx_eoi_bitmap_ioapic_scan_test_guest);
9443 
9444 	/*
9445 	 * Launch L2.
9446 	 * We expect the exit reason to be VMX_VMCALL (and not EOI INDUCED).
9447 	 * In case the reason isn't VMX_VMCALL, the assertion inside
9448 	 * skip_exit_vmcall() will fail.
9449 	 */
9450 	enter_guest();
9451 	skip_exit_vmcall();
9452 
9453 	/* Let L2 finish */
9454 	enter_guest();
9455 	report_pass(__func__);
9456 }
9457 
9458 #define HLT_WITH_RVI_VECTOR		(0xf1)
9459 
9460 bool vmx_hlt_with_rvi_guest_isr_fired;
9461 static void vmx_hlt_with_rvi_guest_isr(isr_regs_t *regs)
9462 {
9463 	vmx_hlt_with_rvi_guest_isr_fired = true;
9464 	eoi();
9465 }
9466 
9467 static void vmx_hlt_with_rvi_guest(void)
9468 {
9469 	handle_irq(HLT_WITH_RVI_VECTOR, vmx_hlt_with_rvi_guest_isr);
9470 
9471 	sti_nop();
9472 	asm volatile ("nop");
9473 
9474 	vmcall();
9475 }
9476 
9477 static void vmx_hlt_with_rvi_test(void)
9478 {
9479 	if (!cpu_has_apicv()) {
9480 		report_skip("%s : Not all required APICv bits supported", __func__);
9481 		return;
9482 	}
9483 
9484 	enable_vid();
9485 
9486 	vmx_hlt_with_rvi_guest_isr_fired = false;
9487 	test_set_guest(vmx_hlt_with_rvi_guest);
9488 
9489 	enter_guest();
9490 	skip_exit_vmcall();
9491 
9492 	vmcs_write(GUEST_ACTV_STATE, ACTV_HLT);
9493 	vmcs_write(GUEST_INT_STATUS, HLT_WITH_RVI_VECTOR);
9494 	enter_guest();
9495 
9496 	report(vmx_hlt_with_rvi_guest_isr_fired, "Interrupt raised in guest");
9497 }
9498 
9499 static void set_irq_line_thread(void *data)
9500 {
9501 	/* Wait until other CPU entered L2 */
9502 	while (vmx_get_test_stage() != 1)
9503 		;
9504 
9505 	/* Set irq-line 0xf to raise vector 0x78 for vCPU 0 */
9506 	ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
9507 	vmx_set_test_stage(2);
9508 }
9509 
9510 static bool irq_78_handler_vmcall_before_eoi;
9511 static void irq_78_handler_guest(isr_regs_t *regs)
9512 {
9513 	set_irq_line(0xf, 0);
9514 	if (irq_78_handler_vmcall_before_eoi)
9515 		vmcall();
9516 	eoi();
9517 	vmcall();
9518 }
9519 
9520 static void vmx_apic_passthrough_guest(void)
9521 {
9522 	handle_irq(0x78, irq_78_handler_guest);
9523 	sti();
9524 
9525 	/* If requested, wait for other CPU to trigger ioapic scan */
9526 	if (vmx_get_test_stage() < 1) {
9527 		vmx_set_test_stage(1);
9528 		while (vmx_get_test_stage() != 2)
9529 			;
9530 	}
9531 
9532 	set_irq_line(0xf, 1);
9533 }
9534 
9535 static void vmx_apic_passthrough(bool set_irq_line_from_thread)
9536 {
9537 	if (set_irq_line_from_thread && (cpu_count() < 2)) {
9538 		report_skip("%s : CPU count < 2", __func__);
9539 		return;
9540 	}
9541 
9542 	/* Test device is required for generating IRQs */
9543 	if (!test_device_enabled()) {
9544 		report_skip("%s : No test device enabled", __func__);
9545 		return;
9546 	}
9547 	u64 cpu_ctrl_0 = CPU_SECONDARY;
9548 	u64 cpu_ctrl_1 = 0;
9549 
9550 	disable_intercept_for_x2apic_msrs();
9551 
9552 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
9553 
9554 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
9555 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
9556 
9557 	if (set_irq_line_from_thread) {
9558 		irq_78_handler_vmcall_before_eoi = false;
9559 		on_cpu_async(1, set_irq_line_thread, NULL);
9560 	} else {
9561 		irq_78_handler_vmcall_before_eoi = true;
9562 		ioapic_set_redir(0xf, 0x78, TRIGGER_LEVEL);
9563 		vmx_set_test_stage(2);
9564 	}
9565 	test_set_guest(vmx_apic_passthrough_guest);
9566 
9567 	if (irq_78_handler_vmcall_before_eoi) {
9568 		/* Before EOI remote_irr should still be set */
9569 		enter_guest();
9570 		skip_exit_vmcall();
9571 		TEST_ASSERT_EQ_MSG(1, (int)ioapic_read_redir(0xf).remote_irr,
9572 			"IOAPIC pass-through: remote_irr=1 before EOI");
9573 	}
9574 
9575 	/* After EOI remote_irr should be cleared */
9576 	enter_guest();
9577 	skip_exit_vmcall();
9578 	TEST_ASSERT_EQ_MSG(0, (int)ioapic_read_redir(0xf).remote_irr,
9579 		"IOAPIC pass-through: remote_irr=0 after EOI");
9580 
9581 	/* Let L2 finish */
9582 	enter_guest();
9583 	report_pass(__func__);
9584 }
9585 
9586 static void vmx_apic_passthrough_test(void)
9587 {
9588 	vmx_apic_passthrough(false);
9589 }
9590 
9591 static void vmx_apic_passthrough_thread_test(void)
9592 {
9593 	vmx_apic_passthrough(true);
9594 }
9595 
9596 static void vmx_apic_passthrough_tpr_threshold_guest(void)
9597 {
9598 	cli();
9599 	apic_set_tpr(0);
9600 }
9601 
9602 static bool vmx_apic_passthrough_tpr_threshold_ipi_isr_fired;
9603 static void vmx_apic_passthrough_tpr_threshold_ipi_isr(isr_regs_t *regs)
9604 {
9605 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = true;
9606 	eoi();
9607 }
9608 
9609 static void vmx_apic_passthrough_tpr_threshold_test(void)
9610 {
9611 	int ipi_vector = 0xe1;
9612 
9613 	disable_intercept_for_x2apic_msrs();
9614 	vmcs_clear_bits(PIN_CONTROLS, PIN_EXTINT);
9615 
9616 	/* Raise L0 TPR-threshold by queueing vector in LAPIC IRR */
9617 	cli();
9618 	apic_set_tpr((ipi_vector >> 4) + 1);
9619 	apic_icr_write(APIC_DEST_SELF | APIC_DEST_PHYSICAL |
9620 			APIC_DM_FIXED | ipi_vector,
9621 			0);
9622 
9623 	test_set_guest(vmx_apic_passthrough_tpr_threshold_guest);
9624 	enter_guest();
9625 
9626 	report(apic_get_tpr() == 0, "TPR was zero by guest");
9627 
9628 	/* Clean pending self-IPI */
9629 	vmx_apic_passthrough_tpr_threshold_ipi_isr_fired = false;
9630 	handle_irq(ipi_vector, vmx_apic_passthrough_tpr_threshold_ipi_isr);
9631 	sti_nop();
9632 	report(vmx_apic_passthrough_tpr_threshold_ipi_isr_fired, "self-IPI fired");
9633 
9634 	report_pass(__func__);
9635 }
9636 
9637 static u64 init_signal_test_exit_reason;
9638 static bool init_signal_test_thread_continued;
9639 
9640 static void init_signal_test_thread(void *data)
9641 {
9642 	struct vmcs *test_vmcs = data;
9643 
9644 	/* Enter VMX operation (i.e. exec VMXON) */
9645 	u64 *ap_vmxon_region = alloc_page();
9646 	enable_vmx();
9647 	init_vmx(ap_vmxon_region);
9648 	TEST_ASSERT(!__vmxon_safe(ap_vmxon_region));
9649 
9650 	/* Signal CPU have entered VMX operation */
9651 	vmx_set_test_stage(1);
9652 
9653 	/* Wait for BSP CPU to send INIT signal */
9654 	while (vmx_get_test_stage() != 2)
9655 		;
9656 
9657 	/*
9658 	 * Signal that we continue as usual as INIT signal
9659 	 * should be blocked while CPU is in VMX operation
9660 	 */
9661 	vmx_set_test_stage(3);
9662 
9663 	/* Wait for signal to enter VMX non-root mode */
9664 	while (vmx_get_test_stage() != 4)
9665 		;
9666 
9667 	/* Enter VMX non-root mode */
9668 	test_set_guest(v2_null_test_guest);
9669 	make_vmcs_current(test_vmcs);
9670 	enter_guest();
9671 	/* Save exit reason for BSP CPU to compare to expected result */
9672 	init_signal_test_exit_reason = vmcs_read(EXI_REASON);
9673 	/* VMCLEAR test-vmcs so it could be loaded by BSP CPU */
9674 	vmcs_clear(test_vmcs);
9675 	launched = false;
9676 	/* Signal that CPU exited to VMX root mode */
9677 	vmx_set_test_stage(5);
9678 
9679 	/* Wait for BSP CPU to signal to exit VMX operation */
9680 	while (vmx_get_test_stage() != 6)
9681 		;
9682 
9683 	/* Exit VMX operation (i.e. exec VMXOFF) */
9684 	vmx_off();
9685 
9686 	/*
9687 	 * Signal to BSP CPU that we continue as usual as INIT signal
9688 	 * should have been consumed by VMX_INIT exit from guest
9689 	 */
9690 	vmx_set_test_stage(7);
9691 
9692 	/* Wait for BSP CPU to signal to enter VMX operation */
9693 	while (vmx_get_test_stage() != 8)
9694 		;
9695 	/* Enter VMX operation (i.e. exec VMXON) */
9696 	TEST_ASSERT(!__vmxon_safe(ap_vmxon_region));
9697 	/* Signal to BSP we are in VMX operation */
9698 	vmx_set_test_stage(9);
9699 
9700 	/* Wait for BSP CPU to send INIT signal */
9701 	while (vmx_get_test_stage() != 10)
9702 		;
9703 
9704 	/* Exit VMX operation (i.e. exec VMXOFF) */
9705 	vmx_off();
9706 
9707 	/*
9708 	 * Exiting VMX operation should result in latched
9709 	 * INIT signal being processed. Therefore, we should
9710 	 * never reach the below code. Thus, signal to BSP
9711 	 * CPU if we have reached here so it is able to
9712 	 * report an issue if it happens.
9713 	 */
9714 	init_signal_test_thread_continued = true;
9715 }
9716 
9717 #define INIT_SIGNAL_TEST_DELAY	100000000ULL
9718 
9719 static void vmx_init_signal_test(void)
9720 {
9721 	struct vmcs *test_vmcs;
9722 
9723 	if (cpu_count() < 2) {
9724 		report_skip("%s : CPU count < 2", __func__);
9725 		return;
9726 	}
9727 
9728 	/* VMCLEAR test-vmcs so it could be loaded by other CPU */
9729 	vmcs_save(&test_vmcs);
9730 	vmcs_clear(test_vmcs);
9731 
9732 	vmx_set_test_stage(0);
9733 	on_cpu_async(1, init_signal_test_thread, test_vmcs);
9734 
9735 	/* Wait for other CPU to enter VMX operation */
9736 	while (vmx_get_test_stage() != 1)
9737 		;
9738 
9739 	/* Send INIT signal to other CPU */
9740 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9741 				   id_map[1]);
9742 	/* Signal other CPU we have sent INIT signal */
9743 	vmx_set_test_stage(2);
9744 
9745 	/*
9746 	 * Wait reasonable amount of time for INIT signal to
9747 	 * be received on other CPU and verify that other CPU
9748 	 * have proceed as usual to next test stage as INIT
9749 	 * signal should be blocked while other CPU in
9750 	 * VMX operation
9751 	 */
9752 	delay(INIT_SIGNAL_TEST_DELAY);
9753 	report(vmx_get_test_stage() == 3,
9754 	       "INIT signal blocked when CPU in VMX operation");
9755 	/* No point to continue if we failed at this point */
9756 	if (vmx_get_test_stage() != 3)
9757 		return;
9758 
9759 	/* Signal other CPU to enter VMX non-root mode */
9760 	init_signal_test_exit_reason = -1ull;
9761 	vmx_set_test_stage(4);
9762 	/*
9763 	 * Wait reasonable amount of time for other CPU
9764 	 * to exit to VMX root mode
9765 	 */
9766 	delay(INIT_SIGNAL_TEST_DELAY);
9767 	if (vmx_get_test_stage() != 5) {
9768 		report_fail("Pending INIT signal didn't result in VMX exit");
9769 		return;
9770 	}
9771 	report(init_signal_test_exit_reason == VMX_INIT,
9772 			"INIT signal during VMX non-root mode result in exit-reason %s (%lu)",
9773 			exit_reason_description(init_signal_test_exit_reason),
9774 			init_signal_test_exit_reason);
9775 
9776 	/* Run guest to completion */
9777 	make_vmcs_current(test_vmcs);
9778 	enter_guest();
9779 
9780 	/* Signal other CPU to exit VMX operation */
9781 	init_signal_test_thread_continued = false;
9782 	vmx_set_test_stage(6);
9783 
9784 	/* Wait reasonable amount of time for other CPU to exit VMX operation */
9785 	delay(INIT_SIGNAL_TEST_DELAY);
9786 	report(vmx_get_test_stage() == 7,
9787 	       "INIT signal consumed on VMX_INIT exit");
9788 	/* No point to continue if we failed at this point */
9789 	if (vmx_get_test_stage() != 7)
9790 		return;
9791 
9792 	/* Signal other CPU to enter VMX operation */
9793 	vmx_set_test_stage(8);
9794 	/* Wait for other CPU to enter VMX operation */
9795 	while (vmx_get_test_stage() != 9)
9796 		;
9797 
9798 	/* Send INIT signal to other CPU */
9799 	apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_INIT | APIC_INT_ASSERT,
9800 				   id_map[1]);
9801 	/* Signal other CPU we have sent INIT signal */
9802 	vmx_set_test_stage(10);
9803 
9804 	/*
9805 	 * Wait reasonable amount of time for other CPU
9806 	 * to exit VMX operation and process INIT signal
9807 	 */
9808 	delay(INIT_SIGNAL_TEST_DELAY);
9809 	report(!init_signal_test_thread_continued,
9810 	       "INIT signal processed after exit VMX operation");
9811 
9812 	/*
9813 	 * TODO: Send SIPI to other CPU to sipi_entry (See x86/cstart64.S)
9814 	 * to re-init it to kvm-unit-tests standard environment.
9815 	 * Somehow (?) verify that SIPI was indeed received.
9816 	 */
9817 }
9818 
9819 #define SIPI_SIGNAL_TEST_DELAY	100000000ULL
9820 
9821 static void vmx_sipi_test_guest(void)
9822 {
9823 	if (apic_id() == 0) {
9824 		/* wait AP enter guest with activity=WAIT_SIPI */
9825 		while (vmx_get_test_stage() != 1)
9826 			;
9827 		delay(SIPI_SIGNAL_TEST_DELAY);
9828 
9829 		/* First SIPI signal */
9830 		apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_STARTUP | APIC_INT_ASSERT, id_map[1]);
9831 		report_pass("BSP(L2): Send first SIPI to cpu[%d]", id_map[1]);
9832 
9833 		/* wait AP enter guest */
9834 		while (vmx_get_test_stage() != 2)
9835 			;
9836 		delay(SIPI_SIGNAL_TEST_DELAY);
9837 
9838 		/* Second SIPI signal should be ignored since AP is not in WAIT_SIPI state */
9839 		apic_icr_write(APIC_DEST_PHYSICAL | APIC_DM_STARTUP | APIC_INT_ASSERT, id_map[1]);
9840 		report_pass("BSP(L2): Send second SIPI to cpu[%d]", id_map[1]);
9841 
9842 		/* Delay a while to check whether second SIPI would cause VMExit */
9843 		delay(SIPI_SIGNAL_TEST_DELAY);
9844 
9845 		/* Test is done, notify AP to exit test */
9846 		vmx_set_test_stage(3);
9847 
9848 		/* wait AP exit non-root mode */
9849 		while (vmx_get_test_stage() != 5)
9850 			;
9851 	} else {
9852 		/* wait BSP notify test is done */
9853 		while (vmx_get_test_stage() != 3)
9854 			;
9855 
9856 		/* AP exit guest */
9857 		vmx_set_test_stage(4);
9858 	}
9859 }
9860 
9861 static void sipi_test_ap_thread(void *data)
9862 {
9863 	struct vmcs *ap_vmcs;
9864 	u64 *ap_vmxon_region;
9865 	void *ap_stack, *ap_syscall_stack;
9866 	u64 cpu_ctrl_0 = CPU_SECONDARY;
9867 	u64 cpu_ctrl_1 = 0;
9868 
9869 	/* Enter VMX operation (i.e. exec VMXON) */
9870 	ap_vmxon_region = alloc_page();
9871 	enable_vmx();
9872 	init_vmx(ap_vmxon_region);
9873 	TEST_ASSERT(!__vmxon_safe(ap_vmxon_region));
9874 	init_vmcs(&ap_vmcs);
9875 	make_vmcs_current(ap_vmcs);
9876 
9877 	/* Set stack for AP */
9878 	ap_stack = alloc_page();
9879 	ap_syscall_stack = alloc_page();
9880 	vmcs_write(GUEST_RSP, (u64)(ap_stack + PAGE_SIZE - 1));
9881 	vmcs_write(GUEST_SYSENTER_ESP, (u64)(ap_syscall_stack + PAGE_SIZE - 1));
9882 
9883 	/* passthrough lapic to L2 */
9884 	disable_intercept_for_x2apic_msrs();
9885 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
9886 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
9887 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
9888 
9889 	/* Set guest activity state to wait-for-SIPI state */
9890 	vmcs_write(GUEST_ACTV_STATE, ACTV_WAIT_SIPI);
9891 
9892 	vmx_set_test_stage(1);
9893 
9894 	/* AP enter guest */
9895 	enter_guest();
9896 
9897 	if (vmcs_read(EXI_REASON) == VMX_SIPI) {
9898 		report_pass("AP: Handle SIPI VMExit");
9899 		vmcs_write(GUEST_ACTV_STATE, ACTV_ACTIVE);
9900 		vmx_set_test_stage(2);
9901 	} else {
9902 		report_fail("AP: Unexpected VMExit, reason=%ld", vmcs_read(EXI_REASON));
9903 		vmx_off();
9904 		return;
9905 	}
9906 
9907 	/* AP enter guest */
9908 	enter_guest();
9909 
9910 	report(vmcs_read(EXI_REASON) != VMX_SIPI,
9911 		"AP: should no SIPI VMExit since activity is not in WAIT_SIPI state");
9912 
9913 	/* notify BSP that AP is already exit from non-root mode */
9914 	vmx_set_test_stage(5);
9915 
9916 	/* Leave VMX operation */
9917 	vmx_off();
9918 }
9919 
9920 static void vmx_sipi_signal_test(void)
9921 {
9922 	if (!(rdmsr(MSR_IA32_VMX_MISC) & MSR_IA32_VMX_MISC_ACTIVITY_WAIT_SIPI)) {
9923 		report_skip("%s : \"ACTIVITY_WAIT_SIPI state\" not supported", __func__);
9924 		return;
9925 	}
9926 
9927 	if (cpu_count() < 2) {
9928 		report_skip("%s : CPU count < 2", __func__);
9929 		return;
9930 	}
9931 
9932 	u64 cpu_ctrl_0 = CPU_SECONDARY;
9933 	u64 cpu_ctrl_1 = 0;
9934 
9935 	/* passthrough lapic to L2 */
9936 	disable_intercept_for_x2apic_msrs();
9937 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) & ~PIN_EXTINT);
9938 	vmcs_write(CPU_EXEC_CTRL0, vmcs_read(CPU_EXEC_CTRL0) | cpu_ctrl_0);
9939 	vmcs_write(CPU_EXEC_CTRL1, vmcs_read(CPU_EXEC_CTRL1) | cpu_ctrl_1);
9940 
9941 	test_set_guest(vmx_sipi_test_guest);
9942 
9943 	/* update CR3 on AP */
9944 	on_cpu(1, update_cr3, (void *)read_cr3());
9945 
9946 	/* start AP */
9947 	on_cpu_async(1, sipi_test_ap_thread, NULL);
9948 
9949 	vmx_set_test_stage(0);
9950 
9951 	/* BSP enter guest */
9952 	enter_guest();
9953 }
9954 
9955 
9956 enum vmcs_access {
9957 	ACCESS_VMREAD,
9958 	ACCESS_VMWRITE,
9959 	ACCESS_NONE,
9960 };
9961 
9962 struct vmcs_shadow_test_common {
9963 	enum vmcs_access op;
9964 	enum Reason reason;
9965 	u64 field;
9966 	u64 value;
9967 	u64 flags;
9968 	u64 time;
9969 } l1_l2_common;
9970 
9971 static inline u64 vmread_flags(u64 field, u64 *val)
9972 {
9973 	u64 flags;
9974 
9975 	asm volatile ("vmread %2, %1; pushf; pop %0"
9976 		      : "=r" (flags), "=rm" (*val) : "r" (field) : "cc");
9977 	return flags & X86_EFLAGS_ALU;
9978 }
9979 
9980 static inline u64 vmwrite_flags(u64 field, u64 val)
9981 {
9982 	u64 flags;
9983 
9984 	asm volatile ("vmwrite %1, %2; pushf; pop %0"
9985 		      : "=r"(flags) : "rm" (val), "r" (field) : "cc");
9986 	return flags & X86_EFLAGS_ALU;
9987 }
9988 
9989 static void vmx_vmcs_shadow_test_guest(void)
9990 {
9991 	struct vmcs_shadow_test_common *c = &l1_l2_common;
9992 	u64 start;
9993 
9994 	while (c->op != ACCESS_NONE) {
9995 		start = rdtsc();
9996 		switch (c->op) {
9997 		default:
9998 			c->flags = -1ull;
9999 			break;
10000 		case ACCESS_VMREAD:
10001 			c->flags = vmread_flags(c->field, &c->value);
10002 			break;
10003 		case ACCESS_VMWRITE:
10004 			c->flags = vmwrite_flags(c->field, 0);
10005 			break;
10006 		}
10007 		c->time = rdtsc() - start;
10008 		vmcall();
10009 	}
10010 }
10011 
10012 static u64 vmread_from_shadow(u64 field)
10013 {
10014 	struct vmcs *primary;
10015 	struct vmcs *shadow;
10016 	u64 value;
10017 
10018 	TEST_ASSERT(!vmcs_save(&primary));
10019 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
10020 	TEST_ASSERT(!make_vmcs_current(shadow));
10021 	value = vmcs_read(field);
10022 	TEST_ASSERT(!make_vmcs_current(primary));
10023 	return value;
10024 }
10025 
10026 static u64 vmwrite_to_shadow(u64 field, u64 value)
10027 {
10028 	struct vmcs *primary;
10029 	struct vmcs *shadow;
10030 
10031 	TEST_ASSERT(!vmcs_save(&primary));
10032 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
10033 	TEST_ASSERT(!make_vmcs_current(shadow));
10034 	vmcs_write(field, value);
10035 	value = vmcs_read(field);
10036 	TEST_ASSERT(!make_vmcs_current(primary));
10037 	return value;
10038 }
10039 
10040 static void vmcs_shadow_test_access(u8 *bitmap[2], enum vmcs_access access)
10041 {
10042 	struct vmcs_shadow_test_common *c = &l1_l2_common;
10043 
10044 	c->op = access;
10045 	vmcs_write(VMX_INST_ERROR, 0);
10046 	enter_guest();
10047 	c->reason = vmcs_read(EXI_REASON) & 0xffff;
10048 	if (c->reason != VMX_VMCALL) {
10049 		skip_exit_insn();
10050 		enter_guest();
10051 	}
10052 	skip_exit_vmcall();
10053 }
10054 
10055 static void vmcs_shadow_test_field(u8 *bitmap[2], u64 field)
10056 {
10057 	struct vmcs_shadow_test_common *c = &l1_l2_common;
10058 	struct vmcs *shadow;
10059 	u64 value;
10060 	uintptr_t flags[2];
10061 	bool good_shadow;
10062 	u32 vmx_inst_error;
10063 
10064 	report_prefix_pushf("field %lx", field);
10065 	c->field = field;
10066 
10067 	shadow = (struct vmcs *)vmcs_read(VMCS_LINK_PTR);
10068 	if (shadow != (struct vmcs *)-1ull) {
10069 		flags[ACCESS_VMREAD] = vmread_flags(field, &value);
10070 		flags[ACCESS_VMWRITE] = vmwrite_flags(field, value);
10071 		good_shadow = !flags[ACCESS_VMREAD] && !flags[ACCESS_VMWRITE];
10072 	} else {
10073 		/*
10074 		 * When VMCS link pointer is -1ull, VMWRITE/VMREAD on
10075 		 * shadowed-fields should fail with setting RFLAGS.CF.
10076 		 */
10077 		flags[ACCESS_VMREAD] = X86_EFLAGS_CF;
10078 		flags[ACCESS_VMWRITE] = X86_EFLAGS_CF;
10079 		good_shadow = false;
10080 	}
10081 
10082 	/* Intercept both VMREAD and VMWRITE. */
10083 	report_prefix_push("no VMREAD/VMWRITE permission");
10084 	/* VMWRITE/VMREAD done on reserved-bit should always intercept */
10085 	if (!(field >> VMCS_FIELD_RESERVED_SHIFT)) {
10086 		set_bit(field, bitmap[ACCESS_VMREAD]);
10087 		set_bit(field, bitmap[ACCESS_VMWRITE]);
10088 	}
10089 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
10090 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
10091 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
10092 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
10093 	report_prefix_pop();
10094 
10095 	if (field >> VMCS_FIELD_RESERVED_SHIFT)
10096 		goto out;
10097 
10098 	/* Permit shadowed VMREAD. */
10099 	report_prefix_push("VMREAD permission only");
10100 	clear_bit(field, bitmap[ACCESS_VMREAD]);
10101 	set_bit(field, bitmap[ACCESS_VMWRITE]);
10102 	if (good_shadow)
10103 		value = vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
10104 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
10105 	report(c->reason == VMX_VMWRITE, "not shadowed for VMWRITE");
10106 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
10107 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
10108 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
10109 	       c->time);
10110 	report(c->flags == flags[ACCESS_VMREAD],
10111 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
10112 	       c->flags, flags[ACCESS_VMREAD]);
10113 	if (good_shadow)
10114 		report(c->value == value,
10115 		       "value read from shadow (%lx) is as expected (%lx)",
10116 		       c->value, value);
10117 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
10118 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
10119 		       "VMX_INST_ERROR (%d) is as expected (%d)",
10120 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
10121 	report_prefix_pop();
10122 
10123 	/* Permit shadowed VMWRITE. */
10124 	report_prefix_push("VMWRITE permission only");
10125 	set_bit(field, bitmap[ACCESS_VMREAD]);
10126 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
10127 	if (good_shadow)
10128 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
10129 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
10130 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
10131 	report(c->reason == VMX_VMCALL,
10132 		"shadowed for VMWRITE (in %ld cycles)",
10133 		c->time);
10134 	report(c->flags == flags[ACCESS_VMREAD],
10135 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
10136 	       c->flags, flags[ACCESS_VMREAD]);
10137 	if (good_shadow) {
10138 		value = vmread_from_shadow(field);
10139 		report(value == 0,
10140 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
10141 		       0ul);
10142 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
10143 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
10144 		       "VMX_INST_ERROR (%d) is as expected (%d)",
10145 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
10146 	}
10147 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
10148 	report(c->reason == VMX_VMREAD, "not shadowed for VMREAD");
10149 	report_prefix_pop();
10150 
10151 	/* Permit shadowed VMREAD and VMWRITE. */
10152 	report_prefix_push("VMREAD and VMWRITE permission");
10153 	clear_bit(field, bitmap[ACCESS_VMREAD]);
10154 	clear_bit(field, bitmap[ACCESS_VMWRITE]);
10155 	if (good_shadow)
10156 		vmwrite_to_shadow(field, MAGIC_VAL_1 + field);
10157 	vmcs_shadow_test_access(bitmap, ACCESS_VMWRITE);
10158 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
10159 	report(c->reason == VMX_VMCALL,
10160 		"shadowed for VMWRITE (in %ld cycles)",
10161 		c->time);
10162 	report(c->flags == flags[ACCESS_VMREAD],
10163 	       "ALU flags after VMWRITE (%lx) are as expected (%lx)",
10164 	       c->flags, flags[ACCESS_VMREAD]);
10165 	if (good_shadow) {
10166 		value = vmread_from_shadow(field);
10167 		report(value == 0,
10168 		       "shadow VMCS value (%lx) is as expected (%lx)", value,
10169 		       0ul);
10170 	} else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMWRITE]) {
10171 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
10172 		       "VMX_INST_ERROR (%d) is as expected (%d)",
10173 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
10174 	}
10175 	vmcs_shadow_test_access(bitmap, ACCESS_VMREAD);
10176 	vmx_inst_error = vmcs_read(VMX_INST_ERROR);
10177 	report(c->reason == VMX_VMCALL, "shadowed for VMREAD (in %ld cycles)",
10178 	       c->time);
10179 	report(c->flags == flags[ACCESS_VMREAD],
10180 	       "ALU flags after VMREAD (%lx) are as expected (%lx)",
10181 	       c->flags, flags[ACCESS_VMREAD]);
10182 	if (good_shadow)
10183 		report(c->value == 0,
10184 		       "value read from shadow (%lx) is as expected (%lx)",
10185 		       c->value, 0ul);
10186 	else if (shadow != (struct vmcs *)-1ull && flags[ACCESS_VMREAD])
10187 		report(vmx_inst_error == VMXERR_UNSUPPORTED_VMCS_COMPONENT,
10188 		       "VMX_INST_ERROR (%d) is as expected (%d)",
10189 		       vmx_inst_error, VMXERR_UNSUPPORTED_VMCS_COMPONENT);
10190 	report_prefix_pop();
10191 
10192 out:
10193 	report_prefix_pop();
10194 }
10195 
10196 static void vmx_vmcs_shadow_test_body(u8 *bitmap[2])
10197 {
10198 	unsigned base;
10199 	unsigned index;
10200 	unsigned bit;
10201 	unsigned highest_index = rdmsr(MSR_IA32_VMX_VMCS_ENUM);
10202 
10203 	/* Run test on all possible valid VMCS fields */
10204 	for (base = 0;
10205 	     base < (1 << VMCS_FIELD_RESERVED_SHIFT);
10206 	     base += (1 << VMCS_FIELD_TYPE_SHIFT))
10207 		for (index = 0; index <= highest_index; index++)
10208 			vmcs_shadow_test_field(bitmap, base + index);
10209 
10210 	/*
10211 	 * Run tests on some invalid VMCS fields
10212 	 * (Have reserved bit set).
10213 	 */
10214 	for (bit = VMCS_FIELD_RESERVED_SHIFT; bit < VMCS_FIELD_BIT_SIZE; bit++)
10215 		vmcs_shadow_test_field(bitmap, (1ull << bit));
10216 }
10217 
10218 static void vmx_vmcs_shadow_test(void)
10219 {
10220 	u8 *bitmap[2];
10221 	struct vmcs *shadow;
10222 
10223 	if (!(ctrl_cpu_rev[0].clr & CPU_SECONDARY)) {
10224 		report_skip("%s : \"Activate secondary controls\" not supported", __func__);
10225 		return;
10226 	}
10227 
10228 	if (!(ctrl_cpu_rev[1].clr & CPU_SHADOW_VMCS)) {
10229 		report_skip("%s : \"VMCS shadowing\" not supported", __func__);
10230 		return;
10231 	}
10232 
10233 	if (!(rdmsr(MSR_IA32_VMX_MISC) &
10234 	      MSR_IA32_VMX_MISC_VMWRITE_SHADOW_RO_FIELDS)) {
10235 		report_skip("%s : VMWRITE can't modify VM-exit information fields.", __func__);
10236 		return;
10237 	}
10238 
10239 	test_set_guest(vmx_vmcs_shadow_test_guest);
10240 
10241 	bitmap[ACCESS_VMREAD] = alloc_page();
10242 	bitmap[ACCESS_VMWRITE] = alloc_page();
10243 
10244 	vmcs_write(VMREAD_BITMAP, virt_to_phys(bitmap[ACCESS_VMREAD]));
10245 	vmcs_write(VMWRITE_BITMAP, virt_to_phys(bitmap[ACCESS_VMWRITE]));
10246 
10247 	shadow = alloc_page();
10248 	shadow->hdr.revision_id = basic_msr.revision;
10249 	shadow->hdr.shadow_vmcs = 1;
10250 	TEST_ASSERT(!vmcs_clear(shadow));
10251 
10252 	vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_RDTSC);
10253 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
10254 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_SHADOW_VMCS);
10255 
10256 	vmcs_write(VMCS_LINK_PTR, virt_to_phys(shadow));
10257 	report_prefix_push("valid link pointer");
10258 	vmx_vmcs_shadow_test_body(bitmap);
10259 	report_prefix_pop();
10260 
10261 	vmcs_write(VMCS_LINK_PTR, -1ull);
10262 	report_prefix_push("invalid link pointer");
10263 	vmx_vmcs_shadow_test_body(bitmap);
10264 	report_prefix_pop();
10265 
10266 	l1_l2_common.op = ACCESS_NONE;
10267 	enter_guest();
10268 }
10269 
10270 /*
10271  * This test monitors the difference between a guest RDTSC instruction
10272  * and the IA32_TIME_STAMP_COUNTER MSR value stored in the VMCS12
10273  * VM-exit MSR-store list when taking a VM-exit on the instruction
10274  * following RDTSC.
10275  */
10276 #define RDTSC_DIFF_ITERS 100000
10277 #define RDTSC_DIFF_FAILS 100
10278 #define HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD 750
10279 
10280 /*
10281  * Set 'use TSC offsetting' and set the guest offset to the
10282  * inverse of the host's current TSC value, so that the guest starts running
10283  * with an effective TSC value of 0.
10284  */
10285 static void reset_guest_tsc_to_zero(void)
10286 {
10287 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_USE_TSC_OFFSET);
10288 	vmcs_write(TSC_OFFSET, -rdtsc());
10289 }
10290 
10291 static void rdtsc_vmexit_diff_test_guest(void)
10292 {
10293 	int i;
10294 
10295 	for (i = 0; i < RDTSC_DIFF_ITERS; i++)
10296 		/* Ensure rdtsc is the last instruction before the vmcall. */
10297 		asm volatile("rdtsc; vmcall" : : : "eax", "edx");
10298 }
10299 
10300 /*
10301  * This function only considers the "use TSC offsetting" VM-execution
10302  * control.  It does not handle "use TSC scaling" (because the latter
10303  * isn't available to the host today.)
10304  */
10305 static unsigned long long host_time_to_guest_time(unsigned long long t)
10306 {
10307 	TEST_ASSERT(!(ctrl_cpu_rev[0].clr & CPU_SECONDARY) ||
10308 		    !(vmcs_read(CPU_EXEC_CTRL1) & CPU_USE_TSC_SCALING));
10309 
10310 	if (vmcs_read(CPU_EXEC_CTRL0) & CPU_USE_TSC_OFFSET)
10311 		t += vmcs_read(TSC_OFFSET);
10312 
10313 	return t;
10314 }
10315 
10316 static unsigned long long rdtsc_vmexit_diff_test_iteration(void)
10317 {
10318 	unsigned long long guest_tsc, host_to_guest_tsc;
10319 
10320 	enter_guest();
10321 	skip_exit_vmcall();
10322 	guest_tsc = (u32) regs.rax + (regs.rdx << 32);
10323 	host_to_guest_tsc = host_time_to_guest_time(exit_msr_store[0].value);
10324 
10325 	return host_to_guest_tsc - guest_tsc;
10326 }
10327 
10328 static void rdtsc_vmexit_diff_test(void)
10329 {
10330 	unsigned long long delta;
10331 	int fail = 0;
10332 	int i;
10333 
10334 	if (!(ctrl_cpu_rev[0].clr & CPU_USE_TSC_OFFSET))
10335 		test_skip("CPU doesn't support the 'use TSC offsetting' processor-based VM-execution control.\n");
10336 
10337 	test_set_guest(rdtsc_vmexit_diff_test_guest);
10338 
10339 	reset_guest_tsc_to_zero();
10340 
10341 	/*
10342 	 * Set up the VMCS12 VM-exit MSR-store list to store just one
10343 	 * MSR: IA32_TIME_STAMP_COUNTER. Note that the value stored is
10344 	 * in the host time domain (i.e., it is not adjusted according
10345 	 * to the TSC multiplier and TSC offset fields in the VMCS12,
10346 	 * as a guest RDTSC would be.)
10347 	 */
10348 	exit_msr_store = alloc_page();
10349 	exit_msr_store[0].index = MSR_IA32_TSC;
10350 	vmcs_write(EXI_MSR_ST_CNT, 1);
10351 	vmcs_write(EXIT_MSR_ST_ADDR, virt_to_phys(exit_msr_store));
10352 
10353 	for (i = 0; i < RDTSC_DIFF_ITERS && fail < RDTSC_DIFF_FAILS; i++) {
10354 		delta = rdtsc_vmexit_diff_test_iteration();
10355 		if (delta >= HOST_CAPTURED_GUEST_TSC_DIFF_THRESHOLD)
10356 			fail++;
10357 	}
10358 
10359 	enter_guest();
10360 
10361 	report(fail < RDTSC_DIFF_FAILS,
10362 	       "RDTSC to VM-exit delta too high in %d of %d iterations, last = %llu",
10363 	       fail, i, delta);
10364 }
10365 
10366 static int invalid_msr_init(struct vmcs *vmcs)
10367 {
10368 	if (!(ctrl_pin_rev.clr & PIN_PREEMPT)) {
10369 		printf("\tPreemption timer is not supported\n");
10370 		return VMX_TEST_EXIT;
10371 	}
10372 	vmcs_write(PIN_CONTROLS, vmcs_read(PIN_CONTROLS) | PIN_PREEMPT);
10373 	preempt_val = 10000000;
10374 	vmcs_write(PREEMPT_TIMER_VALUE, preempt_val);
10375 	preempt_scale = rdmsr(MSR_IA32_VMX_MISC) & 0x1F;
10376 
10377 	if (!(ctrl_exit_rev.clr & EXI_SAVE_PREEMPT))
10378 		printf("\tSave preemption value is not supported\n");
10379 
10380 	vmcs_write(ENT_MSR_LD_CNT, 1);
10381 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)0x13370000);
10382 
10383 	return VMX_TEST_START;
10384 }
10385 
10386 
10387 static void invalid_msr_main(void)
10388 {
10389 	report_fail("Invalid MSR load");
10390 }
10391 
10392 static int invalid_msr_exit_handler(union exit_reason exit_reason)
10393 {
10394 	report_fail("Invalid MSR load");
10395 	print_vmexit_info(exit_reason);
10396 	return VMX_TEST_EXIT;
10397 }
10398 
10399 static int invalid_msr_entry_failure(struct vmentry_result *result)
10400 {
10401 	report(result->exit_reason.failed_vmentry &&
10402 	       result->exit_reason.basic == VMX_FAIL_MSR, "Invalid MSR load");
10403 	return VMX_TEST_VMEXIT;
10404 }
10405 
10406 /*
10407  * The max number of MSRs in an atomic switch MSR list is:
10408  * (111B + 1) * 512 = 4096
10409  *
10410  * Each list entry consumes:
10411  * 4-byte MSR index + 4 bytes reserved + 8-byte data = 16 bytes
10412  *
10413  * Allocate 128 kB to cover max_msr_list_size (i.e., 64 kB) and then some.
10414  */
10415 static const u32 msr_list_page_order = 5;
10416 
10417 static void atomic_switch_msr_limit_test_guest(void)
10418 {
10419 	vmcall();
10420 }
10421 
10422 static void populate_msr_list(struct vmx_msr_entry *msr_list,
10423 			      size_t byte_capacity, int count)
10424 {
10425 	int i;
10426 
10427 	for (i = 0; i < count; i++) {
10428 		msr_list[i].index = MSR_IA32_TSC;
10429 		msr_list[i].reserved = 0;
10430 		msr_list[i].value = 0x1234567890abcdef;
10431 	}
10432 
10433 	memset(msr_list + count, 0xff,
10434 	       byte_capacity - count * sizeof(*msr_list));
10435 }
10436 
10437 static int max_msr_list_size(void)
10438 {
10439 	u32 vmx_misc = rdmsr(MSR_IA32_VMX_MISC);
10440 	u32 factor = ((vmx_misc & GENMASK(27, 25)) >> 25) + 1;
10441 
10442 	return factor * 512;
10443 }
10444 
10445 static void atomic_switch_msrs_test(int count)
10446 {
10447 	struct vmx_msr_entry *vm_enter_load;
10448         struct vmx_msr_entry *vm_exit_load;
10449         struct vmx_msr_entry *vm_exit_store;
10450 	int max_allowed = max_msr_list_size();
10451 	int byte_capacity = 1ul << (msr_list_page_order + PAGE_SHIFT);
10452 	/* Exceeding the max MSR list size at exit triggers KVM to abort. */
10453 	int exit_count = count > max_allowed ? max_allowed : count;
10454 	int cleanup_count = count > max_allowed ? 2 : 1;
10455 	int i;
10456 
10457 	/*
10458 	 * Check for the IA32_TSC MSR,
10459 	 * available with the "TSC flag" and used to populate the MSR lists.
10460 	 */
10461 	if (!(cpuid(1).d & (1 << 4))) {
10462 		report_skip("%s : \"Time Stamp Counter\" not supported", __func__);
10463 		return;
10464 	}
10465 
10466 	/* Set L2 guest. */
10467 	test_set_guest(atomic_switch_msr_limit_test_guest);
10468 
10469 	/* Setup atomic MSR switch lists. */
10470 	vm_enter_load = alloc_pages(msr_list_page_order);
10471 	vm_exit_load = alloc_pages(msr_list_page_order);
10472 	vm_exit_store = alloc_pages(msr_list_page_order);
10473 
10474 	vmcs_write(ENTER_MSR_LD_ADDR, (u64)vm_enter_load);
10475 	vmcs_write(EXIT_MSR_LD_ADDR, (u64)vm_exit_load);
10476 	vmcs_write(EXIT_MSR_ST_ADDR, (u64)vm_exit_store);
10477 
10478 	/*
10479 	 * VM-Enter should succeed up to the max number of MSRs per list, and
10480 	 * should not consume junk beyond the last entry.
10481 	 */
10482 	populate_msr_list(vm_enter_load, byte_capacity, count);
10483 	populate_msr_list(vm_exit_load, byte_capacity, exit_count);
10484 	populate_msr_list(vm_exit_store, byte_capacity, exit_count);
10485 
10486 	vmcs_write(ENT_MSR_LD_CNT, count);
10487 	vmcs_write(EXI_MSR_LD_CNT, exit_count);
10488 	vmcs_write(EXI_MSR_ST_CNT, exit_count);
10489 
10490 	if (count <= max_allowed) {
10491 		enter_guest();
10492 		assert_exit_reason(VMX_VMCALL);
10493 		skip_exit_vmcall();
10494 	} else {
10495 		u32 exit_qual;
10496 
10497 		test_guest_state("Invalid MSR Load Count", true, count,
10498 				 "ENT_MSR_LD_CNT");
10499 
10500 		exit_qual = vmcs_read(EXI_QUALIFICATION);
10501 		report(exit_qual == max_allowed + 1, "exit_qual, %u, is %u.",
10502 		       exit_qual, max_allowed + 1);
10503 	}
10504 
10505 	/* Cleanup. */
10506 	vmcs_write(ENT_MSR_LD_CNT, 0);
10507 	vmcs_write(EXI_MSR_LD_CNT, 0);
10508 	vmcs_write(EXI_MSR_ST_CNT, 0);
10509 	for (i = 0; i < cleanup_count; i++) {
10510 		enter_guest();
10511 		skip_exit_vmcall();
10512 	}
10513 	free_pages_by_order(vm_enter_load, msr_list_page_order);
10514 	free_pages_by_order(vm_exit_load, msr_list_page_order);
10515 	free_pages_by_order(vm_exit_store, msr_list_page_order);
10516 }
10517 
10518 static void atomic_switch_max_msrs_test(void)
10519 {
10520 	atomic_switch_msrs_test(max_msr_list_size());
10521 }
10522 
10523 static void atomic_switch_overflow_msrs_test(void)
10524 {
10525 	if (test_device_enabled())
10526 		atomic_switch_msrs_test(max_msr_list_size() + 1);
10527 	else
10528 		test_skip("Test is only supported on KVM");
10529 }
10530 
10531 static void vmx_pf_exception_test_guest(void)
10532 {
10533 	ac_test_run(PT_LEVEL_PML4, false);
10534 }
10535 
10536 static void vmx_pf_exception_forced_emulation_test_guest(void)
10537 {
10538 	ac_test_run(PT_LEVEL_PML4, true);
10539 }
10540 
10541 typedef void (*invalidate_tlb_t)(void *data);
10542 typedef void (*pf_exception_test_guest_t)(void);
10543 
10544 
10545 static void __vmx_pf_exception_test(invalidate_tlb_t inv_fn, void *data,
10546 				    pf_exception_test_guest_t guest_fn)
10547 {
10548 	u64 efer;
10549 	struct cpuid cpuid;
10550 
10551 	test_set_guest(guest_fn);
10552 
10553 	/* Intercept INVLPG when to perform TLB invalidation from L1 (this). */
10554 	if (inv_fn)
10555 		vmcs_set_bits(CPU_EXEC_CTRL0, CPU_INVLPG);
10556 	else
10557 		vmcs_clear_bits(CPU_EXEC_CTRL0, CPU_INVLPG);
10558 
10559 	enter_guest();
10560 
10561 	while (vmcs_read(EXI_REASON) != VMX_VMCALL) {
10562 		switch (vmcs_read(EXI_REASON)) {
10563 		case VMX_RDMSR:
10564 			assert(regs.rcx == MSR_EFER);
10565 			efer = vmcs_read(GUEST_EFER);
10566 			regs.rdx = efer >> 32;
10567 			regs.rax = efer & 0xffffffff;
10568 			break;
10569 		case VMX_WRMSR:
10570 			assert(regs.rcx == MSR_EFER);
10571 			efer = regs.rdx << 32 | (regs.rax & 0xffffffff);
10572 			vmcs_write(GUEST_EFER, efer);
10573 			break;
10574 		case VMX_CPUID:
10575 			cpuid = (struct cpuid) {0, 0, 0, 0};
10576 			cpuid = raw_cpuid(regs.rax, regs.rcx);
10577 			regs.rax = cpuid.a;
10578 			regs.rbx = cpuid.b;
10579 			regs.rcx = cpuid.c;
10580 			regs.rdx = cpuid.d;
10581 			break;
10582 		case VMX_INVLPG:
10583 			inv_fn(data);
10584 			break;
10585 		default:
10586 			assert_msg(false,
10587 				"Unexpected exit to L1, exit_reason: %s (0x%lx)",
10588 				exit_reason_description(vmcs_read(EXI_REASON)),
10589 				vmcs_read(EXI_REASON));
10590 		}
10591 		skip_exit_insn();
10592 		enter_guest();
10593 	}
10594 
10595 	assert_exit_reason(VMX_VMCALL);
10596 }
10597 
10598 static void vmx_pf_exception_test(void)
10599 {
10600 	__vmx_pf_exception_test(NULL, NULL, vmx_pf_exception_test_guest);
10601 }
10602 
10603 static void vmx_pf_exception_forced_emulation_test(void)
10604 {
10605 	__vmx_pf_exception_test(NULL, NULL, vmx_pf_exception_forced_emulation_test_guest);
10606 }
10607 
10608 static void invalidate_tlb_no_vpid(void *data)
10609 {
10610 	/* If VPID is disabled, the TLB is flushed on VM-Enter and VM-Exit. */
10611 }
10612 
10613 static void vmx_pf_no_vpid_test(void)
10614 {
10615 	if (is_vpid_supported())
10616 		vmcs_clear_bits(CPU_EXEC_CTRL1, CPU_VPID);
10617 
10618 	__vmx_pf_exception_test(invalidate_tlb_no_vpid, NULL,
10619 				vmx_pf_exception_test_guest);
10620 }
10621 
10622 static void invalidate_tlb_invvpid_addr(void *data)
10623 {
10624 	invvpid(INVVPID_ALL, *(u16 *)data, vmcs_read(EXI_QUALIFICATION));
10625 }
10626 
10627 static void invalidate_tlb_new_vpid(void *data)
10628 {
10629 	u16 *vpid = data;
10630 
10631 	/*
10632 	 * Bump VPID to effectively flush L2's TLB from L0's perspective.
10633 	 * Invalidate all VPIDs when the VPID wraps to zero as hardware/KVM is
10634 	 * architecturally allowed to keep TLB entries indefinitely.
10635 	 */
10636 	++(*vpid);
10637 	if (*vpid == 0) {
10638 		++(*vpid);
10639 		invvpid(INVVPID_ALL, 0, 0);
10640 	}
10641 	vmcs_write(VPID, *vpid);
10642 }
10643 
10644 static void __vmx_pf_vpid_test(invalidate_tlb_t inv_fn, u16 vpid)
10645 {
10646 	if (!is_vpid_supported())
10647 		test_skip("VPID unsupported");
10648 
10649 	if (!is_invvpid_supported())
10650 		test_skip("INVVPID unsupported");
10651 
10652 	vmcs_set_bits(CPU_EXEC_CTRL0, CPU_SECONDARY);
10653 	vmcs_set_bits(CPU_EXEC_CTRL1, CPU_VPID);
10654 	vmcs_write(VPID, vpid);
10655 
10656 	__vmx_pf_exception_test(inv_fn, &vpid, vmx_pf_exception_test_guest);
10657 }
10658 
10659 static void vmx_pf_invvpid_test(void)
10660 {
10661 	if (!is_invvpid_type_supported(INVVPID_ADDR))
10662 		test_skip("INVVPID ADDR unsupported");
10663 
10664 	__vmx_pf_vpid_test(invalidate_tlb_invvpid_addr, 0xaaaa);
10665 }
10666 
10667 static void vmx_pf_vpid_test(void)
10668 {
10669 	/* Need INVVPID(ALL) to flush VPIDs upon wrap/reuse. */
10670 	if (!is_invvpid_type_supported(INVVPID_ALL))
10671 		test_skip("INVVPID ALL unsupported");
10672 
10673 	__vmx_pf_vpid_test(invalidate_tlb_new_vpid, 1);
10674 }
10675 
10676 static void vmx_l2_ac_test(void)
10677 {
10678 	bool hit_ac = false;
10679 
10680 	write_cr0(read_cr0() | X86_CR0_AM);
10681 	write_rflags(read_rflags() | X86_EFLAGS_AC);
10682 
10683 	run_in_user(generate_usermode_ac, AC_VECTOR, 0, 0, 0, 0, &hit_ac);
10684 	report(hit_ac, "Usermode #AC handled in L2");
10685 	vmcall();
10686 }
10687 
10688 struct vmx_exception_test {
10689 	u8 vector;
10690 	void (*guest_code)(void);
10691 };
10692 
10693 struct vmx_exception_test vmx_exception_tests[] = {
10694 	{ GP_VECTOR, generate_non_canonical_gp },
10695 	{ UD_VECTOR, generate_ud },
10696 	{ DE_VECTOR, generate_de },
10697 	{ DB_VECTOR, generate_single_step_db },
10698 	{ BP_VECTOR, generate_bp },
10699 	{ AC_VECTOR, vmx_l2_ac_test },
10700 	{ OF_VECTOR, generate_of },
10701 	{ NM_VECTOR, generate_cr0_ts_nm },
10702 	{ NM_VECTOR, generate_cr0_em_nm },
10703 };
10704 
10705 static u8 vmx_exception_test_vector;
10706 
10707 static void vmx_exception_handler(struct ex_regs *regs)
10708 {
10709 	report(regs->vector == vmx_exception_test_vector,
10710 	       "Handling %s in L2's exception handler",
10711 	       exception_mnemonic(vmx_exception_test_vector));
10712 	vmcall();
10713 }
10714 
10715 static void handle_exception_in_l2(u8 vector)
10716 {
10717 	handler old_handler = handle_exception(vector, vmx_exception_handler);
10718 
10719 	vmx_exception_test_vector = vector;
10720 
10721 	enter_guest();
10722 	report(vmcs_read(EXI_REASON) == VMX_VMCALL,
10723 	       "%s handled by L2", exception_mnemonic(vector));
10724 
10725 	handle_exception(vector, old_handler);
10726 }
10727 
10728 static void handle_exception_in_l1(u32 vector)
10729 {
10730 	u32 old_eb = vmcs_read(EXC_BITMAP);
10731 	u32 intr_type;
10732 	u32 intr_info;
10733 
10734 	vmcs_write(EXC_BITMAP, old_eb | (1u << vector));
10735 
10736 	enter_guest();
10737 
10738 	if (vector == BP_VECTOR || vector == OF_VECTOR)
10739 		intr_type = VMX_INTR_TYPE_SOFT_EXCEPTION;
10740 	else
10741 		intr_type = VMX_INTR_TYPE_HARD_EXCEPTION;
10742 
10743 	intr_info = vmcs_read(EXI_INTR_INFO);
10744 	report((vmcs_read(EXI_REASON) == VMX_EXC_NMI) &&
10745 	       (intr_info & INTR_INFO_VALID_MASK) &&
10746 	       (intr_info & INTR_INFO_VECTOR_MASK) == vector &&
10747 	       ((intr_info & INTR_INFO_INTR_TYPE_MASK) >> INTR_INFO_INTR_TYPE_SHIFT) == intr_type,
10748 	       "%s correctly routed to L1", exception_mnemonic(vector));
10749 
10750 	vmcs_write(EXC_BITMAP, old_eb);
10751 }
10752 
10753 static void vmx_exception_test(void)
10754 {
10755 	struct vmx_exception_test *t;
10756 	int i;
10757 
10758 	for (i = 0; i < ARRAY_SIZE(vmx_exception_tests); i++) {
10759 		t = &vmx_exception_tests[i];
10760 
10761 		/*
10762 		 * Override the guest code before each run even though it's the
10763 		 * same code, the VMCS guest state needs to be reinitialized.
10764 		 */
10765 		test_override_guest(t->guest_code);
10766 		handle_exception_in_l2(t->vector);
10767 
10768 		test_override_guest(t->guest_code);
10769 		handle_exception_in_l1(t->vector);
10770 	}
10771 
10772 	test_set_guest_finished();
10773 }
10774 
10775 /*
10776  * Arbitrary canonical values for validating direct writes in the host, e.g. to
10777  * an MSR, and for indirect writes via loads from VMCS fields on VM-Exit.
10778  */
10779 #define TEST_DIRECT_VALUE 	0xff45454545000000
10780 #define TEST_VMCS_VALUE		0xff55555555000000
10781 
10782 static void vmx_canonical_test_guest(void)
10783 {
10784 	while (true)
10785 		vmcall();
10786 }
10787 
10788 static int get_host_value(u64 vmcs_field, u64 *value)
10789 {
10790 	struct descriptor_table_ptr dt_ptr;
10791 
10792 	switch (vmcs_field) {
10793 	case HOST_SYSENTER_ESP:
10794 		*value = rdmsr(MSR_IA32_SYSENTER_ESP);
10795 		break;
10796 	case HOST_SYSENTER_EIP:
10797 		*value =  rdmsr(MSR_IA32_SYSENTER_EIP);
10798 		break;
10799 	case HOST_BASE_FS:
10800 		*value =  rdmsr(MSR_FS_BASE);
10801 		break;
10802 	case HOST_BASE_GS:
10803 		*value =  rdmsr(MSR_GS_BASE);
10804 		break;
10805 	case HOST_BASE_GDTR:
10806 		sgdt(&dt_ptr);
10807 		*value =  dt_ptr.base;
10808 		break;
10809 	case HOST_BASE_IDTR:
10810 		sidt(&dt_ptr);
10811 		*value =  dt_ptr.base;
10812 		break;
10813 	case HOST_BASE_TR:
10814 		*value = get_gdt_entry_base(get_tss_descr());
10815 		/* value might not reflect the actual base if changed by VMX */
10816 		return 1;
10817 	default:
10818 		assert(0);
10819 		return 1;
10820 	}
10821 	return 0;
10822 }
10823 
10824 static int set_host_value(u64 vmcs_field, u64 value)
10825 {
10826 	struct descriptor_table_ptr dt_ptr;
10827 
10828 	switch (vmcs_field) {
10829 	case HOST_SYSENTER_ESP:
10830 		return wrmsr_safe(MSR_IA32_SYSENTER_ESP, value);
10831 	case HOST_SYSENTER_EIP:
10832 		return wrmsr_safe(MSR_IA32_SYSENTER_EIP, value);
10833 	case HOST_BASE_FS:
10834 		return wrmsr_safe(MSR_FS_BASE, value);
10835 	case HOST_BASE_GS:
10836 		/* TODO: _safe variants assume per-cpu gs base*/
10837 		wrmsr(MSR_GS_BASE, value);
10838 		return 0;
10839 	case HOST_BASE_GDTR:
10840 		sgdt(&dt_ptr);
10841 		dt_ptr.base = value;
10842 		lgdt(&dt_ptr);
10843 		return lgdt_fep_safe(&dt_ptr);
10844 	case HOST_BASE_IDTR:
10845 		sidt(&dt_ptr);
10846 		dt_ptr.base = value;
10847 		return lidt_fep_safe(&dt_ptr);
10848 	case HOST_BASE_TR:
10849 		/* Set the base and clear the busy bit */
10850 		set_gdt_entry(FIRST_SPARE_SEL, value, 0x200, 0x89, 0);
10851 		return ltr_safe(FIRST_SPARE_SEL);
10852 	default:
10853 		assert(0);
10854 	}
10855 }
10856 
10857 static void test_host_value_direct(const char *field_name, u64 vmcs_field)
10858 {
10859 	u64 value = 0;
10860 	int vector;
10861 
10862 	/*
10863 	 * Set the directly register via host ISA (e.g lgdt) and check that we
10864 	 * got no exception.
10865 	 */
10866 	vector = set_host_value(vmcs_field, TEST_DIRECT_VALUE);
10867 	if (vector) {
10868 		report_fail("Exception %d when setting %s to 0x%lx via direct write",
10869 			    vector, field_name, TEST_DIRECT_VALUE);
10870 		return;
10871 	}
10872 
10873 	/*
10874 	 * Now check that the host value matches what we expect for fields
10875 	 * that can be read back (these that we can't we assume that are correct)
10876 	 */
10877 	report(get_host_value(vmcs_field, &value) || value == TEST_DIRECT_VALUE,
10878 	       "%s: HOST value set to 0x%lx (wanted 0x%lx) via direct write",
10879 	       field_name, value, TEST_DIRECT_VALUE);
10880 }
10881 
10882 static void test_host_value_vmcs(const char *field_name, u64 vmcs_field)
10883 {
10884 	u64 value = 0;
10885 
10886 	/* Set host state field in the vmcs and do the VM entry
10887 	 * Success of VM entry already shows that L0 accepted the value
10888 	 */
10889 	vmcs_write(vmcs_field, TEST_VMCS_VALUE);
10890 	enter_guest();
10891 	skip_exit_vmcall();
10892 
10893 	/*
10894 	 * Now check that the host value matches what we expect for fields
10895 	 * that can be read back (these that we can't we assume that are correct)
10896 	 */
10897 	report(get_host_value(vmcs_field, &value) || value == TEST_VMCS_VALUE,
10898 	       "%s: HOST value set to 0x%lx (wanted 0x%lx) via VMLAUNCH/VMRESUME",
10899 	       field_name, value, TEST_VMCS_VALUE);
10900 }
10901 
10902 static void do_vmx_canonical_test_one_field(const char *field_name, u64 field)
10903 {
10904 	u64 host_org_value, field_org_value;
10905 
10906 	/* Backup the current host value and vmcs field value values */
10907 	get_host_value(field, &host_org_value);
10908 	field_org_value = vmcs_read(field);
10909 
10910 	test_host_value_direct(field_name, field);
10911 	test_host_value_vmcs(field_name, field);
10912 
10913 	/* Restore original values */
10914 	vmcs_write(field, field_org_value);
10915 	set_host_value(field, host_org_value);
10916 }
10917 
10918 #define vmx_canonical_test_one_field(field) \
10919 	do_vmx_canonical_test_one_field(#field, field)
10920 
10921 static void vmx_canonical_test(void)
10922 {
10923 	report(!(read_cr4() & X86_CR4_LA57), "4 level paging");
10924 
10925 	if (!this_cpu_has(X86_FEATURE_LA57))
10926 		test_skip("5 level paging not supported");
10927 
10928 	test_set_guest(vmx_canonical_test_guest);
10929 
10930 	vmx_canonical_test_one_field(HOST_SYSENTER_ESP);
10931 	vmx_canonical_test_one_field(HOST_SYSENTER_EIP);
10932 	vmx_canonical_test_one_field(HOST_BASE_FS);
10933 	vmx_canonical_test_one_field(HOST_BASE_GS);
10934 	vmx_canonical_test_one_field(HOST_BASE_GDTR);
10935 	vmx_canonical_test_one_field(HOST_BASE_IDTR);
10936 	vmx_canonical_test_one_field(HOST_BASE_TR);
10937 
10938 	test_set_guest_finished();
10939 }
10940 
10941 enum Vid_op {
10942 	VID_OP_SET_ISR,
10943 	VID_OP_NOP,
10944 	VID_OP_SET_CR8,
10945 	VID_OP_SELF_IPI,
10946 	VID_OP_TERMINATE,
10947 	VID_OP_SPIN,
10948 	VID_OP_SPIN_IRR,
10949 	VID_OP_HLT,
10950 };
10951 
10952 struct vmx_basic_vid_test_guest_args {
10953 	enum Vid_op op;
10954 	u8 nr;
10955 	u32 isr_exec_cnt;
10956 	u32 *virtual_apic_page;
10957 	u64 *pi_desc;
10958 	u32 dest;
10959 	bool in_guest;
10960 } vmx_basic_vid_test_guest_args;
10961 
10962 /*
10963  * From the SDM, Bit x of the VIRR is
10964  *     at bit position (x & 1FH)
10965  *     at offset (200H | ((x & E0H) >> 1)).
10966  */
10967 static void set_virr_bit(volatile u32 *virtual_apic_page, u8 nr)
10968 {
10969 	u32 page_offset = (0x200 | ((nr & 0xE0) >> 1)) / sizeof(u32);
10970 	u32 mask = 1 << (nr & 0x1f);
10971 
10972 	virtual_apic_page[page_offset] |= mask;
10973 }
10974 
10975 static void clear_virr_bit(volatile u32 *virtual_apic_page, u8 nr)
10976 {
10977 	u32 page_offset = (0x200 | ((nr & 0xE0) >> 1)) / sizeof(u32);
10978 	u32 mask = 1 << (nr & 0x1f);
10979 
10980 	virtual_apic_page[page_offset] &= ~mask;
10981 }
10982 
10983 static bool get_virr_bit(volatile u32 *virtual_apic_page, u8 nr)
10984 {
10985 	u32 page_offset = (0x200 | ((nr & 0xE0) >> 1)) / sizeof(u32);
10986 	u32 mask = 1 << (nr & 0x1f);
10987 
10988 	return virtual_apic_page[page_offset] & mask;
10989 }
10990 
10991 static void vmx_vid_test_isr(isr_regs_t *regs)
10992 {
10993 	volatile struct vmx_basic_vid_test_guest_args *args =
10994 		&vmx_basic_vid_test_guest_args;
10995 
10996 	args->isr_exec_cnt++;
10997 	barrier();
10998 	eoi();
10999 }
11000 
11001 static void vmx_basic_vid_test_guest(void)
11002 {
11003 	volatile struct vmx_basic_vid_test_guest_args *args =
11004 		&vmx_basic_vid_test_guest_args;
11005 
11006 	sti_nop();
11007 	for (;;) {
11008 		enum Vid_op op = args->op;
11009 		u8 nr = args->nr;
11010 
11011 		switch (op) {
11012 		case VID_OP_TERMINATE:
11013 			return;
11014 		case VID_OP_SET_ISR:
11015 			handle_irq(nr, vmx_vid_test_isr);
11016 			break;
11017 		case VID_OP_SET_CR8:
11018 			write_cr8(nr);
11019 			break;
11020 		case VID_OP_SELF_IPI:
11021 			vmx_x2apic_write(APIC_SELF_IPI, nr);
11022 			break;
11023 		case VID_OP_HLT:
11024 			cli();
11025 			barrier();
11026 			args->in_guest = true;
11027 			barrier();
11028 			safe_halt();
11029 			break;
11030 		case VID_OP_SPIN:
11031 			args->in_guest = true;
11032 			while (!args->isr_exec_cnt)
11033 				pause();
11034 			break;
11035 		case VID_OP_SPIN_IRR: {
11036 			u32 *virtual_apic_page = args->virtual_apic_page;
11037 			u8 nr = args->nr;
11038 
11039 			args->in_guest = true;
11040 			while (!get_virr_bit(virtual_apic_page, nr))
11041 				pause();
11042 			clear_virr_bit(virtual_apic_page, nr);
11043 			break;
11044 		}
11045 		default:
11046 			break;
11047 		}
11048 
11049 		vmcall();
11050 	}
11051 }
11052 
11053 static void set_isrs_for_vmx_basic_vid_test(void)
11054 {
11055 	volatile struct vmx_basic_vid_test_guest_args *args =
11056 		&vmx_basic_vid_test_guest_args;
11057 	u16 nr;
11058 
11059 	/*
11060 	 * kvm-unit-tests uses vector 32 for IPIs, so don't install a test ISR
11061 	 * for that vector.
11062 	 */
11063 	for (nr = 0x21; nr < 0x100; nr++) {
11064 		vmcs_write(GUEST_INT_STATUS, 0);
11065 		args->virtual_apic_page = get_vapic_page();
11066 		args->op = VID_OP_SET_ISR;
11067 		args->nr = nr;
11068 		args->isr_exec_cnt = 0;
11069 		enter_guest();
11070 		skip_exit_vmcall();
11071 	}
11072 	report(true, "Set ISR for vectors 33-255.");
11073 }
11074 
11075 static void vmx_posted_interrupts_test_worker(void *data)
11076 {
11077 	volatile struct vmx_basic_vid_test_guest_args *args =
11078 		&vmx_basic_vid_test_guest_args;
11079 
11080 	while (!args->in_guest)
11081 		pause();
11082 
11083 	test_and_set_bit(args->nr, args->pi_desc);
11084 	test_and_set_bit(256, args->pi_desc);
11085 	apic_icr_write(PI_VECTOR, args->dest);
11086 }
11087 
11088 /*
11089  * Test virtual interrupt delivery (VID) at VM-entry or TPR virtualization
11090  *
11091  * Args:
11092  *   nr: vector under test
11093  *   tpr: task priority under test
11094  *   tpr_virt: If true, then test VID during TPR virtualization. Otherwise,
11095  *       test VID during VM-entry.
11096  */
11097 static void test_basic_vid(u8 nr, u8 tpr, enum Vid_op op, u32 isr_exec_cnt_want,
11098 			   bool eoi_exit_induced)
11099 {
11100 	volatile struct vmx_basic_vid_test_guest_args *args =
11101 		&vmx_basic_vid_test_guest_args;
11102 	u16 rvi_want = isr_exec_cnt_want ? 0 : nr;
11103 	u16 int_status;
11104 
11105 	/*
11106 	 * From the SDM:
11107 	 *     IF "interrupt-window exiting" is 0 AND
11108 	 *     RVI[7:4] > VPPR[7:4] (see Section 29.1.1 for definition of VPPR)
11109 	 *             THEN recognize a pending virtual interrupt;
11110 	 *         ELSE
11111 	 *             do not recognize a pending virtual interrupt;
11112 	 *     FI;
11113 	 *
11114 	 * Thus, VPPR dictates whether a virtual interrupt is recognized.
11115 	 * However, PPR virtualization, which occurs before virtual interrupt
11116 	 * delivery, sets VPPR to VTPR, when SVI is 0.
11117 	 */
11118 	args->isr_exec_cnt = 0;
11119 	args->virtual_apic_page = get_vapic_page();
11120 	args->op = op;
11121 	args->in_guest = false;
11122 	switch (op) {
11123 	case VID_OP_SELF_IPI:
11124 		vmcs_write(GUEST_INT_STATUS, 0);
11125 		args->nr = nr;
11126 		set_vtpr(0);
11127 		break;
11128 	case VID_OP_SET_CR8:
11129 		vmcs_write(GUEST_INT_STATUS, nr);
11130 		args->nr = task_priority_class(tpr);
11131 		set_vtpr(0xff);
11132 		break;
11133 	case VID_OP_SPIN:
11134 	case VID_OP_SPIN_IRR:
11135 	case VID_OP_HLT:
11136 		vmcs_write(GUEST_INT_STATUS, 0);
11137 		args->nr = nr;
11138 		set_vtpr(tpr);
11139 		barrier();
11140 		on_cpu_async(1, vmx_posted_interrupts_test_worker, NULL);
11141 		break;
11142 	default:
11143 		vmcs_write(GUEST_INT_STATUS, nr);
11144 		set_vtpr(tpr);
11145 		break;
11146 	}
11147 
11148 	enter_guest();
11149 	if (eoi_exit_induced) {
11150 		u32 exit_cnt;
11151 
11152 		assert_exit_reason(VMX_EOI_INDUCED);
11153 		for (exit_cnt = 1; exit_cnt < isr_exec_cnt_want; exit_cnt++) {
11154 			enter_guest();
11155 			assert_exit_reason(VMX_EOI_INDUCED);
11156 		}
11157 		enter_guest();
11158 	}
11159 	skip_exit_vmcall();
11160 	TEST_ASSERT_EQ(args->isr_exec_cnt, isr_exec_cnt_want);
11161 	int_status = vmcs_read(GUEST_INT_STATUS);
11162 	TEST_ASSERT_EQ(int_status, rvi_want);
11163 }
11164 
11165 /*
11166  * Test recognizing and delivering virtual interrupts via "Virtual-interrupt
11167  * delivery" for two scenarios:
11168  *   1. When there is a pending interrupt at VM-entry.
11169  *   2. When there is a pending interrupt during TPR virtualization.
11170  */
11171 static void vmx_basic_vid_test(void)
11172 {
11173 	volatile struct vmx_basic_vid_test_guest_args *args =
11174 		&vmx_basic_vid_test_guest_args;
11175 	u8 nr_class;
11176 
11177 	if (!cpu_has_apicv()) {
11178 		report_skip("%s : Not all required APICv bits supported", __func__);
11179 		return;
11180 	}
11181 
11182 	enable_vid();
11183 	test_set_guest(vmx_basic_vid_test_guest);
11184 	set_isrs_for_vmx_basic_vid_test();
11185 
11186 	for (nr_class = 2; nr_class < 16; nr_class++) {
11187 		u16 nr;
11188 		u8 nr_sub_class;
11189 
11190 		for (nr_sub_class = 0; nr_sub_class < 16; nr_sub_class++) {
11191 			u16 tpr;
11192 
11193 			nr = (nr_class << 4) | nr_sub_class;
11194 
11195 			/*
11196 			 * Don't test the reserved IPI vector, as the test ISR
11197 			 * was not installed.
11198 			 */
11199 			if (nr == 0x20)
11200 				continue;
11201 
11202 			test_basic_vid(nr, /*tpr=*/0, VID_OP_SELF_IPI,
11203 				       /*isr_exec_cnt_want=*/1,
11204 				       /*eoi_exit_induced=*/false);
11205 			for (tpr = 0; tpr < 256; tpr++) {
11206 				u32 isr_exec_cnt_want =
11207 					task_priority_class(nr) >
11208 					task_priority_class(tpr) ? 1 : 0;
11209 
11210 				test_basic_vid(nr, tpr, VID_OP_NOP,
11211 					       isr_exec_cnt_want,
11212 					       /*eoi_exit_induced=*/false);
11213 				test_basic_vid(nr, tpr, VID_OP_SET_CR8,
11214 					       isr_exec_cnt_want,
11215 					       /*eoi_exit_induced=*/false);
11216 			}
11217 			report(true, "TPR 0-255 for vector 0x%x.", nr);
11218 		}
11219 	}
11220 
11221 	/* Terminate the guest */
11222 	args->op = VID_OP_TERMINATE;
11223 	enter_guest();
11224 	assert_exit_reason(VMX_VMCALL);
11225 }
11226 
11227 static void test_eoi_virt(u8 nr, u8 lo_pri_nr, bool eoi_exit_induced)
11228 {
11229 	u32 *virtual_apic_page = get_vapic_page();
11230 
11231 	set_virr_bit(virtual_apic_page, lo_pri_nr);
11232 	test_basic_vid(nr, /*tpr=*/0, VID_OP_NOP, /*isr_exec_cnt_want=*/2,
11233 		       eoi_exit_induced);
11234 	TEST_ASSERT(!get_virr_bit(virtual_apic_page, lo_pri_nr));
11235 	TEST_ASSERT(!get_virr_bit(virtual_apic_page, nr));
11236 }
11237 
11238 static void vmx_eoi_virt_test(void)
11239 {
11240 	volatile struct vmx_basic_vid_test_guest_args *args =
11241 		&vmx_basic_vid_test_guest_args;
11242 	u16 nr;
11243 	u16 lo_pri_nr;
11244 
11245 	if (!cpu_has_apicv()) {
11246 		report_skip("%s : Not all required APICv bits supported", __func__);
11247 		return;
11248 	}
11249 
11250 	enable_vid();  /* Note, enable_vid sets APIC_VIRT_ADDR field in VMCS. */
11251 	test_set_guest(vmx_basic_vid_test_guest);
11252 	set_isrs_for_vmx_basic_vid_test();
11253 
11254 	/* Now test EOI virtualization without induced EOI exits. */
11255 	for (nr = 0x22; nr < 0x100; nr++) {
11256 		for (lo_pri_nr = 0x21; lo_pri_nr < nr; lo_pri_nr++)
11257 			test_eoi_virt(nr, lo_pri_nr,
11258 				      /*eoi_exit_induced=*/false);
11259 
11260 		report(true, "Low priority nrs 0x21-0x%x for nr 0x%x.",
11261 		       nr - 1, nr);
11262 	}
11263 
11264 	/* Finally, test EOI virtualization with induced EOI exits. */
11265 	vmcs_write(EOI_EXIT_BITMAP0, GENMASK_ULL(63, 0));
11266 	vmcs_write(EOI_EXIT_BITMAP1, GENMASK_ULL(63, 0));
11267 	vmcs_write(EOI_EXIT_BITMAP2, GENMASK_ULL(63, 0));
11268 	vmcs_write(EOI_EXIT_BITMAP3, GENMASK_ULL(63, 0));
11269 	for (nr = 0x22; nr < 0x100; nr++) {
11270 		for (lo_pri_nr = 0x21; lo_pri_nr < nr; lo_pri_nr++)
11271 			test_eoi_virt(nr, lo_pri_nr,
11272 				      /*eoi_exit_induced=*/true);
11273 
11274 		report(true,
11275 		       "Low priority nrs 0x21-0x%x for nr 0x%x, with induced EOI exits.",
11276 		       nr - 1, nr);
11277 	}
11278 
11279 	/* Terminate the guest */
11280 	args->op = VID_OP_TERMINATE;
11281 	enter_guest();
11282 	assert_exit_reason(VMX_VMCALL);
11283 }
11284 
11285 static void vmx_posted_interrupts_test(void)
11286 {
11287 	volatile struct vmx_basic_vid_test_guest_args *args =
11288 		&vmx_basic_vid_test_guest_args;
11289 	u16 vector;
11290 	u8 class;
11291 
11292 	if (!cpu_has_apicv()) {
11293 		report_skip("%s : Not all required APICv bits supported", __func__);
11294 		return;
11295 	}
11296 
11297 	if (cpu_count() < 2) {
11298 		report_skip("%s : CPU count < 2", __func__);
11299 		return;
11300 	}
11301 
11302 	enable_vid();
11303 	enable_posted_interrupts();
11304 	args->pi_desc = get_pi_desc();
11305 	args->dest = apic_id();
11306 
11307 	test_set_guest(vmx_basic_vid_test_guest);
11308 	set_isrs_for_vmx_basic_vid_test();
11309 
11310 	for (class = 0; class < 16; class++) {
11311 		for (vector = 33; vector < 256; vector++) {
11312 			/*
11313 			 * If the vector isn't above TPR, then the vector should
11314 			 * be moved from PIR to the IRR, but never serviced.
11315 			 *
11316 			 * Only test posted interrupts to a halted vCPU if the
11317 			 * interrupt is expected to be serviced.  Otherwise, the
11318 			 * vCPU will HLT indefinitely.
11319 			 */
11320 			if (task_priority_class(vector) <= class) {
11321 				test_basic_vid(vector, class << 4,
11322 					       VID_OP_SPIN_IRR, 0, false);
11323 				continue;
11324 			}
11325 
11326 			test_basic_vid(vector, class << 4, VID_OP_SPIN, 1, false);
11327 			test_basic_vid(vector, class << 4, VID_OP_HLT, 1, false);
11328 		}
11329 	}
11330 	report(true, "Posted vectors 33-25 cross TPR classes 0-0xf, running and sometimes halted\n");
11331 
11332 	/* Terminate the guest */
11333 	args->op = VID_OP_TERMINATE;
11334 	enter_guest();
11335 }
11336 
11337 #define TEST(name) { #name, .v2 = name }
11338 
11339 /* name/init/guest_main/exit_handler/syscall_handler/guest_regs */
11340 struct vmx_test vmx_tests[] = {
11341 	{ "null", NULL, basic_guest_main, basic_exit_handler, NULL, {0} },
11342 	{ "vmenter", NULL, vmenter_main, vmenter_exit_handler, NULL, {0} },
11343 	{ "preemption timer", preemption_timer_init, preemption_timer_main,
11344 		preemption_timer_exit_handler, NULL, {0} },
11345 	{ "control field PAT", test_ctrl_pat_init, test_ctrl_pat_main,
11346 		test_ctrl_pat_exit_handler, NULL, {0} },
11347 	{ "control field EFER", test_ctrl_efer_init, test_ctrl_efer_main,
11348 		test_ctrl_efer_exit_handler, NULL, {0} },
11349 	{ "CR shadowing", NULL, cr_shadowing_main,
11350 		cr_shadowing_exit_handler, NULL, {0} },
11351 	{ "I/O bitmap", iobmp_init, iobmp_main, iobmp_exit_handler,
11352 		NULL, {0} },
11353 	{ "instruction intercept", insn_intercept_init, insn_intercept_main,
11354 		insn_intercept_exit_handler, NULL, {0} },
11355 	{ "EPT A/D disabled", ept_init, ept_main, ept_exit_handler, NULL, {0} },
11356 	{ "EPT A/D enabled", eptad_init, eptad_main, eptad_exit_handler, NULL, {0} },
11357 	{ "PML", pml_init, pml_main, pml_exit_handler, NULL, {0} },
11358 	{ "interrupt", interrupt_init, interrupt_main,
11359 		interrupt_exit_handler, NULL, {0} },
11360 	{ "nmi_hlt", nmi_hlt_init, nmi_hlt_main,
11361 		nmi_hlt_exit_handler, NULL, {0} },
11362 	{ "debug controls", dbgctls_init, dbgctls_main, dbgctls_exit_handler,
11363 		NULL, {0} },
11364 	{ "MSR switch", msr_switch_init, msr_switch_main,
11365 		msr_switch_exit_handler, NULL, {0}, msr_switch_entry_failure },
11366 	{ "vmmcall", vmmcall_init, vmmcall_main, vmmcall_exit_handler, NULL, {0} },
11367 	{ "disable RDTSCP", disable_rdtscp_init, disable_rdtscp_main,
11368 		disable_rdtscp_exit_handler, NULL, {0} },
11369 	{ "exit_monitor_from_l2_test", NULL, exit_monitor_from_l2_main,
11370 		exit_monitor_from_l2_handler, NULL, {0} },
11371 	{ "invalid_msr", invalid_msr_init, invalid_msr_main,
11372 		invalid_msr_exit_handler, NULL, {0}, invalid_msr_entry_failure},
11373 	/* Basic V2 tests. */
11374 	TEST(v2_null_test),
11375 	TEST(v2_multiple_entries_test),
11376 	TEST(fixture_test_case1),
11377 	TEST(fixture_test_case2),
11378 	/* Opcode tests. */
11379 	TEST(invvpid_test),
11380 	/* VM-entry tests */
11381 	TEST(vmx_controls_test),
11382 	TEST(vmx_host_state_area_test),
11383 	TEST(vmx_guest_state_area_test),
11384 	TEST(vmentry_movss_shadow_test),
11385 	TEST(vmentry_unrestricted_guest_test),
11386 	/* APICv tests */
11387 	TEST(vmx_eoi_bitmap_ioapic_scan_test),
11388 	TEST(vmx_hlt_with_rvi_test),
11389 	TEST(apic_reg_virt_test),
11390 	TEST(virt_x2apic_mode_test),
11391 	TEST(vmx_basic_vid_test),
11392 	TEST(vmx_eoi_virt_test),
11393 	TEST(vmx_posted_interrupts_test),
11394 	/* APIC pass-through tests */
11395 	TEST(vmx_apic_passthrough_test),
11396 	TEST(vmx_apic_passthrough_thread_test),
11397 	TEST(vmx_apic_passthrough_tpr_threshold_test),
11398 	TEST(vmx_init_signal_test),
11399 	TEST(vmx_sipi_signal_test),
11400 	/* VMCS Shadowing tests */
11401 	TEST(vmx_vmcs_shadow_test),
11402 	/* Regression tests */
11403 	TEST(vmx_ldtr_test),
11404 	TEST(vmx_cr_load_test),
11405 	TEST(vmx_cr4_osxsave_test),
11406 	TEST(vmx_no_nm_test),
11407 	TEST(vmx_db_test),
11408 	TEST(vmx_nmi_window_test),
11409 	TEST(vmx_intr_window_test),
11410 	TEST(vmx_pending_event_test),
11411 	TEST(vmx_pending_event_hlt_test),
11412 	TEST(vmx_store_tsc_test),
11413 	TEST(vmx_preemption_timer_zero_test),
11414 	TEST(vmx_preemption_timer_tf_test),
11415 	TEST(vmx_preemption_timer_expiry_test),
11416 	/* EPT access tests. */
11417 	TEST(ept_access_test_not_present),
11418 	TEST(ept_access_test_read_only),
11419 	TEST(ept_access_test_write_only),
11420 	TEST(ept_access_test_read_write),
11421 	TEST(ept_access_test_execute_only),
11422 	TEST(ept_access_test_read_execute),
11423 	TEST(ept_access_test_write_execute),
11424 	TEST(ept_access_test_read_write_execute),
11425 	TEST(ept_access_test_reserved_bits),
11426 	TEST(ept_access_test_ignored_bits),
11427 	TEST(ept_access_test_paddr_not_present_ad_disabled),
11428 	TEST(ept_access_test_paddr_not_present_ad_enabled),
11429 	TEST(ept_access_test_paddr_read_only_ad_disabled),
11430 	TEST(ept_access_test_paddr_read_only_ad_enabled),
11431 	TEST(ept_access_test_paddr_read_write),
11432 	TEST(ept_access_test_paddr_read_write_execute),
11433 	TEST(ept_access_test_paddr_read_execute_ad_disabled),
11434 	TEST(ept_access_test_paddr_read_execute_ad_enabled),
11435 	TEST(ept_access_test_paddr_not_present_page_fault),
11436 	TEST(ept_access_test_force_2m_page),
11437 	/* Atomic MSR switch tests. */
11438 	TEST(atomic_switch_max_msrs_test),
11439 	TEST(atomic_switch_overflow_msrs_test),
11440 	TEST(rdtsc_vmexit_diff_test),
11441 	TEST(vmx_mtf_test),
11442 	TEST(vmx_mtf_pdpte_test),
11443 	TEST(vmx_pf_exception_test),
11444 	TEST(vmx_pf_exception_forced_emulation_test),
11445 	TEST(vmx_pf_no_vpid_test),
11446 	TEST(vmx_pf_invvpid_test),
11447 	TEST(vmx_pf_vpid_test),
11448 	TEST(vmx_exception_test),
11449 	TEST(vmx_canonical_test),
11450 	{ NULL, NULL, NULL, NULL, NULL, {0} },
11451 };
11452