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