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