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