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